跳到正文

剪贴板

剪贴板 hvbm14aa

Lemon_eggplant
原文
剪贴板信息

剪贴板信息

发布
收录
更新
JavaScript
// ==UserScript==
// @name         洛谷提交记录显示优化
// @namespace    https://github.com/chenyuxuan2009/luogu_submission_better
// @version      2.22
// @description  修改提交记录背景
// @author       沉石鱼惊旋
// @match        *://www.luogu.com.cn/record/*
// @match        *://www.luogu.com.cn/
// @match        *://www.luogu.com.cn/*
// @run-at       document-end
// @grant        GM_registerMenuCommand
// @grant        GM_setValue
// @grant        GM_getValue
// @license      MIT
// @downloadURL https://update.greasyfork.org/scripts/530997/%E6%B4%9B%E8%B0%B7%E6%8F%90%E4%BA%A4%E8%AE%B0%E5%BD%95%E6%98%BE%E7%A4%BA%E4%BC%98%E5%8C%96.user.js
// @updateURL https://update.greasyfork.org/scripts/530997/%E6%B4%9B%E8%B0%B7%E6%8F%90%E4%BA%A4%E8%AE%B0%E5%BD%95%E6%98%BE%E7%A4%BA%E4%BC%98%E5%8C%96.meta.js
// ==/UserScript==

let opacity = localStorage.getItem("opacity") || 0.3;
let replaceSidebarStatus = localStorage.getItem("replaceSidebarStatus") || "1";

const jsdelivrOptions = [
    'https://cdn.jsdelivr.net',
    'https://testingcf.jsdelivr.net',
    'https://jsdelivrcn.netlify.app',
    'https://cdn.mengze.vip',
    'https://cdn.bili33.top',
    'https://www.jsdmirror.com',
];

const themeOptions = [
    'nailoong',
    'andy',
    'qqemoji',
    'qqsuperemoji',
    'mixed1',
    'theresa'
];

const themeLabels = {
    "nailoong": "奶龙",
    "andy": "安梦梦",
    "qqemoji": "QQ 大表情",
    "qqsuperemoji": "QQ 超级表情",
    "mixed1": "混搭 1",
    "theresa": "特蕾西娅"
};

const themeTypes = {
    "nailoong": "gif",
    "andy": "gif",
    "qqemoji": "gif",
    "qqsuperemoji": "gif",
    "mixed1": "gif",
    "theresa": "png"
};

let jsdelivr = localStorage.getItem("jsdelivr") || 'https://cdn.jsdelivr.net';
let theme = localStorage.getItem("theme") || 'nailoong';

function getImage(theme, x) {
    return themeOptions.includes(theme)
        ? `${jsdelivr}/gh/chenyuxuan2009/luogu_submission_better/theme/${theme}/${x}.${themeTypes[theme]}`
        : localStorage.getItem(`${x}`);
}

const statusKeys = [
    "AC",
    "WA",
    "TLE",
    "MLE",
    "RE",
    "OLE",
    "UKE",
    "Judging",
    "CE",
    "Waiting",
    "Unshown"
];

const statusLabels = {
    "AC": "AC 图片 URL",
    "WA": "WA 图片 URL",
    "TLE": "TLE 图片 URL",
    "MLE": "MLE 图片 URL",
    "RE": "RE 图片 URL",
    "OLE": "OLE 图片 URL",
    "UKE": "UKE 图片 URL",
    "Judging": "Judging 图片 URL",
    "CE": "CE 图片 URL",
    "Waiting": "Waiting 图片 URL",
    "Unshown": "Unshown 图片 URL"
};

const AC = getImage(theme, 'AC');
const WA = getImage(theme, 'WA');
const TLE = getImage(theme, 'TLE');
const MLE = getImage(theme, 'MLE');
const RE = getImage(theme, 'RE');
const OLE = getImage(theme, 'OLE');
const UKE = getImage(theme, 'UKE');
const Judging = getImage(theme, 'Judging');
const CE = getImage(theme, 'CE');
const Waiting = getImage(theme, 'Waiting');
const Unshown = getImage(theme, 'Unshown');

