vjudge beetter

· · 个人记录

// ==UserScript==
// @name         VJudge Better
// @namespace    https://github.com/yourname/vjudge-better
// @version      9.1.0
// @description  VJudge 题库页给洛谷链接;比赛页给原 OJ + 洛谷 + VJudge
// @author       You
// @match        https://vjudge.net/*
// @match        https://cn.vjudge.net/*
// @noframes
// @grant        none
// @run-at       document-end
// ==/UserScript==

(function () {
    'use strict';

    const TAG = '[VJB v9.1]';
    const NS = '__VJ_BETTER_NS__';
    const MY_VERSION = '9.1.0';
    const PANEL_ATTR = 'data-vjb-v91';
    const CACHE_KEY = 'vjb_origin_v26';
    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) {}
        try { if (prev.hostRef && prev.hostRef.parentNode) prev.hostRef.remove(); } catch (e) {}
    }
    for (let i = 90; i >= 24; i--) {
        try { window['__VJB_V' + i + '__'] = false; } catch (e) {}
    }
    try { window.__VJB_V3__ = false; } catch (e) {}

    const state = {
        version: MY_VERSION,
        intervalId: null,
        urlPoller: null,
        panelRef: null,
        hostRef: null,
        lastUrl: location.href,
        originCache: {},
        pendingOrigin: new Set(),
    };
    window[NS] = state;

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

    // ============ OJ 判断 ============
    const ojKey = (oj) => String(oj).toLowerCase().replace(/\s+/g, '');
    const isLuogu = (o) => ['洛谷', 'luogu', 'lg'].includes(o);
    const isCF = (o) => ['codeforces', 'cf', 'codeforce'].includes(o);
    const isAT = (o) => ['atcoder', 'at', 'atc'].includes(o);

    const ojLabel = (oj) => {
        const o = ojKey(oj);
        if (isLuogu(o)) return '洛谷';
        if (isCF(o)) return 'CF';
        if (isAT(o)) return 'AtCoder';
        return oj;
    };
    const ojColor = (oj) => {
        const o = ojKey(oj);
        if (isLuogu(o)) return '#0e639c';
        if (isCF(o)) return '#d9534f';
        if (isAT(o)) return '#5cb85c';
        return '#888';
    };

    // ============ 洛谷链接 ============
    const buildLuoguLink = (oj, probNum) => {
        const o = ojKey(oj);
        const n = String(probNum).trim();
        if (!n) return null;
        if (isLuogu(o)) return `https://www.luogu.com.cn/problem/${n}`;
        if (isAT(o)) {
            const id = n.toLowerCase();
            return `https://www.luogu.com.cn/problem/AT_${id}`;
        }
        if (isCF(o)) {
            if (/^gym[-_]?/i.test(n)) return null;
            return `https://www.luogu.com.cn/problem/CF${n.toUpperCase()}`;
        }
        return null;
    };

    // ============ VJudge 题库链接 ============
    const buildVjudgeProblemLink = (oj, probNum) =>
        `https://vjudge.net/problem/${oj}-${probNum}`;

    const buildVjudgeSearch = (title) =>
        `https://vjudge.net/problem#title=${encodeURIComponent(title)}`;

    // ============ 原 OJ 链接构造(兜底) ============
    const buildLuoguDirect = (pid) => {
        let n = String(pid).trim();
        if (/^\d+$/.test(n)) n = 'P' + n;
        return `https://www.luogu.com.cn/problem/${n}`;
    };
    const buildCFDirect = (raw) => {
        raw = String(raw).trim();
        let gym = false;
        if (/^gym[-_]?/i.test(raw)) { gym = true; raw = raw.replace(/^gym[-_]?/i, ''); }
        const m = raw.match(/([A-Za-z]\d*)$/);
        if (!m) return null;
        const cid = raw.slice(0, -m[1].length);
        if (!/^\d+$/.test(cid)) return null;
        return gym
            ? `https://codeforces.com/gym/${cid}/problem/${m[1].toUpperCase()}`
            : `https://codeforces.com/contest/${cid}/problem/${m[1].toUpperCase()}`;
    };
    const buildATDirect = (raw) => {
        raw = String(raw).trim().toLowerCase();
        if (!raw) return null;
        if (/^[a-z]+[\d]+_[a-z0-9]+$/.test(raw)) {
            return `https://atcoder.jp/contests/${raw.split('_')[0]}/tasks/${raw}`;
        }
        let m = raw.match(/^([a-z]+[\d]+[a-z]+)(\d+)$/);
        if (m) return `https://atcoder.jp/contests/${m[1]}/tasks/${raw}`;
        m = raw.match(/^([a-z]+[\d]+)([a-z]\d*)$/);
        if (m) return `https://atcoder.jp/contests/${m[1]}/tasks/${m[1]}_${m[2]}`;
        return null;
    };
    const buildOJDirect = (oj, probNum) => {
        const o = ojKey(oj);
        if (isLuogu(o)) return buildLuoguDirect(probNum);
        if (isCF(o)) return buildCFDirect(probNum);
        if (isAT(o)) return buildATDirect(probNum);
        return null;
    };

    // ============ 从 /origin 拿真实链接 ============
    const fetchOriginLink = (oj, probNum) => {
        const key = oj + '-' + probNum;
        if (state.originCache[key] !== undefined) return state.originCache[key];
        if (state.pendingOrigin.has(key)) return null;
        state.pendingOrigin.add(key);

        const url = `https://vjudge.net/problem/${encodeURIComponent(oj)}-${encodeURIComponent(probNum)}/origin`;
        log('fetch /origin:', url);

        fetch(url, { credentials: 'include' })
            .then(r => r.text())
            .then(html => {
                const doc = new DOMParser().parseFromString(html, 'text/html');
                let found = null;
                const og = doc.querySelector('meta[property="og:url"]');
                if (og) {
                    const link = og.getAttribute('content');
                    if (link && /^https?:\/\//.test(link)) found = link;
                }
                if (!found) {
                    for (const a of doc.querySelectorAll('a[href]')) {
                        const h = a.getAttribute('href') || '';
                        if (/atcoder\.jp\/contests\/[^\/]+\/tasks\/[^\s?#]+/i.test(h)) { found = h; break; }
                        if (/codeforces\.com\/(?:contest|gym)\/\d+\/problem\/[A-Za-z]\d*/i.test(h)) { found = h; break; }
                        if (/luogu\.com(?:\.cn)?\/problem\/[A-Z0-9_]+/i.test(h)) { found = h; break; }
                    }
                }
                state.originCache[key] = found;
                log(found ? '★★★ /origin 命中: ' + found : '/origin 无链接');
                lastKey = null;
                tick();
            })
            .catch(e => {
                log('fetch /origin 失败:', e.message);
                state.originCache[key] = null;
                lastKey = null;
                tick();
            })
            .finally(() => state.pendingOrigin.delete(key));
        return null;
    };

    // ============ DOM 读取 OJ 来源 ============
    const readOriginFromDom = () => {
        const origin = document.querySelector('#problem-origin');
        if (origin) {
            const href = origin.getAttribute('href') || '';
            if (href && href !== '#') {
                const m = href.match(/\/problem\/([A-Za-z\u4e00-\u9fa5]+)-([A-Za-z0-9_]+)/);
                if (m) return { oj: m[1], probNum: m[2] };
            }
        }
        for (const a of document.querySelectorAll('a[href*="/origin"]')) {
            const h = a.getAttribute('href') || '';
            const m = h.match(/\/problem\/([A-Za-z\u4e00-\u9fa5]+)-([A-Za-z0-9_]+)\/origin/);
            if (m) return { oj: m[1], probNum: m[2] };
        }
        const text = document.body.innerText || '';
        const m = text.match(/请手动在\s*([A-Za-z\u4e00-\u9fa5]+)\s*[-–—]\s*([A-Za-z0-9_]+)\s*提交/);
        if (m) return { oj: m[1], probNum: m[2] };
        return null;
    };

    // ============ 路径解析 ============
    const fromProblemPath = () => {
        const m = location.pathname.match(/\/problem\/(.+?)\/?$/);
        if (!m) return null;
        const full = decodeURIComponent(m[1]);
        const i = full.indexOf('-');
        if (i <= 0) return null;
        return { oj: full.slice(0, i).trim(), probNum: full.slice(i + 1).trim() };
    };

    // ============ 缓存(比赛页) ============
    const memCache = {};
    const loadCache = () => {
        try {
            const s = sessionStorage.getItem(CACHE_KEY);
            if (s) {
                const p = JSON.parse(s);
                for (const k in p) memCache[k] = p[k];
            }
        } catch (e) {}
    };
    const saveCache = (cid, prob, info) => {
        memCache[cid] = memCache[cid] || {};
        if (info) memCache[cid][prob] = info;
        try { sessionStorage.setItem(CACHE_KEY, JSON.stringify(memCache)); } catch (e) {}
    };
    const getCached = (cid, prob) => {
        const c = memCache[cid];
        if (!c || !(prob in c)) return undefined;
        return c[prob];
    };
    loadCache();

    // ============ 面板 UI ============
    const makeBtn = (label, url, color, title) => {
        const a = document.createElement('a');
        a.textContent = label;
        a.title = title || '';
        a.href = url || 'javascript:void(0)';
        if (url) { a.target = '_blank'; a.rel = 'noopener noreferrer'; }
        a.style.cssText = `display:block;padding:5px 14px;margin:4px 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:${url ? color : '#bbb'};
            ${url ? 'box-shadow:0 2px 6px rgba(0,0,0,.2);cursor:pointer;' : 'cursor:not-allowed;'}`;
        if (url) {
            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 makeText = (text, color) => {
        const t = document.createElement('div');
        t.textContent = text;
        t.style.cssText = `font-size:11px;color:${color || '#999'};text-align:center;padding:4px 8px;`;
        return t;
    };

    const createPanelEl = () => {
        const p = document.createElement('div');
        p.setAttribute(PANEL_ATTR, 'panel');
        p.style.cssText = `position:fixed;top:16px;right:16px;z-index:2147483647;
            display:none;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;`;
        return p;
    };

    // ============ ★ 题库页:只给洛谷链接 ★ ============
    const buildProblemPanel = () => {
        const p = createPanelEl();
        const info = fromProblemPath();
        if (!info || !info.oj || !info.probNum) {
            p.appendChild(makeText('未找到'));
            return p;
        }
        const luoguUrl = buildLuoguLink(info.oj, info.probNum);
        if (luoguUrl) {
            p.appendChild(makeBtn('洛谷', luoguUrl, '#0e639c', `在洛谷打开 ${info.probNum}`));
            return p;
        }
        p.appendChild(makeText('未找到'));
        return p;
    };

    // ============ ★ 比赛页:原OJ + 洛谷 + VJudge,无来源给搜索 ★ ============
    const buildContestPanel = () => {
        const p = createPanelEl();
        const cm = location.pathname.match(/\/contest\/(\d+)/);
        const hm = location.hash.match(/#problem\/([A-Za-z0-9]+)/);
        if (!cm || !hm) {
            p.appendChild(makeText('未找到'));
            return p;
        }
        const cid = cm[1], curIdx = hm[1];

        // 获取 OJ 来源
        let origin = getCached(cid, curIdx);
        if (!origin) {
            const dom = readOriginFromDom();
            if (dom) { saveCache(cid, curIdx, dom); origin = dom; }
        }

        // 无来源 → VJudge 搜索
        if (!origin || !origin.oj || !origin.probNum) {
            const title = getProblemTitle();
            if (title) {
                p.appendChild(makeBtn('搜索原题', buildVjudgeSearch(title), '#5cb85c', `在 VJudge 搜索: ${title}`));
            } else {
                p.appendChild(makeText('未找到'));
            }
            return p;
        }

        const isOriginalLuogu = isLuogu(ojKey(origin.oj));
        const key = origin.oj + '-' + origin.probNum;

        // 原 OJ 链接
        let ojUrl = null;
        if (state.originCache[key] !== undefined) {
            ojUrl = state.originCache[key];
        } else if (!state.pendingOrigin.has(key)) {
            fetchOriginLink(origin.oj, origin.probNum);
        }
        if (!ojUrl) ojUrl = buildOJDirect(origin.oj, origin.probNum);

        // ★ 洛谷题:只挂一个洛谷链接(原OJ按钮跳过)
        if (isOriginalLuogu) {
            const luoguUrl = buildLuoguLink(origin.oj, origin.probNum);
            if (luoguUrl) {
                p.appendChild(makeBtn('洛谷', luoguUrl, '#0e639c', `洛谷 ${origin.probNum}`));
            }
            p.appendChild(makeBtn('VJudge', buildVjudgeProblemLink(origin.oj, origin.probNum), '#6c757d', '在 VJudge 题库打开'));
            return p;
        }

        // CF/AtCoder 题:原 OJ + 洛谷 + VJudge
        if (ojUrl) {
            p.appendChild(makeBtn(ojLabel(origin.oj), ojUrl, ojColor(origin.oj), `${ojLabel(origin.oj)} ${origin.probNum}`));
        }
        const luoguUrl = buildLuoguLink(origin.oj, origin.probNum);
        if (luoguUrl) {
            p.appendChild(makeBtn('洛谷', luoguUrl, '#0e639c', `洛谷 ${origin.probNum}`));
        }
        p.appendChild(makeBtn('VJudge', buildVjudgeProblemLink(origin.oj, origin.probNum), '#6c757d', '在 VJudge 题库打开'));
        return p;
    };

    const getProblemTitle = () => {
        const el = document.querySelector('#problem-title');
        if (!el) return '';
        const raw = (el.textContent || '').trim();
        return raw.replace(/^[A-Za-z]\d?\s*[-–—.]\s*/, '').trim() || raw;
    };

    const ensureHost = () => {
        if (state.hostRef && document.body.contains(state.hostRef)) return state.hostRef;
        const h = document.createElement('div');
        h.id = 'vjb-host-v91';
        h.setAttribute(PANEL_ATTR, 'host');
        h.style.cssText = 'position:fixed;top:0;left:0;width:0;height:0;z-index:2147483647;pointer-events:none;';
        document.body.appendChild(h);
        state.hostRef = h;
        return h;
    };

    // ============ 定位 ============
    const findContainer = () => {
        const sels = ['#problem', '#contest-problem-detail-view', '#problem-content', '.problem-content', '#problem-statement', '.problem-statement'];
        for (const s of sels) {
            const el = document.querySelector(s);
            if (el && el.offsetHeight > 100 && el.offsetWidth > 400) return el;
        }
        const ifr = document.querySelector('iframe[src*="/problem/description/"]');
        if (ifr) {
            const r = ifr.getBoundingClientRect();
            if (r.width > 300 && r.height > 100) return ifr;
        }
        return null;
    };

    const positionPanel = (panel) => {
        if (!panel || !panel.isConnected) return;
        const c = findContainer();
        if (!c) { panel.style.display = 'none'; return; }
        const r = c.getBoundingClientRect();
        const pw = panel.offsetWidth || 100;
        const ph = panel.offsetHeight || 60;
        let left = r.right - pw - 12;
        let top = r.top + 8;
        if (left < 8) left = 8;
        if (top < 8) top = 8;
        if (left + pw > window.innerWidth - 8) left = window.innerWidth - pw - 8;
        if (top + ph > window.innerHeight - 8) top = window.innerHeight - ph - 8;
        panel.style.left = left + 'px';
        panel.style.top = top + 'px';
        panel.style.right = 'auto';
        panel.style.display = 'flex';
    };

    // ============ 清理历史 ============
    const purgeLegacy = (keep) => {
        const isProtected = (el) => {
            if (!keep) return false;
            if (el === keep) return true;
            if (keep.contains(el)) return true;
            if (el.contains(keep)) return true;
            return false;
        };
        const attrs = ['data-vjb-v90','data-vjb-v86','data-vjb-v85','data-vjb-v84','data-vjb-v83','data-vjb-v82','data-vjb-v81','data-vjb-v80','data-vjb-v74','data-vjb-v73','data-vjb-v72','data-vjb-v71','data-vjb-v7','data-vjb-v6','data-vjb-v5','data-vjb-v3','data-vjb-panel-v24'];
        for (const attr of attrs) {
            document.querySelectorAll(`[${attr}]`).forEach(el => {
                if (isProtected(el)) return;
                el.remove();
            });
        }
        for (let i = 90; i >= 36; i--) {
            if (keep && keep.id === 'vjb-host-v' + i) continue;
            document.querySelectorAll('#vjb-host-v' + i).forEach(el => {
                if (isProtected(el)) return;
                el.remove();
            });
        }
        ['vj-better-panel','vjb-floating-panel-2024','vjbetter-panel','vjb-panel','vj-better-toolbar','vjbetter-toolbar']
            .forEach(id => document.querySelectorAll('#' + id).forEach(el => {
                if (isProtected(el)) return;
                el.remove();
            }));
    };

    // ============ 渲染 ============
    let lastKey = null;

    const computeKey = () => {
        if (/\/problem\//.test(location.pathname)) {
            const info = fromProblemPath();
            return info ? 'P|' + info.oj + '|' + info.probNum : 'P|null';
        }
        const cm = location.pathname.match(/\/contest\/(\d+)/);
        const hm = location.hash.match(/#problem\/([A-Za-z0-9]+)/);
        if (!cm || !hm) return 'C|null';
        const origin = getCached(cm[1], hm[1]) || readOriginFromDom();
        if (origin && origin.oj) {
            const k = origin.oj + '-' + origin.probNum;
            const ojUrl = state.originCache[k];
            return 'C|O|' + origin.oj + '|' + origin.probNum + '|' + (ojUrl === undefined ? 'pending' : (ojUrl || 'none'));
        }
        const title = getProblemTitle();
        return title ? 'C|S|' + title : 'C|NF';
    };

    const render = () => {
        if (window[NS] !== state) {
            clearInterval(state.intervalId);
            if (state.urlPoller) clearInterval(state.urlPoller);
            if (state.panelRef && state.panelRef.parentNode) state.panelRef.remove();
            if (state.hostRef && state.hostRef.parentNode) state.hostRef.remove();
            return;
        }
        const host = ensureHost();
        purgeLegacy(host);

        const isProblemPage = /\/problem\//.test(location.pathname);
        const isContestPage = /\/contest\//.test(location.pathname);

        if (!isProblemPage && !isContestPage) {
            if (state.panelRef && state.panelRef.parentNode) state.panelRef.remove();
            state.panelRef = null;
            lastKey = null;
            return;
        }

        const key = computeKey();

        if (!state.panelRef || !state.panelRef.parentNode || key !== lastKey) {
            if (state.panelRef && state.panelRef.parentNode) state.panelRef.remove();
            const panel = isProblemPage ? buildProblemPanel() : buildContestPanel();
            host.appendChild(panel);
            state.panelRef = panel;
            lastKey = key;
            log('面板重建,key =', key);
        }
        positionPanel(state.panelRef);
    };

    let rafPending = false;
    const schedulePosition = () => {
        if (rafPending) return;
        rafPending = true;
        requestAnimationFrame(() => {
            rafPending = false;
            if (state.panelRef) positionPanel(state.panelRef);
        });
    };
    window.addEventListener('scroll', schedulePosition, { passive: true, capture: true });
    window.addEventListener('resize', schedulePosition);

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

    state.stopAll = () => {
        if (state.intervalId) clearInterval(state.intervalId);
        if (state.urlPoller) clearInterval(state.urlPoller);
        if (state.panelRef && state.panelRef.parentNode) state.panelRef.remove();
        if (state.hostRef && state.hostRef.parentNode) state.hostRef.remove();
    };

    const onUrlChange = () => {
        log('URL 变化 →', location.href);
        lastKey = null;
        tick();
    };

    const startUrlPoller = () => {
        if (state.urlPoller) clearInterval(state.urlPoller);
        state.urlPoller = setInterval(() => {
            if (location.href !== state.lastUrl) {
                state.lastUrl = location.href;
                onUrlChange();
            }
        }, 200);
    };

    tick();
    state.intervalId = setInterval(tick, 800);
    startUrlPoller();

    window.addEventListener('hashchange', () => {
        if (location.href !== state.lastUrl) {
            state.lastUrl = location.href;
            onUrlChange();
        }
    });
    window.addEventListener('popstate', () => {
        if (location.href !== state.lastUrl) {
            state.lastUrl = location.href;
            onUrlChange();
        }
    });

})();