那些有用的篡改猴插件
Luogu 随机跳题
// ==UserScript==
// @name 洛谷随机跳题(Luogu Random Picker)
// @namespace luogu-random-picker
// @version 1.0.0
// @description 在洛谷网页内一键随机跳转题目:可按难度区间、题号范围(收录时间)、年份、算法/来源标签、关键词等条件筛选;首次使用自动同步题库索引,之后本地即时抽题。
// @author TakisuGui
// @match https://www.luogu.com.cn/*
// @match http://www.luogu.com.cn/*
// @icon https://www.luogu.com.cn/favicon.ico
// @run-at document-idle
// @noframes
// @grant none
// @license MIT
// ==/UserScript==
(function () {
'use strict';
const SCRIPT_VERSION = '1.0.0';
const SITE = 'https://www.luogu.com.cn';
const LS_INDEX = 'lg_rp_index_v1';
const LS_META = 'lg_rp_meta_v1';
const LS_TAGS = 'lg_rp_tags_v1';
const LS_STATE = 'lg_rp_state_v1';
const INDEX_TTL = 7 * 24 * 60 * 60 * 1000;
const INDEX_CONCURRENCY = 6;
const RETRY_LIMIT = 3;
// ------------------------------------------------------------------
// 难度档位(洛谷现行体系:0=暂无评定,1..8 由易到难)
// ------------------------------------------------------------------
const DIFFS = [
{ v: 0, name: '暂无评定', color: '#9e9e9e' },
{ v: 1, name: '入门', color: '#e74c3c' },
{ v: 2, name: '普及-', color: '#f39c12' },
{ v: 3, name: '普及', color: '#f1c40f' },
{ v: 4, name: '普及+/提高-', color: '#2ecc71' },
{ v: 5, name: '提高', color: '#00bcd4' },
{ v: 6, name: '提高+/省选-', color: '#3498db' },
{ v: 7, name: '省选/NOI-', color: '#9b59b6' },
{ v: 8, name: 'NOI/NOI+/CTS', color: '#34495e' },
];
const DEFAULT_STATE = {
diffMin: 1,
diffMax: 8,
pidFrom: '',
pidTo: '',
yearFrom: '',
yearTo: '',
tags: [],
tagMode: 'any',
keyword: '',
excludeRepeat: true,
autoJump: true,
};
const CURATED_NAMES = [
'动态规划 DP', '背包 DP', '区间 DP', '树形 DP', '状压 DP', '数位 DP', '线性 DP',
'图论', '最短路', '生成树', '二分图', '网络流', '费用流', '拓扑排序',
'数论', '素数判断', '最大公约数 gcd', '博弈论',
'搜索', '广度优先搜索 BFS', '深度优先搜索 DFS', '记忆化搜索', '剪枝',
'贪心', '模拟', '枚举', '排序', '递推', '分治',
'字符串', 'KMP', '哈希', '字典树 Trie', '高精度',
'树形数据结构', '线段树', '树状数组', '平衡树', '并查集', '树论', '树上差分',
'计算几何', '数学', '概率与期望', '快速傅里叶变换 FFT',
];
// ------------------------------------------------------------------
// 基础工具
// ------------------------------------------------------------------
function delay(ms) {
return new Promise(function (resolve) {
setTimeout(resolve, ms);
});
}
function esc(s) {
return String(s == null ? '' : s)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
}
function pidNumber(pid) {
const n = parseInt(String(pid).replace(/[^0-9]/g, ''), 10);
return Number.isFinite(n) ? n : 0;
}
function readLS(key, fallback) {
try {
const raw = localStorage.getItem(key);
return raw == null ? fallback : raw;
} catch (e) {
return fallback;
}
}
function writeLS(key, value) {
try {
localStorage.setItem(key, value);
return true;
} catch (e) {
return false;
}
}
function readJSON(key, fallback) {
try {
const raw = localStorage.getItem(key);
return raw == null ? fallback : JSON.parse(raw);
} catch (e) {
return fallback;
}
}
function writeJSON(key, obj) {
try {
localStorage.setItem(key, JSON.stringify(obj));
return true;
} catch (e) {
return false;
}
}
function cloneState(s) {
return Object.assign({}, DEFAULT_STATE, JSON.parse(JSON.stringify(s || {})));
}
function sanitizeState(s) {
const st = cloneState(s);
st.diffMin = Number.isFinite(+st.diffMin) ? Math.min(8, Math.max(0, +st.diffMin)) : 1;
st.diffMax = Number.isFinite(+st.diffMax) ? Math.min(8, Math.max(0, +st.diffMax)) : 8;
if (st.diffMin > st.diffMax) st.diffMax = st.diffMin;
st.pidFrom = String(st.pidFrom || '').trim().toUpperCase();
st.pidTo = String(st.pidTo || '').trim().toUpperCase();
st.yearFrom = String(st.yearFrom || '');
st.yearTo = String(st.yearTo || '');
st.tags = (Array.isArray(st.tags) ? st.tags : []).map(Number).filter(Number.isFinite);
st.tagMode = st.tagMode === 'all' ? 'all' : 'any';
st.keyword = String(st.keyword || '').trim();
st.excludeRepeat = st.excludeRepeat !== false;
st.autoJump = st.autoJump !== false;
return st;
}
// ------------------------------------------------------------------
// 数据解析 / 编码
// ------------------------------------------------------------------
function parseListHTML(html) {
const text = String(html || '');
let json = null;
const trimmed = text.trim();
if (trimmed.charAt(0) === '{') {
json = JSON.parse(trimmed);
} else {
const m = text.match(/<script id="lentille-context" type="application\/json">([\s\S]*?)<\/script>/);
if (!m) throw new Error('PAGE_FORMAT_UNEXPECTED');
json = JSON.parse(m[1]);
}
const data = (json && (json.data || json.currentData)) || {};
const pr = data.problems || {};
const result = Array.isArray(pr.result) ? pr.result : [];
return {
count: pr.count,
perPage: pr.perPage,
problems: result
.filter(function (x) { return x && x.pid; })
.map(function (x) {
return {
pid: String(x.pid),
name: String(x.name || ''),
diff: Number.isFinite(+x.difficulty) ? +x.difficulty : 0,
tags: Array.isArray(x.tags) ? x.tags.map(Number) : [],
};
}),
};
}
function encodeProblems(problems) {
return problems
.map(function (p) {
const name = String(p.name || '').replace(/[\t\n\r]/g, ' ');
return [p.pid, name, p.diff, (p.tags || []).join(',')].join('\t');
})
.join('\n');
}
function decodeProblems(blob) {
const list = [];
if (!blob) return list;
const lines = String(blob).split('\n');
for (const line of lines) {
if (!line) continue;
const parts = line.split('\t');
if (parts.length < 3) continue;
const tags = parts[3] ? parts[3].split(',').map(Number) : [];
list.push({
pid: parts[0],
name: parts[1],
diff: Number.isFinite(+parts[2]) ? +parts[2] : 0,
tags: tags.filter(Number.isFinite),
});
}
return list;
}
// ------------------------------------------------------------------
// 题库索引同步
// ------------------------------------------------------------------
async function fetchListPage(page) {
let lastErr = null;
for (let attempt = 0; attempt < RETRY_LIMIT; attempt++) {
try {
const resp = await fetch(SITE + '/problem/list?page=' + page + '&_contentOnly=1', {
credentials: 'include',
cache: 'no-store',
headers: { Accept: 'text/html,application/json' },
});
if (!resp.ok) throw new Error('HTTP ' + resp.status);
const html = await resp.text();
const parsed = parseListHTML(html);
if (!parsed.problems.length && !parsed.count) throw new Error('EMPTY_PAGE');
return parsed;
} catch (e) {
lastErr = e;
await delay(400 * (attempt + 1) + Math.random() * 300);
}
}
throw lastErr || new Error('FETCH_FAILED');
}
function isIndexFresh(meta) {
if (!meta) return false;
if (meta.ver !== SCRIPT_VERSION) return false;
if (!meta.ts) return false;
return Date.now() - meta.ts < INDEX_TTL;
}
async function syncIndex(onProgress) {
const map = new Map();
const first = await fetchListPage(1);
const count = first.count || 0;
const perPage = first.perPage || 50;
const totalPages = Math.max(1, Math.ceil(count / perPage));
let done = 0;
function addProblems(problems) {
for (const p of problems) {
if (!map.has(p.pid)) {
map.set(p.pid, p);
done++;
}
}
}
addProblems(first.problems);
onProgress && onProgress(done, count, 1, totalPages, '同步中');
let next = 2;
let consecutiveFails = 0;
async function worker() {
while (next <= totalPages) {
if (syncAbort && syncAbort.aborted) {
const err = new Error('ABORTED');
throw err;
}
const page = next++;
try {
const parsed = await fetchListPage(page);
addProblems(parsed.problems);
consecutiveFails = 0;
} catch (e) {
consecutiveFails++;
if (consecutiveFails >= 5) throw e;
}
onProgress && onProgress(done, count, Math.min(page, totalPages), totalPages, '同步中');
}
}
const workers = [];
const n = Math.min(INDEX_CONCURRENCY, totalPages);
for (let i = 0; i < n; i++) workers.push(worker());
try {
await Promise.all(workers);
} finally {
onProgress && onProgress(done, count, totalPages, totalPages, done >= count ? '完成' : '部分完成');
}
const problems = [...map.values()];
const ok = writeLS(LS_INDEX, encodeProblems(problems));
writeJSON(LS_META, {
ts: Date.now(),
ver: SCRIPT_VERSION,
count: problems.length,
pages: totalPages,
complete: done >= count,
});
return { problems: problems, count: done, saved: ok, complete: done >= count };
}
function loadCachedProblems() {
const meta = readJSON(LS_META, null);
if (!isIndexFresh(meta)) return null;
const blob = readLS(LS_INDEX, '');
if (!blob) return null;
const problems = decodeProblems(blob);
if (!problems.length) return null;
return { problems: problems, meta: meta };
}
// ------------------------------------------------------------------
// 标签字典
// ------------------------------------------------------------------
function parseTagsJSON(text) {
let j = null;
const trimmed = String(text || '').trim();
if (trimmed.charAt(0) === '{' || trimmed.charAt(0) === '[') {
j = JSON.parse(trimmed);
} else {
const m = trimmed.match(/<script id="lentille-context" type="application\/json">([\s\S]*?)<\/script>/);
if (m) j = JSON.parse(m[1]);
}
const tags = (j && (j.tags || (j.data && j.data.tags))) || [];
return Array.isArray(tags) ? tags : [];
}
function parseTagCaches() {
const obj = readJSON(LS_TAGS, { ts: 0, tags: [] });
if (Array.isArray(obj.tags) && obj.tags.length) {
return { ts: obj.ts || 0, tags: obj.tags };
}
return { ts: 0, tags: [] };
}
async function ensureTags() {
const cached = parseTagCaches();
if (cached.tags.length && Date.now() - cached.ts < 24 * 60 * 60 * 1000) return cached.tags;
try {
const resp = await fetch(SITE + '/_lfe/tags/zh-CN', { credentials: 'include', cache: 'no-store' });
if (!resp.ok) throw new Error('HTTP ' + resp.status);
const tags = parseTagsJSON(await resp.text());
if (tags.length) {
writeJSON(LS_TAGS, { ts: Date.now(), tags: tags });
return tags;
}
} catch (e) {
// ignore, fall through to cache
}
return cached.tags;
}
function buildTagIndex(tags) {
const byId = new Map();
for (const t of tags) byId.set(t.id, t);
return { byId: byId, tags: tags };
}
function rootOfType(t, byId, type) {
let cur = t;
let guard = 0;
while (cur && cur.parent != null && guard++ < 10) {
const parent = byId.get(cur.parent);
if (!parent || parent.type !== type) break;
cur = parent;
}
return cur;
}
function groupByRoot(tags, type, byId) {
const groups = new Map();
for (const t of tags) {
if (t.type !== type) continue;
const root = rootOfType(t, byId, type);
if (!groups.has(root.id)) groups.set(root.id, { root: root, children: [] });
groups.get(root.id).children.push(t);
}
return [...groups.values()];
}
function yearTagMap(tags) {
const map = new Map();
const maxYear = new Date().getFullYear() + 2;
for (const t of tags) {
if (t.type === 4 && /^\d{4}$/.test(String(t.name))) {
const y = Number(t.name);
if (y <= maxYear) map.set(y, t.id);
}
}
return map;
}
// ------------------------------------------------------------------
// 筛选
// ------------------------------------------------------------------
function makeFilter(state, tagInfo) {
const st = sanitizeState(state);
const pidFrom = pidNumber(st.pidFrom);
const pidTo = pidNumber(st.pidTo);
const tagSet = new Set(st.tags);
const yearIds = new Set();
if (st.yearFrom || st.yearTo) {
const yMap = yearTagMap(tagInfo.tags);
const lo = st.yearFrom ? +st.yearFrom : 1900;
const hi = st.yearTo ? +st.yearTo : 2100;
for (const [y, id] of yMap) {
if (y >= lo && y <= hi) yearIds.add(id);
}
}
const kw = st.keyword ? st.keyword.toLowerCase() : '';
const kwPid = kw && /^p?\d+$/.test(kw) ? pidNumber(kw) : 0;
return function (p) {
if (p.diff < st.diffMin || p.diff > st.diffMax) return false;
if (pidFrom || pidTo) {
const n = pidNumber(p.pid);
if (pidFrom && n < pidFrom) return false;
if (pidTo && n > pidTo) return false;
}
if (yearIds.size) {
let hasYear = false;
for (const t of p.tags) {
if (yearIds.has(t)) {
hasYear = true;
break;
}
}
if (!hasYear) return false;
}
if (kw) {
const inName = String(p.name).toLowerCase().indexOf(kw) >= 0;
const inPid = kwPid > 0 && pidNumber(p.pid) === kwPid;
if (!inName && !inPid) return false;
}
if (tagSet.size) {
if (st.tagMode === 'all') {
for (const id of tagSet) {
if (p.tags.indexOf(id) < 0) return false;
}
} else {
let any = false;
for (const id of tagSet) {
if (p.tags.indexOf(id) >= 0) {
any = true;
break;
}
}
if (!any) return false;
}
}
return true;
};
}
function countMatches(problems, filter) {
let n = 0;
for (const p of problems) if (filter(p)) n++;
return n;
}
function pickOne(problems, filter, sessionSeen) {
const seen = sessionSeen || new Set();
const pool = [];
for (const p of problems) {
if (filter(p)) pool.push(p);
}
if (!pool.length) return null;
let list = pool;
let skipped = false;
if (seen.size) {
const fresh = pool.filter(function (p) { return !seen.has(p.pid); });
if (fresh.length) {
list = fresh;
} else {
skipped = true;
}
}
return { problem: list[Math.floor(Math.random() * list.length)], skipped: skipped };
}
// ------------------------------------------------------------------
// UI
// ------------------------------------------------------------------
let root = null; // shadow host
let shadow = null;
let modalEl = null;
let panelEl = null;
let resultEl = null;
let state = sanitizeState(DEFAULT_STATE);
let tagInfo = buildTagIndex([]);
let problems = [];
let meta = null;
let sessionSeen = new Set();
let jumpTimer = null;
let syncing = false;
let syncAbort = null;
function loadSessionSeen() {
try {
const raw = sessionStorage.getItem('lg_rp_seen_v1');
if (raw) sessionSeen = new Set(JSON.parse(raw));
} catch (e) {
sessionSeen = new Set();
}
}
function saveSessionSeen() {
try {
sessionStorage.setItem('lg_rp_seen_v1', JSON.stringify([...sessionSeen]));
} catch (e) {
// ignore
}
}
function loadState() {
state = sanitizeState(readJSON(LS_STATE, DEFAULT_STATE));
}
function persistState() {
writeJSON(LS_STATE, state);
}
function diffLabel(v) {
const d = DIFFS.find(function (x) { return x.v === v; });
return d || DIFFS[0];
}
function tagNames(ids) {
const out = [];
for (const id of ids || []) {
const t = tagInfo.byId.get(id);
out.push(t ? t.name : String(id));
}
return out;
}
function toast(msg) {
let box = shadow && shadow.getElementById('toast');
if (!box) {
box = document.createElement('div');
box.id = 'toast';
shadow.appendChild(box);
}
box.textContent = msg;
box.classList.add('show');
clearTimeout(box._timer);
box._timer = setTimeout(function () { box.classList.remove('show'); }, 2600);
}
function css() {
return `
:host { all: initial; }
* { box-sizing: border-box; }
.fab {
position: fixed; right: 22px; bottom: 24px; z-index: 999999;
display: flex; align-items: center; gap: 8px;
padding: 11px 18px; border: none; cursor: pointer;
background: #3498db; color: #fff; font-size: 14px; font-family: "PingFang SC","Microsoft YaHei",sans-serif;
border-radius: 999px; box-shadow: 0 4px 14px rgba(0,0,0,.25); transition: transform .15s;
}
.fab:hover { transform: translateY(-2px); background: #2f89c5; }
.fab:active { transform: scale(.96); }
.fab .dice { font-size: 18px; line-height: 1; }
.overlay {
position: fixed; inset: 0; z-index: 999998; display: none;
align-items: flex-start; justify-content: center; overflow-y: auto;
background: rgba(0,0,0,.45); padding: 24px 12px;
}
.overlay.open { display: flex; }
.modal {
width: 760px; max-width: 100%; margin: auto; background: #fff;
border-radius: 12px; box-shadow: 0 12px 48px rgba(0,0,0,.25);
font-family: "PingFang SC","Microsoft YaHei",system-ui,sans-serif;
color: #1f2328; font-size: 14px; line-height: 1.5;
}
.head {
display: flex; align-items: center; justify-content: space-between;
padding: 14px 18px; border-bottom: 1px solid #eceff2;
}
.head .title { font-size: 17px; font-weight: 600; display:flex; align-items:center; gap:8px; }
.head .sub { font-size: 12px; color: #8b95a0; margin-left: 8px; font-weight: 400; }
.close { border: none; background: none; cursor: pointer; font-size: 20px; color: #8b95a0; line-height: 1; }
.close:hover { color: #333; }
.body { padding: 16px 18px 4px; }
.row { display: flex; gap: 14px; flex-wrap: wrap; margin-bottom: 12px; }
.field { flex: 1 1 220px; min-width: 200px; }
.field label { display: block; font-size: 12px; color: #6b7580; margin-bottom: 4px; }
.field select, .field input {
width: 100%; padding: 7px 9px; border: 1px solid #d6dbe1; border-radius: 6px;
font: inherit; background: #fff; color: inherit; outline: none;
}
.field select:focus, .field input:focus { border-color: #3498db; }
.range-hint { font-size: 11px; color: #98a2ab; margin-top: 3px; }
.tag-zone { border: 1px solid #e3e7eb; border-radius: 8px; padding: 10px; margin-bottom: 12px; }
.tag-bar { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-bottom: 8px; }
.tag-bar .mode { display: flex; gap: 4px; align-items: center; font-size: 12px; }
.tag-bar .mode label { display: flex; align-items: center; gap: 3px; cursor: pointer; }
.tag-search { flex: 1 1 180px; min-width: 150px; padding: 6px 9px; border: 1px solid #d6dbe1; border-radius: 6px; font: inherit; outline: none; }
.tag-search:focus { border-color: #3498db; }
.tag-sel-info { font-size: 12px; color: #3498db; }
.tag-clear { font-size: 12px; color: #98a2ab; background:none; border:none; cursor:pointer; text-decoration:underline; }
.quick { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 8px; }
.quick .qlabel { font-size: 12px; color: #98a2ab; line-height: 24px; margin-right: 2px; }
.tag-groups { max-height: 220px; overflow-y: auto; border: 1px solid #eef1f4; border-radius: 6px; padding: 4px 8px; }
details { margin: 3px 0; }
summary { cursor: pointer; font-size: 13px; color: #444; padding: 3px 2px; user-select: none; }
summary .cnt { color: #b0b8c0; font-size: 11px; margin-left: 4px; }
.chips { display: flex; flex-wrap: wrap; gap: 6px; padding: 2px 2px 8px 12px; }
.chip { display: inline-flex; align-items: center; gap: 4px; border: 1px solid #dde2e8; border-radius: 999px; padding: 3px 10px; cursor: pointer; font-size: 12px; background: #fafbfc; transition: all .12s; }
.chip:hover { border-color: #8fc6ea; }
.chip input { display: none; }
.chip.on { background: #eaf4fc; border-color: #6ab0e0; color: #1b6cab; }
.no-tag { color: #b0b8c0; font-size: 12px; padding: 6px 4px; }
.flat-title { font-size: 12px; color: #8b95a0; margin: 6px 2px 2px; }
.foot {
display: flex; align-items: center; gap: 12px; padding: 12px 18px 16px;
border-top: 1px solid #eceff2; flex-wrap: wrap;
}
.match-num { font-size: 12px; color: #8b95a0; }
.match-num b { color: #3498db; }
.foot .spacer { flex: 1; }
.btn {
border: none; border-radius: 8px; padding: 9px 18px; font: inherit; cursor: pointer;
transition: filter .12s, transform .12s;
}
.btn:hover { filter: brightness(.96); }
.btn:active { transform: translateY(1px); }
.btn-primary { background: #3498db; color: #fff; font-weight: 600; }
.btn-ghost { background: #f1f3f5; color: #333; }
.btn[disabled] { opacity: .55; cursor: not-allowed; }
.btn-sm { padding: 6px 12px; font-size: 13px; }
.switch-row { display: flex; gap: 16px; flex-wrap: wrap; align-items: center; margin-bottom: 12px; font-size: 13px; }
.switch-row label { display: flex; align-items: center; gap: 5px; cursor: pointer; }
.syncbar { display: flex; align-items: center; gap: 10px; background: #f4f8fc; border: 1px solid #dbe9f5; border-radius: 8px; padding: 8px 12px; margin-bottom: 12px; font-size: 12px; color: #1f6fae; }
.syncbar .prog { flex: 1; }
.bar { height: 5px; background: #dfe8f0; border-radius: 3px; overflow: hidden; margin-top: 4px; }
.bar > i { display: block; height: 100%; background: #3498db; transition: width .2s; }
.syncbar.hidden { display: none; }
.result { border: 1px solid #e3e7eb; border-radius: 10px; padding: 14px 16px; margin: 0 0 12px; background: #fbfcfd; display: none; }
.result.show { display: block; animation: pop .22s ease; }
@keyframes pop { from { transform: scale(.97); opacity: 0; } to { transform: scale(1); opacity: 1; } }
.res-pid { font-size: 20px; font-weight: 700; color: #1f2328; }
.res-name { font-size: 15px; color: #57606a; margin: 2px 0 10px; }
.res-meta { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-bottom: 4px; }
.badge { display: inline-block; border-radius: 4px; padding: 1px 8px; font-size: 12px; color: #fff; }
.res-tags { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 4px; }
.res-tag { background: #eef2f6; color: #48525c; border-radius: 4px; font-size: 12px; padding: 1px 8px; }
.res-actions { display: flex; gap: 10px; margin-top: 12px; align-items: center; }
.jump-note { font-size: 12px; color: #98a2ab; }
.link { color: #3498db; text-decoration: none; font-size: 12px; }
.link:hover { text-decoration: underline; }
.muted { color: #8b95a0; font-size: 12px; }
#toast {
position: fixed; left: 50%; bottom: 30px; transform: translateX(-50%) translateY(20px);
background: rgba(20,26,31,.92); color: #fff; font-size: 13px; padding: 9px 18px;
border-radius: 999px; opacity: 0; pointer-events: none; transition: all .2s; z-index: 1000000;
font-family: "PingFang SC","Microsoft YaHei",sans-serif;
}
#toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }
`;
}
function buildModal() {
const modal = document.createElement('div');
modal.className = 'modal';
modalEl = modal;
const head = document.createElement('div');
head.className = 'head';
head.innerHTML = '<div class="title">🎲 随机跳题 <span class="sub">洛谷题库 · 索引本地筛选</span></div>';
const closeBtn = document.createElement('button');
closeBtn.className = 'close';
closeBtn.textContent = '×';
closeBtn.addEventListener('click', closeModal);
head.appendChild(closeBtn);
const body = document.createElement('div');
body.className = 'body';
// 同步提示条
const syncbar = document.createElement('div');
syncbar.className = 'syncbar hidden';
syncbar.innerHTML =
'<div class="prog"><span class="msg">同步题库中…</span>' +
'<div class="bar"><i style="width:0%"></i></div></div>' +
'<button class="btn btn-ghost btn-sm abort-sync">取消</button>';
const syncMsg = syncbar.querySelector('.msg');
const syncBar = syncbar.querySelector('.bar i');
syncbar.querySelector('.abort-sync').addEventListener('click', function () {
if (syncAbort) syncAbort.aborted = true;
});
// 难度
const diffField = document.createElement('div');
diffField.className = 'field';
const diffRow = document.createElement('div');
diffRow.style.cssText = 'display:flex;gap:8px;align-items:center;';
const diffMinSel = document.createElement('select');
const diffMaxSel = document.createElement('select');
const diffDash = document.createElement('span');
diffDash.style.cssText = 'color:#98a2ab;';
diffDash.textContent = '~';
for (const d of DIFFS) {
diffMinSel.appendChild(new Option(d.name + '(' + d.v + ')', String(d.v)));
diffMaxSel.appendChild(new Option(d.name + '(' + d.v + ')', String(d.v)));
}
diffRow.appendChild(diffMinSel);
diffRow.appendChild(diffDash);
diffRow.appendChild(diffMaxSel);
diffField.appendChild(makeLabel('难度区间'));
diffField.appendChild(diffRow);
// 题号范围
const pidField = document.createElement('div');
pidField.className = 'field';
const pidRow = document.createElement('div');
pidRow.style.cssText = 'display:flex;gap:8px;align-items:center;';
const pidFrom = document.createElement('input');
pidFrom.placeholder = '如 P1000';
const pidTo = document.createElement('input');
pidTo.placeholder = '如 P17391';
const pidDash = document.createElement('span');
pidDash.style.cssText = 'color:#98a2ab;';
pidDash.textContent = '~';
pidRow.appendChild(pidFrom);
pidRow.appendChild(pidDash);
pidRow.appendChild(pidTo);
pidField.appendChild(makeLabel('题号范围(按收录先后近似时间)'));
pidField.appendChild(pidRow);
pidField.appendChild(makeHint('留空表示不限'));
// 年份范围
const yearField = document.createElement('div');
yearField.className = 'field';
const yearRow = document.createElement('div');
yearRow.style.cssText = 'display:flex;gap:8px;align-items:center;';
const yearFrom = document.createElement('select');
const yearTo = document.createElement('select');
const yearDash = document.createElement('span');
yearDash.style.cssText = 'color:#98a2ab;';
yearDash.textContent = '~';
yearRow.appendChild(yearFrom);
yearRow.appendChild(yearDash);
yearRow.appendChild(yearTo);
yearField.appendChild(makeLabel('年份区间(题目带年份标签才命中)'));
yearField.appendChild(yearRow);
yearField.appendChild(makeHint('如 NOIP 2015、CSP 2023 等'));
const rowA = document.createElement('div');
rowA.className = 'row';
rowA.appendChild(diffField);
rowA.appendChild(pidField);
rowA.appendChild(yearField);
// 关键词
const kwField = document.createElement('div');
kwField.className = 'field';
const kwInput = document.createElement('input');
kwInput.placeholder = '标题关键词,如 采药、排列';
kwField.appendChild(makeLabel('标题关键词'));
kwField.appendChild(kwInput);
const switchRow = document.createElement('div');
switchRow.className = 'switch-row';
const anyLbl = document.createElement('label');
const anyRadio = document.createElement('input');
anyRadio.type = 'radio';
anyRadio.name = 'tagmode';
anyRadio.value = 'any';
anyLbl.appendChild(anyRadio);
anyLbl.appendChild(document.createTextNode('标签命中:任一'));
const allLbl = document.createElement('label');
const allRadio = document.createElement('input');
allRadio.type = 'radio';
allRadio.name = 'tagmode';
allRadio.value = 'all';
allLbl.appendChild(allRadio);
allLbl.appendChild(document.createTextNode('全部'));
switchRow.appendChild(anyLbl);
switchRow.appendChild(allLbl);
switchRow.appendChild(document.createElement('span')).className = 'spacer';
const exclLbl = document.createElement('label');
const exclChk = document.createElement('input');
exclChk.type = 'checkbox';
exclLbl.appendChild(exclChk);
exclLbl.appendChild(document.createTextNode('本次会话不重复'));
switchRow.appendChild(exclLbl);
const autoLbl = document.createElement('label');
const autoChk = document.createElement('input');
autoChk.type = 'checkbox';
autoLbl.appendChild(autoChk);
autoLbl.appendChild(document.createTextNode('抽中后自动跳转'));
switchRow.appendChild(autoLbl);
const kwRow = document.createElement('div');
kwRow.className = 'row';
kwRow.appendChild(kwField);
// 标签区
const tagZone = document.createElement('div');
tagZone.className = 'tag-zone';
panelEl = tagZone;
body.appendChild(syncbar);
body.appendChild(rowA);
body.appendChild(kwRow);
body.appendChild(switchRow);
body.appendChild(tagZone);
// 底部
const foot = document.createElement('div');
foot.className = 'foot';
const matchNum = document.createElement('span');
matchNum.className = 'match-num';
foot.appendChild(matchNum);
const spacer = document.createElement('span');
spacer.className = 'spacer';
foot.appendChild(spacer);
const syncBtn = document.createElement('button');
syncBtn.className = 'btn btn-ghost btn-sm';
syncBtn.textContent = '更新题库';
foot.appendChild(syncBtn);
const goBtn = document.createElement('button');
goBtn.className = 'btn btn-primary';
goBtn.textContent = '🎲 抽一题';
foot.appendChild(goBtn);
// 结果区
const result = document.createElement('div');
result.className = 'result';
resultEl = result;
body.appendChild(result);
modal.appendChild(head);
modal.appendChild(body);
modal.appendChild(foot);
const overlay = document.createElement('div');
overlay.className = 'overlay';
overlay.appendChild(modal);
overlay.addEventListener('mousedown', function (e) {
if (e.target === overlay) closeModal();
});
shadow.appendChild(overlay);
// 事件绑定与初始渲染
const updatePreview = debounce(renderPreview, 120);
diffMinSel.addEventListener('change', function () {
state.diffMin = +diffMinSel.value;
if (state.diffMin > state.diffMax) {
state.diffMax = state.diffMin;
diffMaxSel.value = String(state.diffMax);
}
persistState();
updatePreview();
});
diffMaxSel.addEventListener('change', function () {
state.diffMax = +diffMaxSel.value;
if (state.diffMax < state.diffMin) {
state.diffMin = state.diffMax;
diffMinSel.value = String(state.diffMin);
}
persistState();
updatePreview();
});
pidFrom.addEventListener('input', function () {
state.pidFrom = pidFrom.value;
persistState();
updatePreview();
});
pidTo.addEventListener('input', function () {
state.pidTo = pidTo.value;
persistState();
updatePreview();
});
yearFrom.addEventListener('change', function () {
state.yearFrom = yearFrom.value;
if (state.yearFrom && state.yearTo && +state.yearFrom > +state.yearTo) {
state.yearTo = state.yearFrom;
yearTo.value = state.yearTo;
}
persistState();
updatePreview();
});
yearTo.addEventListener('change', function () {
state.yearTo = yearTo.value;
if (state.yearFrom && state.yearTo && +state.yearFrom > +state.yearTo) {
state.yearFrom = state.yearTo;
yearFrom.value = state.yearFrom;
}
persistState();
updatePreview();
});
kwInput.addEventListener('input', function () {
state.keyword = kwInput.value;
persistState();
updatePreview();
});
anyRadio.addEventListener('change', function () {
state.tagMode = 'any';
persistState();
updatePreview();
});
allRadio.addEventListener('change', function () {
state.tagMode = 'all';
persistState();
updatePreview();
});
exclChk.addEventListener('change', function () {
state.excludeRepeat = exclChk.checked;
persistState();
});
autoChk.addEventListener('change', function () {
state.autoJump = autoChk.checked;
persistState();
});
syncBtn.addEventListener('click', function () {
startSync();
});
goBtn.addEventListener('click', function () {
doPick();
});
ui = {
syncbar: syncbar,
syncMsg: syncMsg,
syncBar: syncBar,
diffMinSel: diffMinSel,
diffMaxSel: diffMaxSel,
pidFrom: pidFrom,
pidTo: pidTo,
yearFrom: yearFrom,
yearTo: yearTo,
kwInput: kwInput,
anyRadio: anyRadio,
allRadio: allRadio,
exclChk: exclChk,
autoChk: autoChk,
matchNum: matchNum,
goBtn: goBtn,
result: result,
closeBtn: closeBtn,
};
}
let ui = null;
function makeLabel(text) {
const l = document.createElement('label');
l.textContent = text;
return l;
}
function makeHint(text) {
const s = document.createElement('div');
s.className = 'range-hint';
s.textContent = text;
return s;
}
function debounce(fn, ms) {
let t = null;
return function () {
clearTimeout(t);
t = setTimeout(fn, ms);
};
}
function fillYearOptions(select, years, selected, placeholder) {
select.innerHTML = '';
const none = new Option(placeholder, '');
select.appendChild(none);
for (const y of years) {
select.appendChild(new Option(String(y), String(y)));
}
if (selected) select.value = String(selected);
}
function rebuildTagPicker(tags) {
if (!panelEl) return;
panelEl.innerHTML = '';
tagInfo = buildTagIndex(tags);
const byId = tagInfo.byId;
const bar = document.createElement('div');
bar.className = 'tag-bar';
const search = document.createElement('input');
search.className = 'tag-search';
search.placeholder = '搜索标签名,如“背包”“数论”';
const info = document.createElement('span');
info.className = 'tag-sel-info';
info.textContent = '已选 0 个';
const clearBtn = document.createElement('button');
clearBtn.className = 'tag-clear';
clearBtn.textContent = '清空';
bar.appendChild(search);
bar.appendChild(info);
bar.appendChild(clearBtn);
panelEl.appendChild(bar);
// 快速标签
const quick = document.createElement('div');
quick.className = 'quick';
const qLabel = document.createElement('span');
qLabel.className = 'qlabel';
qLabel.textContent = '常用:';
quick.appendChild(qLabel);
const quickChips = [];
for (const name of CURATED_NAMES) {
const t = tags.find(function (x) { return x.name === name; });
if (t) quickChips.push(t);
}
for (const t of quickChips) {
quick.appendChild(buildChip(t.id, t.name));
}
panelEl.appendChild(quick);
// 分组
const groups = document.createElement('div');
groups.className = 'tag-groups';
const sections = [];
sections.push({ title: '算法标签', type: 2 });
sections.push({ title: '题目来源', type: 3 });
sections.push({ title: '题目性质', type: 5 });
sections.push({ title: '地区', type: 1 });
for (const sec of sections) {
const sub = groupByRoot(tags, sec.type, byId);
const flat = [];
const tree = [];
for (const g of sub) {
if (g.children.length === 1 && g.children[0].id === g.root.id) {
flat.push(g.children[0]);
} else {
tree.push(g);
}
}
if (flat.length) {
const label = document.createElement('div');
label.className = 'flat-title';
label.textContent = sec.title;
const chips = document.createElement('div');
chips.className = 'chips';
flat.sort(function (a, b) {
return String(a.name).localeCompare(String(b.name), 'zh-CN');
});
for (const t of flat) {
chips.appendChild(buildChip(t.id, t.name, 'flat-' + t.id));
}
groups.appendChild(label);
groups.appendChild(chips);
}
for (const g of tree) {
const det = document.createElement('details');
const sum = document.createElement('summary');
const label = (g.root && g.root.name) || sec.title;
sum.innerHTML = esc(label) + '<span class="cnt">' + g.children.length + '</span>';
const chips = document.createElement('div');
chips.className = 'chips';
const ordered = g.children.slice().sort(function (a, b) {
const na = String(a.name).length;
const nb = String(b.name).length;
return na - nb || String(a.name).localeCompare(String(b.name), 'zh-CN');
});
for (const t of ordered) {
chips.appendChild(buildChip(t.id, t.name, String(g.root.id) + '-' + t.id));
}
det.appendChild(sum);
det.appendChild(chips);
groups.appendChild(det);
}
}
panelEl.appendChild(groups);
clearBtn.addEventListener('click', function () {
state.tags = [];
persistState();
syncTagUI();
renderPreview();
});
search.addEventListener('input', function () {
const kw = search.value.trim().toLowerCase();
groups.querySelectorAll('details').forEach(function (det) {
let show = false;
det.querySelectorAll('.chip').forEach(function (chip) {
const ok = !kw || chip.getAttribute('data-name').toLowerCase().indexOf(kw) >= 0;
chip.style.display = ok ? '' : 'none';
if (ok) show = true;
});
det.style.display = show ? '' : 'none';
});
});
// 打开包含已选标签的组
try {
groups.querySelectorAll('details').forEach(function (det) {
let has = false;
det.querySelectorAll('.chip').forEach(function (chip) {
if (state.tags.indexOf(+chip.getAttribute('data-id')) >= 0) has = true;
});
if (has) det.open = true;
});
} catch (e) {
// ignore
}
}
function buildChip(id, name, key) {
const chip = document.createElement('label');
chip.className = 'chip';
chip.setAttribute('data-id', id);
chip.setAttribute('data-name', name);
chip.setAttribute('data-key', key || String(id));
const cb = document.createElement('input');
cb.type = 'checkbox';
cb.value = String(id);
const span = document.createElement('span');
span.textContent = name;
chip.appendChild(cb);
chip.appendChild(span);
chip.addEventListener('click', function () {
// 用 click 完成切换
});
cb.addEventListener('change', function () {
updateTagSelection();
});
return chip;
}
function collectCheckedChips() {
const ids = [];
if (!panelEl) return ids;
panelEl.querySelectorAll('.chip input:checked').forEach(function (cb) {
const v = +cb.value;
if (Number.isFinite(v) && ids.indexOf(v) < 0) ids.push(v);
});
return ids;
}
function syncTagUI() {
if (!panelEl) return;
const wanted = new Set(state.tags);
panelEl.querySelectorAll('.chip').forEach(function (chip) {
const id = +chip.getAttribute('data-id');
const cb = chip.querySelector('input');
if (wanted.has(id) && !cb.checked) cb.checked = true;
if (!wanted.has(id) && cb.checked) cb.checked = false;
chip.classList.toggle('on', wanted.has(id));
});
const radios = panelEl.querySelectorAll('.tag-bar input[type=radio]');
radios.forEach(function (r) {
r.checked = r.value === state.tagMode;
});
const info = panelEl.querySelector('.tag-sel-info');
if (info) info.textContent = '已选 ' + state.tags.length + ' 个';
}
function updateTagSelection() {
state.tags = collectCheckedChips();
persistState();
syncTagUI();
renderPreview();
}
function renderPreview() {
if (!ui || !ui.matchNum) return;
if (!problems.length) {
ui.matchNum.innerHTML = '题库未同步:首次使用会自动建立本地索引(约 1~2 分钟),完成后即可离线秒抽';
ui.goBtn.disabled = true;
return;
}
const n = countMatches(problems, makeFilter(state, tagInfo));
const metaPrefix = metaPrefixText();
ui.matchNum.innerHTML = metaPrefix + '当前条件下可抽 <b>' + n + '</b> 题';
if (n === 0) ui.goBtn.disabled = true;
else ui.goBtn.disabled = false;
}
function metaPrefixText() {
if (!meta || !meta.ts) return '';
const date = new Date(meta.ts);
const pad = function (v) { return v < 10 ? '0' + v : String(v); };
const stale = Date.now() - meta.ts > INDEX_TTL;
return (
'题库 ' + (meta.count || 0) + ' 题 · ' +
date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()) +
(stale ? '(已过期,建议更新)' : '') + ' · '
);
}
function showResult(p, skipped) {
if (!resultEl) return;
resultEl.innerHTML = '';
clearJumpTimer();
const d = diffLabel(p.diff);
const head = document.createElement('div');
head.className = 'res-pid';
head.textContent = p.pid;
const name = document.createElement('div');
name.className = 'res-name';
name.textContent = p.name;
const meta = document.createElement('div');
meta.className = 'res-meta';
const badge = document.createElement('span');
badge.className = 'badge';
badge.style.background = d.color;
badge.textContent = d.name;
meta.appendChild(badge);
const url = SITE + '/problem/' + p.pid;
const link = document.createElement('a');
link.className = 'link';
link.href = url;
link.target = '_blank';
link.rel = 'noopener';
link.textContent = '题目链接 ↗';
meta.appendChild(link);
resultEl.appendChild(head);
resultEl.appendChild(name);
resultEl.appendChild(meta);
const tagRow = document.createElement('div');
tagRow.className = 'res-tags';
const names = tagNames(p.tags);
for (const n of names.slice(0, 12)) {
const s = document.createElement('span');
s.className = 'res-tag';
s.textContent = n;
tagRow.appendChild(s);
}
if (names.length > 12) {
const more = document.createElement('span');
more.className = 'res-tag';
more.textContent = '+' + (names.length - 12);
tagRow.appendChild(more);
}
resultEl.appendChild(tagRow);
const actions = document.createElement('div');
actions.className = 'res-actions';
const again = document.createElement('button');
again.className = 'btn btn-ghost btn-sm';
again.textContent = '换一题';
const openBtn = document.createElement('button');
openBtn.className = 'btn btn-primary btn-sm';
openBtn.textContent = '开始挑战 →';
actions.appendChild(again);
actions.appendChild(openBtn);
resultEl.appendChild(actions);
again.addEventListener('click', function () {
doPick();
});
openBtn.addEventListener('click', function () {
window.location.href = url;
});
resultEl.classList.add('show');
if (skipped) toast('已排除题都被抽过啦,本次允许重复');
if (state.autoJump) {
const note = document.createElement('div');
note.className = 'jump-note';
note.textContent = '1.2 秒后自动跳转…(点击“开始挑战”可立即前往)';
resultEl.appendChild(note);
jumpTimer = setTimeout(function () {
window.location.href = url;
}, 1200);
}
}
function clearJumpTimer() {
if (jumpTimer) {
clearTimeout(jumpTimer);
jumpTimer = null;
}
}
function doPick() {
clearJumpTimer();
if (!problems.length) {
toast('题库索引为空,请先同步题库');
return;
}
const res = pickOne(problems, makeFilter(state, tagInfo), state.excludeRepeat ? sessionSeen : null);
if (!res) {
toast('没有符合条件的题目,试试放宽条件');
return;
}
sessionSeen.add(res.problem.pid);
if (state.excludeRepeat) saveSessionSeen();
showResult(res.problem, res.skipped);
}
async function startSync() {
if (syncing) return;
syncing = true;
syncAbort = { aborted: false };
ui.syncbar.classList.remove('hidden');
ui.goBtn.disabled = true;
try {
const result = await syncIndex(function (done, total, page, pages, msg) {
ui.syncMsg.textContent = msg + ':' + done + ' / ' + total + ' 题(' + page + ' / ' + pages + ' 页)';
const pct = total ? Math.min(100, Math.round((done / total) * 100)) : 0;
ui.syncBar.style.width = pct + '%';
});
meta = { ts: Date.now(), ver: SCRIPT_VERSION, count: result.count };
problems = result.problems;
ui.syncMsg.textContent = '同步完成,共 ' + problems.length + ' 题';
ui.syncBar.style.width = '100%';
renderPreview();
if (!result.complete) {
toast('部分页面同步失败,可再点一次“更新题库”重试');
} else if (!result.saved) {
toast('浏览器存储空间不足,本次索引仅在当前页面有效');
}
} catch (e) {
const aborted = e && e.message === 'ABORTED';
const cached = loadCachedProblems();
if (cached) {
problems = cached.problems;
meta = cached.meta;
}
ui.syncMsg.textContent = aborted
? '已取消同步'
: '同步失败(' + (e && e.message ? e.message : '网络错误') + '),请重试';
ui.syncBar.style.width = '0%';
} finally {
syncing = false;
syncAbort = null;
setTimeout(function () {
if (ui.syncbar) ui.syncbar.classList.add('hidden');
}, 1200);
renderPreview();
}
}
function openModal() {
if (!modalEl) return;
clearJumpTimer();
const overlay = modalEl.parentElement;
overlay.classList.add('open');
document.body.appendChild(root);
applyStateToUI();
renderPreview();
if (!problems.length) {
startSync();
} else if (Date.now() - (meta && meta.ts || 0) > INDEX_TTL) {
toast('题库数据已过期,点击“更新题库”刷新');
}
}
function closeModal() {
clearJumpTimer();
if (modalEl) modalEl.parentElement.classList.remove('open');
}
function applyStateToUI() {
if (!ui) return;
ui.diffMinSel.value = String(state.diffMin);
ui.diffMaxSel.value = String(state.diffMax);
ui.pidFrom.value = state.pidFrom;
ui.pidTo.value = state.pidTo;
refreshYearSelects();
ui.kwInput.value = state.keyword;
ui.anyRadio.checked = state.tagMode === 'any';
ui.allRadio.checked = state.tagMode === 'all';
ui.exclChk.checked = state.excludeRepeat;
ui.autoChk.checked = state.autoJump;
syncTagUI();
}
function refreshYearSelects() {
if (!ui) return;
const years = yearTagMap(tagInfo.tags);
const yearList = [...years.keys()].sort(function (a, b) { return a - b; });
fillYearOptions(ui.yearFrom, yearList, state.yearFrom, '不限');
fillYearOptions(ui.yearTo, yearList, state.yearTo, '不限');
}
async function init() {
if (!window || !window.document || !window.location || window.location.hostname.indexOf('luogu.com.cn') < 0) return;
loadState();
loadSessionSeen();
root = document.createElement('div');
shadow = root.attachShadow({ mode: 'open' });
const style = document.createElement('style');
style.textContent = css();
shadow.appendChild(style);
document.body.appendChild(root);
const fab = document.createElement('button');
fab.className = 'fab';
fab.innerHTML = '<span class="dice">🎲</span><span>随机跳题</span>';
fab.addEventListener('click', function () {
openModal();
});
shadow.appendChild(fab);
buildModal();
const tags = await ensureTags();
tagInfo = buildTagIndex(tags);
rebuildTagPicker(tags);
refreshYearSelects();
syncTagUI();
renderPreview();
const cached = loadCachedProblems();
if (cached) {
problems = cached.problems;
meta = cached.meta;
}
}
// Node 环境导出核心逻辑用于测试
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
SCRIPT_VERSION: SCRIPT_VERSION,
DIFFS: DIFFS,
parseListHTML: parseListHTML,
encodeProblems: encodeProblems,
decodeProblems: decodeProblems,
pidNumber: pidNumber,
makeFilter: makeFilter,
buildTagIndex: buildTagIndex,
yearTagMap: yearTagMap,
groupByRoot: groupByRoot,
countMatches: countMatches,
pickOne: pickOne,
sanitizeState: sanitizeState,
};
return;
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})();
Tip:注意 抽中后直接跳转 选项.
CF Better
AT Better

浙公网安备 33010602011771号