const ACcol = `rgba(82, 196, 26, ${opacity})`;
const WAcol = `rgba(231, 76, 60, ${opacity})`;
const TLEcol = `rgba(5, 34, 66, ${opacity})`;
const MLEcol = `rgba(5, 34, 66, ${opacity})`;
const REcol = `rgba(157, 61, 207, ${opacity})`;
const OLEcol = `rgba(5, 34, 66, ${opacity})`;
const UKEcol = `rgba(14, 29, 105, ${opacity})`;
const Judgingcol = `rgba(20, 85, 143, ${opacity})`;
const CEcol = `rgba(250, 219, 20, ${opacity})`;
const Waitingcol = `rgba(20, 85, 143, ${opacity})`;
const Unshowncol = `rgba(38, 38, 38, ${opacity})`;

const sta = [
    AC,
    WA,
    TLE,
    MLE,
    RE,
    OLE,
    UKE,
    Judging,
    CE,
    Waiting,
    Unshown
];

const col = [
    ACcol,
    WAcol,
    TLEcol,
    MLEcol,
    REcol,
    OLEcol,
    UKEcol,
    Judgingcol,
    CEcol,
    Waitingcol,
    Unshowncol
];

const txt = [
    "AC",
    "WA",
    "TLE",
    "MLE",
    "RE",
    "OLE",
    "UKE",
    "Judging",
    "CE",
    "WJ",
    "US"
];

/*
 * 缓存背景字符串。
 * 原脚本每次扫描都会重新拼接字符串,现在只生成一次。
 */
const backgroundCache = [];

function getBackground(x) {
    if (x < 0 || x >= sta.length) return "";

    if (!backgroundCache[x]) {
        backgroundCache[x] =
            `linear-gradient(${col[x]}, ${col[x]}), url('${sta[x]}')`;
    }

    return backgroundCache[x];
}

function getCol(x) {
    return `background: ${getBackground(x)}; background-size: cover;`;
}

/*
 * 状态文本 → 状态编号
 */
function getStatusIndex(status) {
    if (!status) return -1;

    status = status.trim();

    if (status === "AC") return 0;
    if (status === "WA") return 1;
    if (status === "TL" || status === "TLE") return 2;
    if (status === "ML" || status === "MLE") return 3;
    if (status === "RE") return 4;
    if (status === "OL" || status === "OLE") return 5;
    if (status === "UK" || status === "UKE") return 6;

    return -1;
}

/*
 * 设置 test-case 背景。
 *
 * 不再使用:
 *     tc[i].style = ...
 *
 * 因为这会直接覆盖整个 style 属性。
 */
function setTestCaseBackground(node, statusIndex) {
    if (!node || statusIndex < 0) return;

    const background = getBackground(statusIndex);

    if (node.dataset.luoguSubmissionBetterBg === background) {
        return;
    }

    node.dataset.luoguSubmissionBetterBg = background;

    node.style.setProperty(
        "background",
        background,
        "important"
    );

    node.style.setProperty(
        "background-size",
        "cover",
        "important"
    );

    node.style.setProperty(
        "background-position",
        "center",
        "important"
    );

    node.style.setProperty(
        "background-repeat",
        "no-repeat",
        "important"
    );
}

/*
 * 找到提交记录中的 test-case。
 */
function getTestCases() {
    return document.getElementsByClassName("test-case");
}

/*
 * 找到右侧「评测状态」。
 */
function getSidebarStatusInfo() {
    const doc = document.querySelector("div.info-rows");

    if (!doc) return null;

    for (let i = 0; i < doc.children.length; i += 1) {
        const row = doc.children[i];

        if (
            row.children[0] &&
            row.children[0].children[0] &&
            row.children[0].children[0].textContent.includes("评测状态")
        ) {
            return row.children[1] || null;
        }
    }

    return null;
}

/*
 * 更新右侧栏状态。
 *
 * 只有状态真正变化的时候才重新写 innerHTML。
 */
