版本比较
洛谷美化油猴插件
正文
增加 457 行删除 1 行
123345678344 行未改动全部展开353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811隐藏**题号** & **难度**。
```:::info[]```javascript// ==UserScript==// @name Luogu 题号+难度 整合工具// @namespace http://tampermonkey.net/// @version 1.2344 行未改动全部展开 init(); }})();```:::
预览题目显示**难度 & 标签**。
:::info[]```javascript// ==UserScript==// @name 洛谷题目难度着色+标签速览// @namespace https://www.luogu.com.cn/// @version 2.2// @description 自动着色洛谷题目编号,悬停显示标签,双击跳转题目;// @author Assistant// @match https://www.luogu.com.cn/*// @grant GM_xmlhttpRequest// @grant GM_getValue// @grant GM_setValue// @grant GM_openInTab// @connect cdn.luogu.com.cn// @require https://cdn.jsdelivr.net/npm/pako@2.1.0/dist/pako.min.js// ==/UserScript==
(function() { 'use strict';
// 难度颜色映射 const DIFFICULTY_COLORS = { 0: '#808080', // 灰色 1: '#e74c3c', // 红色 2: '#e67e22', // 橙色 3: '#f1c40f', // 黄色 4: '#2ecc71', // 绿色 5: '#00bcd4', // 青色 6: '#2196F3', // 蓝色 7: '#9c3dcf', // 紫色 8: '#000000' // 黑色 };
const DATA_URL = 'https://cdn.luogu.com.cn/problemset-open/latest.ndjson.gz'; const DB_NAME = 'LuoguProblemDB'; const DB_VERSION = 1; const STORE_NAME = 'problems'; const MIN_UPDATE_INTERVAL = 3 * 24 * 60 * 60 * 1000; // 3天(毫秒)
// 题目编号正则,支持 P, B, CF, SP, AT, UVA 等 const PID_PATTERN = /\b(?:P|B|CF|SP|AT(?:_[A-Za-z0-9]+)?|UVA)\d+[A-Za-z0-9]*\b/g;
let problemDataMap = new Map(); // pid -> { difficulty, title, tags, type } let processedTextNodes = new WeakSet(); let processedLinks = new WeakSet(); let observer = null; let tooltip = null;
// ---------- 提示框 ---------- function createTooltip() { if (tooltip) return; tooltip = document.createElement('div'); tooltip.id = 'luogu-problem-tooltip'; tooltip.style.cssText = ` position: fixed; z-index: 9999999; background: rgba(30, 30, 30, 0.95); color: #fff; padding: 8px 12px; border-radius: 6px; font-size: 12px; max-width: 300px; word-wrap: break-word; pointer-events: none; display: none; box-shadow: 0 2px 8px rgba(0,0,0,0.3); `; document.body.appendChild(tooltip); }
function showTooltip(x, y, content) { createTooltip(); tooltip.innerHTML = content; tooltip.style.display = 'block'; const rect = tooltip.getBoundingClientRect(); let left = x + 10; let top = y + 10; if (left + rect.width > window.innerWidth - 5) left = x - rect.width - 10; if (top + rect.height > window.innerHeight - 5) top = y - rect.height - 10; tooltip.style.left = left + 'px'; tooltip.style.top = top + 'px'; }
function hideTooltip() { if (tooltip) tooltip.style.display = 'none'; }
// ---------- 状态提示 ---------- function showStatusMessage(text, isError = false) { const existing = document.getElementById('luogu-problem-status'); if (existing) existing.remove(); const div = document.createElement('div'); div.id = 'luogu-problem-status'; div.style.cssText = ` position: fixed; top: 20px; right: 20px; background: ${isError ? '#f44336' : '#2196F3'}; color: white; padding: 8px 16px; border-radius: 6px; z-index: 999999; font-size: 14px; box-shadow: 0 2px 8px rgba(0,0,0,0.2); max-width: 300px; word-wrap: break-word; `; div.textContent = text; document.body.appendChild(div); if (!isError) { setTimeout(() => { if (div.parentNode) div.remove(); }, 5000); } }
// ---------- IndexedDB 操作 ---------- function openDB() { return new Promise((resolve, reject) => { const request = indexedDB.open(DB_NAME, DB_VERSION); request.onupgradeneeded = (e) => { const db = e.target.result; if (!db.objectStoreNames.contains(STORE_NAME)) { db.createObjectStore(STORE_NAME, { keyPath: 'pid' }); } }; request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); }); }
async function getProblemCount() { const db = await openDB(); return new Promise((resolve, reject) => { const tx = db.transaction(STORE_NAME, 'readonly'); const store = tx.objectStore(STORE_NAME); const req = store.count(); req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error); }); }
async function clearProblems() { const db = await openDB(); return new Promise((resolve, reject) => { const tx = db.transaction(STORE_NAME, 'readwrite'); const store = tx.objectStore(STORE_NAME); const req = store.clear(); req.onsuccess = () => resolve(); req.onerror = () => reject(req.error); }); }
async function bulkInsert(problems) { const db = await openDB(); return new Promise((resolve, reject) => { const tx = db.transaction(STORE_NAME, 'readwrite'); const store = tx.objectStore(STORE_NAME); for (const p of problems) { store.put(p); } tx.oncomplete = () => resolve(); tx.onerror = () => reject(tx.error); }); }
async function loadProblemDataMap() { const db = await openDB(); return new Promise((resolve, reject) => { const tx = db.transaction(STORE_NAME, 'readonly'); const store = tx.objectStore(STORE_NAME); const req = store.getAll(); req.onsuccess = () => { const map = new Map(); req.result.forEach(item => { map.set(item.pid, { difficulty: item.difficulty, title: item.title || '', tags: item.tags || [], type: item.type || '' }); }); resolve(map); }; req.onerror = () => reject(req.error); }); }
// ---------- 下载题库数据 ---------- async function downloadAndStoreData(onProgress) { if (typeof pako === 'undefined') { throw new Error('pako 库未加载,请刷新页面重试。'); } await clearProblems(); return new Promise((resolve, reject) => { GM_xmlhttpRequest({ method: 'GET', url: DATA_URL, responseType: 'arraybuffer', onload: async (res) => { try { const compressed = new Uint8Array(res.response); const decompressed = pako.ungzip(compressed, { to: 'string' }); const lines = decompressed.split('\n').filter(line => line.trim() !== ''); const total = lines.length; const batchSize = 1000; let imported = 0;
const importBatch = async (start) => { const end = Math.min(start + batchSize, total); const batch = []; for (let i = start; i < end; i++) { try { const obj = JSON.parse(lines[i]); batch.push({ pid: obj.pid, title: obj.title, difficulty: obj.difficulty, type: obj.type, tags: obj.tags || [] }); } catch (e) {} } if (batch.length > 0) { await bulkInsert(batch); imported += batch.length; if (onProgress) onProgress(imported, total); } if (end < total) { await importBatch(end); } else { resolve(); } };
await importBatch(0); } catch (e) { reject(e); } }, onerror: (err) => reject(err) }); }); }
// ---------- 工具函数:打开题目页面(新增) ---------- function openProblemPage(pid) { const url = `https://www.luogu.com.cn/problem/${pid}`; if (typeof GM_openInTab === 'function') { GM_openInTab(url, { active: true, insert: true }); } else { window.open(url, '_blank'); } }
// ---------- DOM 着色与事件绑定 ---------- function colorizeNode(node) { if (!node) return; if (node.nodeType === Node.TEXT_NODE) { processTextNode(node); } else if (node.nodeType === Node.ELEMENT_NODE) { if (node.tagName === 'SCRIPT' || node.tagName === 'STYLE' || node.tagName === 'NOSCRIPT') return; if (node.classList && node.classList.contains('lg-diff-color')) return;
// 处理指向题目的链接 if (node.tagName === 'A' && node.getAttribute('href')?.includes('/problem/')) { processProblemLink(node); return; }
const childNodes = node.childNodes; for (let i = 0; i < childNodes.length; i++) { colorizeNode(childNodes[i]); } } }
function processTextNode(node) { if (processedTextNodes.has(node)) return; const text = node.textContent; if (!text) return;
PID_PATTERN.lastIndex = 0; const replacements = []; let match; while ((match = PID_PATTERN.exec(text)) !== null) { const pid = match[0]; const problemData = problemDataMap.get(pid); if (problemData) { replacements.push({ start: match.index, end: PID_PATTERN.lastIndex, pid: pid, difficulty: problemData.difficulty, tags: problemData.tags, title: problemData.title }); } }
if (replacements.length === 0) { processedTextNodes.add(node); return; }
const fragment = document.createDocumentFragment(); let lastIndex = 0; for (const r of replacements) { if (r.start > lastIndex) { fragment.appendChild(document.createTextNode(text.substring(lastIndex, r.start))); } const span = document.createElement('span'); span.className = 'lg-diff-color'; span.style.color = DIFFICULTY_COLORS[r.difficulty] || '#808080'; span.style.fontWeight = 'bold'; span.textContent = r.pid; span.style.cursor = 'pointer';
span.addEventListener('mouseenter', (e) => { const tags = r.tags && r.tags.length ? r.tags.join(', ') : '暂无标签'; const title = r.title ? `<strong>${r.pid} ${r.title}</strong>` : `<strong>${r.pid}</strong>`; showTooltip(e.clientX, e.clientY, `${title}<br>标签:${tags}`); }); span.addEventListener('mousemove', (e) => { if (tooltip && tooltip.style.display === 'block') { showTooltip(e.clientX, e.clientY, tooltip.innerHTML); } }); span.addEventListener('mouseleave', hideTooltip);
// 双击打开题目页面(使用新函数) span.addEventListener('dblclick', (e) => { e.preventDefault(); e.stopImmediatePropagation(); openProblemPage(r.pid); });
fragment.appendChild(span); lastIndex = r.end; } if (lastIndex < text.length) { fragment.appendChild(document.createTextNode(text.substring(lastIndex))); }
node.parentNode.replaceChild(fragment, node); processedTextNodes.add(node); }
function processProblemLink(a) { if (processedLinks.has(a)) return; const href = a.getAttribute('href'); const match = href && href.match(/\/problem\/([^/?]+)/); if (!match) return; const pid = decodeURIComponent(match[1]); const data = problemDataMap.get(pid);
processedLinks.add(a);
if (data) { const color = DIFFICULTY_COLORS[data.difficulty] || '#808080'; a.style.setProperty('color', color, 'important'); a.style.fontWeight = 'bold'; } a.style.cursor = 'pointer';
// 阻止单击默认跳转,让双击事件能够生效 a.addEventListener('click', (e) => { e.preventDefault(); });
a.addEventListener('mouseenter', (e) => { const tags = data && data.tags && data.tags.length ? data.tags.join(', ') : '暂无标签'; const title = data && data.title ? `<strong>${pid} ${data.title}</strong>` : `<strong>${pid}</strong>`; showTooltip(e.clientX, e.clientY, `${title}<br>标签:${tags}`); }); a.addEventListener('mousemove', (e) => { if (tooltip && tooltip.style.display === 'block') { showTooltip(e.clientX, e.clientY, tooltip.innerHTML); } }); a.addEventListener('mouseleave', hideTooltip);
// 双击打开新页面(使用新函数) a.addEventListener('dblclick', (e) => { e.preventDefault(); e.stopImmediatePropagation(); openProblemPage(pid); }); }
function colorizeExistingDOM() { colorizeNode(document.body); }
function startObserver() { if (observer) observer.disconnect(); observer = new MutationObserver((mutations) => { mutations.forEach((mutation) => { mutation.addedNodes.forEach((node) => { colorizeNode(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); }
// ---------- 初始化 ---------- async function init() { try { const lastUpdate = GM_getValue('last_update_time', 0); const now = Date.now();
let count = await getProblemCount();
if (count === 0) { showStatusMessage('正在下载洛谷题库数据,首次使用可能需要几十秒...'); console.log('[洛谷题目着色] 无本地题库,开始下载...'); await downloadAndStoreData((current, total) => { if (current % 5000 === 0 || current === total) { showStatusMessage(`题库下载中: ${current}/${total}`); } }); GM_setValue('last_update_time', Date.now()); showStatusMessage('题库下载完成,正在着色...'); console.log('[洛谷题目着色] 下载完成'); } else if (now - lastUpdate >= MIN_UPDATE_INTERVAL) { showStatusMessage('题库数据已超过3天未更新,正在更新...'); console.log('[洛谷题目着色] 超过3天,开始更新题库...'); await downloadAndStoreData((current, total) => { if (current % 5000 === 0 || current === total) { showStatusMessage(`题库更新中: ${current}/${total}`); } }); GM_setValue('last_update_time', Date.now()); showStatusMessage('题库更新完成,正在着色...'); } else { console.log('[洛谷题目着色] 题库数据在3天内已更新过,使用本地缓存'); }
problemDataMap = await loadProblemDataMap(); console.log(`[洛谷题目着色] 已加载 ${problemDataMap.size} 条题目数据`); colorizeExistingDOM(); startObserver(); showStatusMessage('题目难度着色与标签速览已启用', false); } catch (err) { console.error('[洛谷题目着色] 初始化失败:', err); showStatusMessage('题库下载失败,请检查网络后刷新重试', true); startObserver(); } }
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', init); } else { init(); }})();```:::