JavaScript// ==UserScript==
// @name Luogu 个性化插件
// @namespace https://www.luogu.com.cn/
// @version 5.1.0
// @description 显示洛谷题目难度颜色;让主题背景图铺满全屏,并让顶部导航栏与侧边栏半透明
// @author realskc, Assistant(整合)
// @match https://www.luogu.com.cn/*
// @match https://*.luogu.com.cn/*
// @grant none
// @run-at document-start
// ==/UserScript==
'use strict';
(function () {
/* ==================== 公共工具 ==================== */
// 注入 <style>:不依赖 GM_addStyle,保持 @grant none 以便直接访问页面全局变量
function injectStyle(cssText) {
const style = document.createElement('style');
style.textContent = cssText;
const parent = document.head || document.documentElement;
if (parent) {
parent.appendChild(style);
return;
}
// document-start 极早期兜底:等根节点出现
const obs = new MutationObserver(() => {
const p = document.head || document.documentElement;
if (p) {
obs.disconnect();
p.appendChild(style);
}
});
obs.observe(document, { childList: true, subtree: true });
}
function onDomReady(fn) {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', fn, { once: true });
} else {
fn();
}
}
function onDocumentElementReady(fn) {
if (document.documentElement) {
fn(document.documentElement);
return;
}
const obs = new MutationObserver(() => {
if (document.documentElement) {
obs.disconnect();
fn(document.documentElement);
}
});
obs.observe(document, { childList: true, subtree: true });
}
/* ==================== 一、全屏背景 + 导航/侧边栏半透明 ==================== */
const OPACITY = 65; // 导航栏/侧边栏不透明度百分比(保留多少原色,建议 40~80)
const BLUR_PX = 16; // 毛玻璃模糊程度(像素)
injectStyle(`
/* ===== 让 html 和 body 接管全屏背景 ===== */
html, body {
background-color: var(--theme-body-back, #ffffff) !important;
background-image: var(--theme-body-color, none), var(--theme-body-image, none) !important;
background-repeat: no-repeat, no-repeat !important;
background-size: cover, cover !important;
background-position: center, center !important;
background-attachment: fixed, fixed !important;
}
/* 隐藏洛谷原本限制在主内容区的背景伪元素,避免重复渲染 */
.theme-page::before {
display: none !important;
}
.theme-page {
background-color: transparent !important;
}
/* ===== 顶部导航栏 (.top-bar) 半透明 ===== */
.top-bar {
background-color: color-mix(
in srgb,
var(--theme-navi-back, #ffffff) ${OPACITY}%,
transparent
) !important;
backdrop-filter: blur(${BLUR_PX}px) !important;
-webkit-backdrop-filter: blur(${BLUR_PX}px) !important;
border-bottom: 1px solid rgba(128, 128, 128, 0.15) !important;
}
/* ===== 左侧边栏 (.sidebar, .lside) 半透明 ===== */
.sidebar,
.lside {
background-color: color-mix(
in srgb,
var(--theme-sidebar-back, var(--theme-navi-back, #ffffff)) ${OPACITY}%,
transparent
) !important;
backdrop-filter: blur(${BLUR_PX}px) !important;
-webkit-backdrop-filter: blur(${BLUR_PX}px) !important;
border-right: 1px solid rgba(128, 128, 128, 0.15) !important;
}
`);
// 将 .theme-page 上的背景变量同步到根节点 html
function syncThemeBackground() {
const themePage = document.querySelector('.theme-page');
if (!themePage) return;
const root = document.documentElement;
const properties = [
'--theme-body-back',
'--theme-body-image',
'--theme-body-image-repeat',
'--theme-body-image-size',
'--theme-body-image-position',
'--theme-body-color',
'--theme-body-color-filter',
'--theme-body-mask'
];
properties.forEach(prop => {
const val = themePage.style.getPropertyValue(prop);
if (val) {
root.style.setProperty(prop, val);
}
});
}
document.addEventListener('DOMContentLoaded', syncThemeBackground);
const themeAttrObserver = new MutationObserver(syncThemeBackground);
onDocumentElementReady(() => {
const domObserver = new MutationObserver(() => {
const themePage = document.querySelector('.theme-page');
if (themePage) {
themeAttrObserver.observe(themePage, {
attributes: true,
attributeFilter: ['style', 'class']
});
syncThemeBackground();
}
});
domObserver.observe(document.documentElement, {
childList: true,
subtree: true
});
syncThemeBackground();
});
/* ==================== 二、题目难度颜色 ==================== */
const problemDifficultyToColor = [
[191, 191, 191],
[254, 76, 97],
[243, 156, 17],
[255, 193, 22],
[82, 196, 26],
[19, 194, 194],
[52, 152, 219],
[157, 61, 207],
[14, 29, 105]
];
const problemToColorMap = new Map();
class FetchRateLimiter {
constructor(limit) {
this.limit = limit;
this.queue = [];
this.queuePrior = [];
this.active = false;
this.requestCache = new Map();
}
process() {
this.active = true;
let resolve, reject, url;
if (this.queuePrior.length > 0) {
({ resolve, reject, url } = this.queuePrior.shift());
} else if (this.queue.length > 0) {
({ resolve, reject, url } = this.queue.shift());
} else {
this.active = false;
return;
}
fetch(url)
.then(resolve)
.catch(reject);
setTimeout(this.process.bind(this), this.limit);
}
push(url, prior) {
if (this.requestCache.has(url)) {
return this.requestCache.get(url);
}
const request = new Promise((resolve, reject) => {
if (prior) {
this.queuePrior.push({ url, resolve, reject });
} else {
this.queue.push({ url, resolve, reject });
}
if (!this.active) {
this.process();
}
}).then(response => response.text());
this.requestCache.set(url, request);
return request;
}
}
const limiter = new FetchRateLimiter(300);
function fillPracticeProblems(problemList) {
if (!Array.isArray(problemList) || problemList.lgbot1Visited) {
return;
}
for (const item of problemList) {
if (
item &&
item.pid &&
Number.isInteger(item.difficulty) &&
problemDifficultyToColor[item.difficulty]
) {
problemToColorMap.set(
item.pid,
`rgb(${problemDifficultyToColor[item.difficulty].join(',')})`
);
}
}
problemList.lgbot1Visited = true;
}
async function getProblemColor(problemid, prior = false) {
// 原脚本在 document-end 执行 + 500ms 延迟;合并后改为 DOM 就绪后再延迟,行为一致
onDomReady(() => {
// 题库页没有可着色的题目链接,直接跳过整个颜色功能
if (window.location.pathname === '/problem/list') {
return;
}
setTimeout(addProblemsColor, 500);
});
if (window.location.href.startsWith('https://www.luogu.com.cn/record/list')) {
if (typeof _feInstance !== 'undefined') {
const resultList = _feInstance.currentData?.records?.result;
if (Array.isArray(resultList) && !resultList.lgbot1Visited) {
for (const item of resultList) {
const problem = item.problem;
if (
problem &&
problem.pid &&
Number.isInteger(problem.difficulty) &&
problemDifficultyToColor[problem.difficulty]
) {
problemToColorMap.set(
problem.pid,
`rgb(${problemDifficultyToColor[problem.difficulty].join(',')})`
);
}
}
resultList.lgbot1Visited = true;
}
}
}
if (/^https:\/\/www\.luogu\.com\.cn\/user\/\d+#practice$/.test(window.location.href)) {
if (typeof _feInstance !== 'undefined') {
fillPracticeProblems(_feInstance.currentData?.submittedProblems);
fillPracticeProblems(_feInstance.currentData?.passedProblems);
}
}
if (problemToColorMap.has(problemid)) {
return problemToColorMap.get(problemid);
}
const url = '/problem/' + problemid;
let data;
try {
data = await limiter.push(url, prior);
} catch (error) {
console.error('Error fetching problem data:', error, problemid);
return;
}
const parser = new DOMParser();
const doc = parser.parseFromString(data, 'text/html');
let scriptText = '';
for (const script of doc.querySelectorAll('script')) {
scriptText += script.textContent;
}
const match = scriptText.match(/"difficulty":(\d+)/);
if (!match) {
return;
}
const difficulty = Number(match[1]);
const colorArray = problemDifficultyToColor[difficulty];
if (!colorArray) {
return;
}
const color = `rgb(${colorArray.join(',')})`;
problemToColorMap.set(problemid, color);
return color;
}
function isProblemId(problemid) {
if (problemid.startsWith('AT_')) {
return true;
}
if (!/[a-zA-Z]/.test(problemid)) {
return false;
}
if (!/[0-9]/.test(problemid)) {
return false;
}
return true;
}
/* 【修复 1】快速过滤 + 防重复处理 */
function isPotentialProblemLink(item) {
const href = item.getAttribute('href') || '';
if (href.includes('/problem/')) return true;
// 兼容题库/比赛里 href="javascript:void 0" 的题目标题链接
if (item.matches('a[data-v-bade3303][data-v-4842157a]')) return true;
return false;
}
async function addProblemColor(item) {
if (!isPotentialProblemLink(item)) return; // 非题目链接直接跳过,不读 innerText
if (item.dataset.lgbot1Colored === '1') return; // 已处理过,避免 observer 回环
let problemid = item.href.split('/').pop();
let prior = false;
if (problemid.includes('?forum=')) {
problemid = problemid.split('=').pop();
prior = true;
}
problemid = problemid.split('?')[0];
problemid = problemid.split('=').pop();
if (item.matches('a[data-v-bade3303][data-v-4842157a]')) {
if (problemid === 'javascript:void 0') {
problemid = (item.textContent || '').split(' ')[0];
}
}
if (!isProblemId(problemid)) {
return;
}
// 用 textContent 代替 innerText,避免强制重排
const text = item.textContent || '';
if (text.startsWith(problemid)) {
const spanItem = item.children[0];
if (
spanItem &&
spanItem.matches('span.pid') &&
spanItem.textContent === problemid
) {
const color = await getProblemColor(problemid, prior);
if (!color) return;
spanItem.style.color = color;
spanItem.style.fontWeight = 'bold';
item.dataset.lgbot1Colored = '1';
} else {
const color = await getProblemColor(problemid, prior);
if (!color) return;
const content = item.innerHTML;
item.innerHTML = content.replace(
problemid,
`<b style="color: ${color};">${problemid}</b>`
);
item.dataset.lgbot1Colored = '1';
}
}
}
/* 【修复 3】MutationObserver 只查题目链接 */
function addProblemsColor() {
const SELECTOR = 'a[href*="/problem/"], a[data-v-bade3303][data-v-4842157a]';
const observer = new MutationObserver(async mutationsList => {
for (const mutation of mutationsList) {
if (mutation.type === 'childList') {
for (const addedNode of mutation.addedNodes) {
if (addedNode.nodeType !== Node.ELEMENT_NODE) {
continue;
}
if (addedNode.matches(SELECTOR)) {
addProblemColor(addedNode);
}
const newItems = addedNode.querySelectorAll(SELECTOR);
for (const newItem of newItems) {
addProblemColor(newItem);
}
}
} else if (mutation.type === 'characterData') {
const parent = mutation.target.parentElement;
if (parent && parent.matches('span.pid')) {
const color = await getProblemColor(mutation.target.textContent);
if (color) {
parent.style.color = color;
parent.style.fontWeight = 'bold';
}
}
}
}
});
observer.observe(document, {
childList: true,
subtree: true,
characterData: true
});
const nodelist = document.querySelectorAll(SELECTOR);
for (const item of nodelist) {
addProblemColor(item);
}
}
// 原脚本在 document-end 执行 + 500ms 延迟;合并后改为 DOM 就绪后再延迟,行为一致
onDomReady(() => {
setTimeout(addProblemsColor, 500);
});
})();