function updateSidebarStatus(info, firstSTA) {
    if (!info || firstSTA < 0) return;

    const current = info.dataset.luoguSubmissionBetterStatus || "";

    if (current === String(firstSTA)) {
        return;
    }

    const background = getBackground(firstSTA);

    if (firstSTA === 7) {
        info.innerHTML = `
            <div
                data-v-21e0a7cc=""
                class="test-case"
                style="background: ${background}; background-size: cover;"
                id="luogu_submission_better_right_row"
            >
                <div data-v-21e0a7cc="" class="content">
                    <div
                        data-v-bbdab89a=""
                        data-v-21e0a7cc=""
                        class="spinner"
                        style="width: 32px; height: 32px;"
                    >
                        <div
                            data-v-bbdab89a=""
                            style="width: 32px; height: 32px; border-width: 2px;"
                        ></div>
                    </div>
                </div>
            </div>
        `;
    } else {
        info.innerHTML = `
            <div
                data-v-21e0a7cc=""
                class="test-case"
                style="background: ${background}; background-size: cover;"
                id="luogu_submission_better_right_row"
            >
                <div data-v-21e0a7cc="" class="content">
                    <div data-v-21e0a7cc="" class="status">
                        ${txt[firstSTA]}
                    </div>
                </div>
            </div>
        `;
    }

    info.dataset.luoguSubmissionBetterStatus = String(firstSTA);
}

/*
 * 防止 MutationObserver 因为我们自己修改右侧栏而重复触发。
 */
let updatingSidebar = false;

/*
 * 核心函数。
 *
 * 相比原版:
 * 1. 不读取 innerHTML
 * 2. 不重复 getElementsByClassName
 * 3. 不覆盖整个 style
 * 4. 相同背景不重复写
 * 5. 只在真正需要时修改右侧栏
 */
function subBetter() {
    if (updatingSidebar) return;

    const tc = getTestCases();
    const len = tc.length;

    if (!len) return;

    let firstSTA = -1;
    let ac = 0;
    let judging = 0;

    for (let i = 0; i < len; i += 1) {
        const node = tc[i];

        if (node.id === "luogu_submission_better_right_row") {
            continue;
        }

        /*
         * 原版通过 innerHTML.includes("spinner")
         * 判断是否正在评测。
         *
         * 改成 querySelector,避免把整个 HTML 字符串取出来。
         */
        if (node.querySelector(".spinner")) {
            judging = 1;
            setTestCaseBackground(node, 7);
            continue;
        }

        const statusNode = node.querySelector(".status");

        if (!statusNode) continue;

        const status = statusNode.textContent.trim();
        const tmpSTA = getStatusIndex(status);

        if (tmpSTA === -1) continue;

        setTestCaseBackground(node, tmpSTA);

        if (tmpSTA === 0) {
            ac = 1;
        }

        if (tmpSTA !== 0 && firstSTA === -1) {
            firstSTA = tmpSTA;
        }
    }

    if (judging) {
        firstSTA = 7;
    }

    if (firstSTA === -1 && ac) {
        firstSTA = 0;
    }

    if (replaceSidebarStatus !== "1") {
        return;
    }

    const info = getSidebarStatusInfo();

    if (!info) return;

    const infoText = info.textContent || "";

    if (infoText.includes("Judging")) {
        firstSTA = 7;
    } else if (infoText.includes("Compile Error")) {
        firstSTA = 8;
    } else if (infoText.includes("Unknown Error")) {
        firstSTA = 6;
    } else if (infoText.includes("Waiting")) {
        firstSTA = 9;
    } else if (infoText.includes("Unshown")) {
        firstSTA = 10;
    }

    if (firstSTA === -1) return;

    updatingSidebar = true;

    updateSidebarStatus(info, firstSTA);

    updatingSidebar = false;
}

/*
 * ============================================================
 * 提交记录页面优化刷新器
 * ============================================================
 *
 * 原版:
 *
 * setInterval(subBetter, 10);
 *
 * 即:
 *
 * 每秒 100 次
 * ×
 * 每次扫描全部 test-case
 *
 * 对液态玻璃页面非常不友好。
 *
 * 现在:
 *
 * DOM 有变化 → 防抖更新
 * 没变化 → 不扫描
 * 另外每 800ms 做一次极低频兜底
 */

