luogu better

· · 个人记录

// ==UserScript==
// @name         Luogu Better
// @namespace    https://github.com/yourname/luogu-better
// @version      1.3.0
// @description  在洛谷题目页跳转 VJudge 题库
// @author       You
// @match        https://www.luogu.com.cn/problem/*
// @match        https://www.luogu.com/problem/*
// @noframes
// @grant        none
// @run-at       document-end
// ==/UserScript==

(function () {
    'use strict';

    const TAG = '[LGB v1.3]';
    const NS = '__LUOGU_BETTER_NS__';
    const PANEL_ATTR = 'data-lgb-panel';
    const log = (...a) => console.log(TAG, ...a);

    if (window.self !== window.top) return;

    // 单例:干掉旧实例
    const prev = window[NS];
    if (prev) {
        try { if (prev.intervalId) clearInterval(prev.intervalId); } catch (e) {}
        try { if (prev.urlPoller) clearInterval(prev.urlPoller); } catch (e) {}
        try { if (prev.panelRef && prev.panelRef.parentNode) prev.panelRef.remove(); } catch (e) {}
    }
    const state = {
        intervalId: null,
        urlPoller: null,
        panelRef: null,
        lastUrl: location.href,
    };
    window[NS] = state;

    log('启动', location.href);

    // ============ 从 URL 提取洛谷题号 ============
    // 要求首字符大写字母,排除 list 等小写路径
    // 匹配:P1001 / B2001 / T1234 / U123456 / SP1234 / CF1361B / AT_abc123_a
    // 排除:list / solution/xxx / 其他小写路径
    const getPid = () => {
        const m = location.pathname.match(/^\/problem\/([A-Z][A-Za-z0-9_]*)\/?$/);
        return m ? m[1] : null;
    };

    // ============ 洛谷题号 → VJudge 题库 ID ============
    //   P1001        →  洛谷-P1001
    //   B2001        →  洛谷-B2001
    //   AT_abc123_a  →  AtCoder-abc123_a
    //   CF1361B      →  CodeForces-1361B
    const pidToVjudgeName = (pid) => {
        if (/^AT_/i.test(pid)) {
            return 'AtCoder-' + pid.slice(3).toLowerCase();
        }
        if (/^CF/i.test(pid)) {
            return 'CodeForces-' + pid.slice(2);
        }
        return '洛谷-' + pid;
    };

    const buildVjudgeUrl = (pid) => {
        return 'https://vjudge.net/problem/' + encodeURIComponent(pidToVjudgeName(pid));
    };

    // ============ 面板 UI ============
    const makeBtn = (label, url, color, title) => {
        const a = document.createElement('a');
        a.textContent = label;
        a.title = title || '';
        a.href = url;
        a.target = '_blank';
        a.rel = 'noopener noreferrer';
        a.style.cssText = `display:block;padding:5px 14px;margin:0;border-radius:14px;
            color:#fff;text-decoration:none;font-weight:600;font-size:12.5px;
            text-align:center;transition:transform .15s,opacity .15s;
            background:${color};box-shadow:0 2px 6px rgba(0,0,0,.2);cursor:pointer;`;
        a.addEventListener('mouseenter', () => { a.style.transform = 'translateX(-3px)'; a.style.opacity = '0.9'; });
        a.addEventListener('mouseleave', () => { a.style.transform = ''; a.style.opacity = '1'; });
        return a;
    };

    const createPanel = (pid) => {
        const p = document.createElement('div');
        p.setAttribute(PANEL_ATTR, 'panel');
        p.style.cssText = `position:fixed;top:80px;right:20px;z-index:2147483647;
            display:flex;flex-direction:column;padding:6px;border-radius:10px;
            background:rgba(255,255,255,.96);box-shadow:0 4px 14px rgba(0,0,0,.18);
            font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;
            min-width:84px;pointer-events:auto;`;

        const vjName = pidToVjudgeName(pid);
        p.appendChild(makeBtn('VJudge', buildVjudgeUrl(pid), '#5cb85c', `在 VJudge 打开 ${vjName}`));
        return p;
    };

    // ============ 清理旧面板 ============
    const purgeLegacy = (keep) => {
        document.querySelectorAll(`[${PANEL_ATTR}]`).forEach(el => {
            if (el === keep || (keep && keep.contains(el))) return;
            el.remove();
        });
    };

    const removePanel = () => {
        if (state.panelRef && state.panelRef.parentNode) state.panelRef.remove();
        state.panelRef = null;
    };

    // ============ 渲染 ============
    let lastPid = null;

    const render = () => {
        if (window[NS] !== state) {
            clearInterval(state.intervalId);
            clearInterval(state.urlPoller);
            removePanel();
            return;
        }

        const pid = getPid();
        if (!pid) {
            if (state.panelRef) {
                removePanel();
                lastPid = null;
                log('不在题目页,已移除面板');
            }
            return;
        }

        purgeLegacy(state.panelRef);

        if (lastPid === pid && state.panelRef && state.panelRef.parentNode) {
            return;
        }

        removePanel();
        const panel = createPanel(pid);
        document.body.appendChild(panel);
        state.panelRef = panel;
        lastPid = pid;
        log('面板已创建:', pid, '→', pidToVjudgeName(pid));
    };

    const tick = () => { try { render(); } catch (e) { log('异常:', e); } };

    // ============ 启动 ============
    tick();
    state.intervalId = setInterval(tick, 800);

    state.urlPoller = setInterval(() => {
        if (location.href !== state.lastUrl) {
            state.lastUrl = location.href;
            lastPid = null;
            tick();
        }
    }, 200);

    window.addEventListener('popstate', () => {
        lastPid = null;
        tick();
    });

})();