let updateTimer = null;
let fallbackTimer = null;
let recordObserver = null;
let observedRoot = null;

function scheduleSubBetter(delay = 80) {
    if (updateTimer !== null) return;

    updateTimer = setTimeout(function () {
        updateTimer = null;
        subBetter();
    }, delay);
}

/*
 * 找到最适合观察的 DOM 容器。
 *
 * 优先观察 test-case 的父节点,
 * 避免直接观察整个 body。
 */
function findObserveRoot() {
    const first = document.querySelector(
        ".test-case:not(#luogu_submission_better_right_row)"
    );

    if (!first) return null;

    return first.parentElement || null;
}

function setupRecordObserver() {
    if (recordObserver) return;

    const root = findObserveRoot();

    if (!root) return;

    observedRoot = root;

    recordObserver = new MutationObserver(function (mutations) {
        if (updatingSidebar) return;

        /*
         * 只要真的有 childList 变化就安排一次更新。
         *
         * 多次 Mutation 会被 scheduleSubBetter 合并。
         */
        for (let i = 0; i < mutations.length; i += 1) {
            if (mutations[i].type === "childList") {
                scheduleSubBetter(80);
                break;
            }
        }
    });

    recordObserver.observe(root, {
        childList: true,
        subtree: true
    });
}

/*
 * 由于洛谷是 Vue SPA,页面可能在我们建立 Observer
 * 后重新创建整个提交记录区域。
 *
 * 因此使用 800ms 低频检查。
 *
 * 这和原来的 10ms 有数量级区别:
 *
 * 100 次/秒 → 1.25 次/秒
 */
function startRecordFallback() {
    if (fallbackTimer !== null) return;

    fallbackTimer = setInterval(function () {
        if (!/^https:\/\/www\.luogu\.com\.cn\/record\/\d+$/.test(window.location.href)) {
            return;
        }

        const root = findObserveRoot();

        if (root && root !== observedRoot) {
            if (recordObserver) {
                recordObserver.disconnect();
                recordObserver = null;
            }

            setupRecordObserver();
        }

        scheduleSubBetter(0);
    }, 800);
}

/*
 * ============================================================
 * 设置面板
 * ============================================================
 */

function addButton() {
    /*
     * 防止 SPA / 脚本重复执行导致按钮重复。
     */
    if (document.getElementById("pluginSettingsBtn")) {
        return;
    }

    function createSettingsPopup() {
        /*
         * 如果已经存在弹窗,避免重复创建。
         */
        if (document.getElementById("settingsPopup")) return;

        const popup = document.createElement("div");

        popup.id = "settingsPopup";

        popup.innerHTML = `
            <div class="popup-header">
                <span>插件设置</span>
                <button id="closePopup">✖</button>
            </div>

            <p>调整纯色背景的透明度:</p>

            <input
                type="number"
                id="opacityInput"
                min="0"
                max="1"
                step="0.1"
                value="${localStorage.getItem("opacity") || 0.3}"
            >

            <button id="saveOpacity">
                保存透明度设置
            </button>

            <p>
                选择 jsdelivr 源服务器:<br>
                (只适用官方主题)
            </p>

            <select id="jsdelivrSelect">
                ${jsdelivrOptions.map(option => `
                    <option
                        value="${option}"
                        ${option === jsdelivr ? "selected" : ""}
                    >
                        ${option}
                    </option>
                `).join("")}

                <option
                    value="custom"
                    ${!jsdelivrOptions.includes(jsdelivr) ? "selected" : ""}
                >
                    自定义
                </option>
            </select>

            <input
                type="text"
                id="customJsdelivr"
                placeholder="输入自定义地址"
                ${
                    !jsdelivrOptions.includes(jsdelivr)
                        ? `value="${jsdelivr}" style="display:block;"`
                        : `style="display:none;"`
                }
            >

            <button id="saveJsdelivr">
                保存 jsdelivr 设置
            </button>

            <p>选择主题:</p>

            <select id="themeSelect">
                ${themeOptions.map(option => `
                    <option
                        value="${option}"
                        ${option === theme ? "selected" : ""}
                    >
                        ${option}
                        (${themeLabels[option]})
                        (${themeTypes[option] === "gif" ? "动图" : "静图"})
                    </option>
                `).join("")}

                <option
                    value="custom"
                    ${!themeOptions.includes(theme) ? "selected" : ""}
                >
                    自定义
                </option>
            </select>

            <div
                id="customThemeInputs"
                style="display: ${
                    !themeOptions.includes(theme) ? "block" : "none"
                };"
            >
                ${statusKeys.map(key => `
                    <input
                        type="text"
                        id="${key}"
                        placeholder="输入 ${statusLabels[key]}"
                        value="${
                            localStorage.getItem(key) ||
                            getImage(theme, key)
                        }"
                    >
                `).join("")}
            </div>

            <button id="saveTheme">
                保存主题设置
            </button>

            <p>替换右侧栏评测状态:</p>

            <select id="replaceSidebarStatus">
                <option
                    value="1"
                    ${replaceSidebarStatus === "1" ? "selected" : ""}
                >
                    是
                </option>

                <option
                    value="0"
                    ${replaceSidebarStatus === "0" ? "selected" : ""}
                >
                    否
                </option>
            </select>

            <button id="saveReplaceSidebarStatus">
                保存状态设置
            </button>
        `;

        /*
         * 样式只创建一次。
         */
        let style = document.getElementById(
            "luoguSubmissionBetterSettingsStyle"
        );

        if (!style) {
            style = document.createElement("style");

            style.id = "luoguSubmissionBetterSettingsStyle";

            style.textContent = `
#settingsPopup {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 300px;
    background: white;
    border: 1px solid #ccc;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    padding: 20px;
    z-index: 9999;
    border-radius: 8px;
    text-align: center;
    font-family: Arial, sans-serif;
    max-height: 80vh;
    overflow-y: auto;
}

#settingsPopup .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 16px;
    font-weight: bold;
    border-bottom: 1px solid #ccc;
    padding-bottom: 8px;
    margin-bottom: 10px;
}

#settingsPopup #closePopup {
    background: none;
    border: none;
    cursor: pointer;
    font-size: 18px;
}

#settingsPopup input,
#settingsPopup select {
    width: 100%;
    padding: 5px;
    margin: 5px 0;
    border-radius: 5px;
    border: 1px solid #ccc;
    box-sizing: border-box;
    text-align: center;
}

#settingsPopup button:not(.popup-header button) {
    background: #007bff;
    color: white;
    border: none;
    padding: 8px 12px;
    cursor: pointer;
    border-radius: 5px;
    width: 100%;
}

#settingsPopup button:not(.popup-header button):hover {
    background: #0056b3;
}
`;

            document.head.appendChild(style);
        }

        document.body.appendChild(popup);

        /*
         * 保存透明度
         */
        document
            .getElementById("saveOpacity")
            .addEventListener("click", function () {
                const value =
                    document.getElementById("opacityInput").value;

                if (
                    value === "" ||
                    Number(value) < 0 ||
                    Number(value) > 1
                ) {
                    alert("请输入 0~1 之间的数");
                    return;
                }

                localStorage.setItem("opacity", value);

                alert(`设置已保存:透明度 = ${value}`);
            });

        /*
         * jsdelivr 自定义地址
         */
        document
            .getElementById("jsdelivrSelect")
            .addEventListener("change", function () {
                const customInput =
                    document.getElementById("customJsdelivr");

                customInput.style.display =
                    this.value === "custom"
                        ? "block"
                        : "none";
            });

        document
            .getElementById("saveJsdelivr")
            .addEventListener("click", function () {
                const selected =
                    document.getElementById("jsdelivrSelect").value;

                const newJsdelivr =
                    selected === "custom"
                        ? document
                            .getElementById("customJsdelivr")
                            .value
                            .trim()
                        : selected;

                if (!newJsdelivr) {
                    alert("请输入有效的 jsdelivr 地址");
                    return;
                }

                localStorage.setItem(
                    "jsdelivr",
                    newJsdelivr
                );

                alert(
                    `设置已保存:jsdelivr 源 = ${newJsdelivr}`
                );
            });

        /*
         * 主题选择
         */
        document
            .getElementById("themeSelect")
            .addEventListener("change", function () {
                document.getElementById(
                    "customThemeInputs"
                ).style.display =
                    this.value === "custom"
                        ? "block"
                        : "none";
            });

        /*
         * 保存主题
         */
        document
            .getElementById("saveTheme")
            .addEventListener("click", function () {
                const selected =
                    document.getElementById("themeSelect").value;

                const newTheme =
                    selected === "custom"
                        ? "custom"
                        : selected;

                if (newTheme === "custom") {
                    const missingFields =
                        statusKeys.filter(key => {
                            const input =
                                document.getElementById(key);

                            return (
                                !input ||
                                !input.value.trim()
                            );
                        });

                    if (missingFields.length > 0) {
                        alert(
                            "请填写所有图片的完整 URL!"
                        );
                        return;
                    }

                    statusKeys.forEach(key => {
                        localStorage.setItem(
                            key,
                            document
                                .getElementById(key)
                                .value
                                .trim()
                        );
                    });
                }

                localStorage.setItem(
                    "theme",
                    newTheme
                );

                alert(
                    `设置已保存:主题 = ${
                        newTheme === "custom"
                            ? "自定义"
                            : newTheme +
                              "(" +
                              themeLabels[newTheme] +
                              ")"
                    }`
                );
            });

        /*
         * 右侧栏状态
         */
        document
            .getElementById("saveReplaceSidebarStatus")
            .addEventListener("click", function () {
                const value =
                    document.getElementById(
                        "replaceSidebarStatus"
                    ).value;

                localStorage.setItem(
                    "replaceSidebarStatus",
                    value
                );

                alert(
                    `设置已保存:${
                        value === "1"
                            ? "替换"
                            : "不替换"
                    } 右侧栏评测状态`
                );
            });

        /*
         * 关闭
         */
        document
            .getElementById("closePopup")
            .addEventListener("click", function () {
                popup.remove();
            });
    }

    /*
     * 找到洛谷侧边栏。
     */
    const sidebar =
        document.querySelector(
            ".nav-group.on-expand ul"
        );

    if (!sidebar) return;

    /*
     * 防止重复。
     */
    if (
        document.getElementById(
            "pluginSettingsBtn"
        )
    ) {
        return;
    }

    const li =
        document.createElement("li");

    li.setAttribute(
        "data-v-40281d0d",
        ""
    );

    li.setAttribute(
        "data-v-6c9e83f4",
        ""
    );

    li.title = "插件设置";

    li.innerHTML = `
        <a
            data-v-12b24cc3=""
            data-v-40281d0d=""
            href="#"
            disabled="false"
            id="pluginSettingsBtn"
        >
            <span
                data-v-40281d0d=""
                class="title minor"
            >
                插件设置
            </span>
        </a>
    `;

    sidebar.appendChild(li);

    document
        .getElementById("pluginSettingsBtn")
        .addEventListener(
            "click",
            function (event) {
                event.preventDefault();
                createSettingsPopup();
            }
        );
}

/*
 * ============================================================
 * 启动
 * ============================================================
 */

(function () {
    "use strict";

    const isRecordPage =
        /^https:\/\/www\.luogu\.com\.cn\/record\/\d+$/
            .test(window.location.href);

    if (isRecordPage) {
        /*
         * 第一次立即处理。
         */
        scheduleSubBetter(0);

        /*
         * 等 Vue 把提交记录 DOM 建出来以后建立 Observer。
         */
        const observerTimer = setInterval(function () {
            setupRecordObserver();

            if (recordObserver) {
                clearInterval(observerTimer);
            }
        }, 200);

        /*
         * 低频兜底。
         */
        startRecordFallback();
    }

    /*
     * 原脚本也是 1 秒后添加按钮。
     */
    setTimeout(function () {
        addButton();
    }, 1000);
})();