JavaScript// ==UserScript==
// @name BZOJ 综合增强:测试点大方块 + 分区字体恢复
// @namespace https://bzoj.org/
// @version 1.0.0
// @description 适用于任意 Hydro OJ 的测试点大方块、自动轮询、字体独立设置;无分数显示;悬停仅显示状态名+耗时+内存
// @author bzoj-enhancer
// @match https://*/*
// @grant GM_notification
// @grant GM_addStyle
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_registerMenuCommand
// @run-at document-end
// ==/UserScript==
(function () {
'use strict';
// ==================== 分区字体恢复模块 ====================
const FontModule = {
STORAGE_UI_FONT: 'bzoj_ui_font',
STORAGE_CODE_FONT: 'bzoj_code_font',
currentUiFont: '',
currentCodeFont: '',
init: function () {
this.currentUiFont = GM_getValue(this.STORAGE_UI_FONT, '');
this.currentCodeFont = GM_getValue(this.STORAGE_CODE_FONT, '');
if (this.currentUiFont || this.currentCodeFont) {
this.applyFonts(this.currentUiFont, this.currentCodeFont);
}
if (window.location.pathname.includes('/home/settings/preference')) {
this.wakeUpPreferencePage();
}
GM_registerMenuCommand('⚙️ 前往字体偏好设置', () => {
const domain = window.location.origin;
window.open(domain + '/home/settings/preference', '_blank');
});
},
applyFonts: function (uiFont, codeFont) {
const oldStyle = document.getElementById('bzoj-font-style');
if (oldStyle) oldStyle.remove();
if (!uiFont && !codeFont) return;
let css = '';
if (uiFont) {
css += `
body, p, span, div, a, li, td, th, h1, h2, h3, h4, h5, h6,
input, textarea, button, select, label, table, caption,
.markdown-body, .section__title, .user-info, .menu-item,
.dialog__body, .page-header, .breadcrumb {
font-family: ${uiFont} !important;
}
`;
}
if (codeFont) {
css += `
pre, code, .CodeMirror, .monaco-editor, .code-area,
[class*="code"], [class*="Code"],
.problem-detail pre, .submission-code, .editor-container,
.ace_editor, .hljs, .syntaxhighlighter,
.markdown-body pre, .markdown-body code,
.code-editor, .monaco-editor .view-lines {
font-family: ${codeFont} !important;
}
`;
}
if (css) {
GM_addStyle(css);
const styles = document.querySelectorAll('style');
const lastStyle = styles[styles.length - 1];
if (lastStyle) lastStyle.id = 'bzoj-font-style';
}
},
saveFontSettings: function (uiFont, codeFont) {
this.currentUiFont = uiFont;
this.currentCodeFont = codeFont;
GM_setValue(this.STORAGE_UI_FONT, uiFont);
GM_setValue(this.STORAGE_CODE_FONT, codeFont);
this.applyFonts(uiFont, codeFont);
},
wakeUpPreferencePage: function () {
const self = this;
const observer = new MutationObserver(() => {
const fontInputs = document.querySelectorAll('select, input');
let uiFontElement = null;
let codeFontElement = null;
fontInputs.forEach(el => {
const name = (el.name || el.id || '').toLowerCase();
const placeholder = (el.placeholder || '').toLowerCase();
const label = (el.closest('label')?.textContent || '').toLowerCase();
if (name.includes('ui') && name.includes('font') ||
label.includes('界面') && label.includes('字体') ||
placeholder.includes('界面字体')) {
uiFontElement = el;
}
if (name.includes('code') && name.includes('font') ||
label.includes('代码') && label.includes('字体') ||
placeholder.includes('代码字体')) {
codeFontElement = el;
}
});
if (!uiFontElement || !codeFontElement) {
const allInputs = document.querySelectorAll('input, select, textarea');
for (const el of allInputs) {
const parentText = (el.closest('.form-group')?.textContent || '') +
(el.closest('tr')?.textContent || '');
if (!uiFontElement && parentText.includes('界面') && parentText.includes('字体')) {
uiFontElement = el;
}
if (!codeFontElement && parentText.includes('代码') && parentText.includes('字体')) {
codeFontElement = el;
}
}
}
if (!uiFontElement || !codeFontElement) return;
[uiFontElement, codeFontElement].forEach(el => {
el.disabled = false;
el.style.display = '';
el.style.visibility = '';
el.removeAttribute('hidden');
let parent = el.parentElement;
while (parent && parent !== document.body) {
if (parent.style.display === 'none') parent.style.display = '';
if (parent.style.visibility === 'hidden') parent.style.visibility = '';
if (parent.hasAttribute('hidden')) parent.removeAttribute('hidden');
parent = parent.parentElement;
}
});
if (self.currentUiFont && uiFontElement.value !== self.currentUiFont) {
uiFontElement.value = self.currentUiFont;
}
if (self.currentCodeFont && codeFontElement.value !== self.currentCodeFont) {
codeFontElement.value = self.currentCodeFont;
}
const handleChange = () => {
const newUi = uiFontElement.value.trim();
const newCode = codeFontElement.value.trim();
self.saveFontSettings(newUi, newCode);
};
uiFontElement.addEventListener('change', handleChange);
codeFontElement.addEventListener('change', handleChange);
if (uiFontElement.tagName === 'INPUT') uiFontElement.addEventListener('input', handleChange);
if (codeFontElement.tagName === 'INPUT') codeFontElement.addEventListener('input', handleChange);
observer.disconnect();
});
observer.observe(document.body, { childList: true, subtree: true });
}
};
// ==================== 测试点大方块模块 ====================
const TestcaseModule = {
STATUS_MAP: {
'accepted': { bg: '#52C41A', text: 'AC', display: 'Accepted', color: '#fff' },
'wrong answer': { bg: '#E74C3C', text: 'WA', display: 'Wrong Answer', color: '#fff' },
'time limit exceeded': { bg: '#052242', text: 'TLE', display: 'Time Limit Exceeded', color: '#fff' },
'memory limit exceeded':{ bg: '#052242', text: 'MLE', display: 'Memory Limit Exceeded', color: '#fff' },
'runtime error': { bg: '#9D3DCF', text: 'RE', display: 'Runtime Error', color: '#fff' },
'compile error': { bg: '#FADB14', text: 'CE', display: 'Compile Error', color: '#333' },
'output limit exceeded':{ bg: '#052242', text: 'OLE', display: 'Output Limit Exceeded', color: '#fff' },
'system error': { bg: '#000000', text: 'SE', display: 'System Error', color: '#fff' },
'judging': { bg: '#64b5f6', text: '⟳', display: 'Judging', color: '#fff', spin: true },
'compiling': { bg: '#64b5f6', text: '⟳', display: 'Compiling', color: '#fff', spin: true },
'waiting': { bg: '#64b5f6', text: '⟳', display: 'Waiting', color: '#fff', spin: true },
'running': { bg: '#64b5f6', text: '⟳', display: 'Running', color: '#fff', spin: true },
'fetched': { bg: '#B8860B', text: 'FET', display: 'Fetched', color: '#fff' },
},
ALIAS_MAP: {
'time exceeded': 'time limit exceeded',
'memory exceeded': 'memory limit exceeded',
'ac': 'accepted', 'wa': 'wrong answer', 'tle': 'time limit exceeded',
'mle': 'memory limit exceeded', 're': 'runtime error', 'ce': 'compile error',
'ole': 'output limit exceeded', 'se': 'system error',
},
PENDING_STATES: new Set(['waiting', 'compiling', 'running', 'judging', 'pending', 'queueing', 'fetched']),
POLL_INTERVAL: 1.5,
lastBannerKey: '',
pollTimer: null,
lastOverallStatus: '',
observer: null,
themeObserver: null,
containerElem: null,
// 提取纯净状态名(用于方块缩写和通知)
extractStatus: function(raw) {
if (!raw) return '';
const firstLine = raw.trim().split('\n')[0];
const statusNames = [
'Accepted', 'Wrong Answer', 'Time Limit Exceeded', 'Memory Limit Exceeded',
'Runtime Error', 'Compile Error', 'Output Limit Exceeded', 'System Error',
'Judging', 'Compiling', 'Waiting', 'Running', 'Fetched'
];
for (const name of statusNames) {
if (firstLine.toLowerCase().includes(name.toLowerCase())) return name;
}
for (const alias of Object.keys(this.ALIAS_MAP)) {
if (firstLine.toLowerCase().includes(alias)) return alias;
}
return firstLine.substring(0, 40);
},
normalizeStatus: function(raw) {
if (!raw) return '';
let text = raw.trim().toLowerCase();
if (this.ALIAS_MAP[text]) return this.ALIAS_MAP[text];
if (this.STATUS_MAP[text]) return text;
for (const key of Object.keys(this.STATUS_MAP)) {
if (text.includes(key)) return key;
}
return text.substring(0, 30);
},
getStatusInfo: function(key) {
return this.STATUS_MAP[key] || { bg: '#9e9e9e', text: key.substring(0,3).toUpperCase(), display: key, color: '#fff' };
},
isFinished: function(key) {
return key && !this.PENDING_STATES.has(key);
},
getOverallStatusKey: function(doc = document) {
const primary = doc.querySelector('.record-status--text');
if (primary) {
const status = this.extractStatus(primary.textContent.trim());
return this.normalizeStatus(status);
}
const dataEl = doc.querySelector('[data-status]');
if (dataEl) {
const ds = dataEl.getAttribute('data-status');
if (ds) return this.normalizeStatus(this.extractStatus(ds));
}
const cells = doc.querySelectorAll('.detail-status, td[class*="status"]');
for (const cell of cells) {
const text = cell.textContent.trim();
if (text.includes('#') && text.includes('ms')) continue;
if (text.length < 40 && text.length > 0) return this.normalizeStatus(this.extractStatus(text));
}
const bodyText = doc.body.innerText.toLowerCase();
const checkOrder = ['accepted', 'wrong answer', 'time limit exceeded', 'memory limit exceeded',
'runtime error', 'compile error', 'output limit exceeded', 'system error',
'judging', 'compiling', 'waiting', 'running', 'fetched'];
for (const kw of checkOrder) if (bodyText.includes(kw)) return kw;
return '';
},
getWorstStatus: function(testcases) {
const severity = {
'system error': 10, 'runtime error': 9, 'memory limit exceeded': 8,
'time limit exceeded': 7, 'output limit exceeded': 6, 'wrong answer': 5,
'compile error': 4, 'accepted': 3,
};
let worst = 'accepted', worstScore = 0;
for (const tc of testcases) {
const s = severity[tc.key] || 0;
if (s > worstScore) { worstScore = s; worst = tc.key; }
}
return worst;
},
notifyAndBanner: function(statusKey) {
if (statusKey === this.lastBannerKey) return;
this.lastBannerKey = statusKey;
const info = this.getStatusInfo(statusKey);
const notifyTitle = '评测状态更新';
if (typeof GM_notification !== 'undefined') {
GM_notification({ title: notifyTitle, text: info.display, timeout: 5000 });
} else if ('Notification' in window && Notification.permission === 'granted') {
new Notification(notifyTitle, { body: info.display });
}
const old = document.getElementById('bzoj-auto-banner');
if (old) old.remove();
const banner = document.createElement('div');
banner.id = 'bzoj-auto-banner';
banner.style.cssText = `
position:fixed; top:0; left:0; right:0; z-index:2147483647;
background:${info.bg}; color:${info.color}; padding:15px 12px; text-align:center;
font-size:16px; font-weight:bold; box-shadow:0 2px 12px rgba(0,0,0,0.3);
`;
banner.textContent = `📢 评测状态:${info.display}`;
document.body.prepend(banner);
setTimeout(() => {
banner.style.opacity = '0'; banner.style.transition = 'opacity 0.5s';
setTimeout(() => banner.remove(), 500);
}, 4000);
},
getColumnMap: function(table) {
const ths = table.querySelectorAll('thead th, thead td');
const map = { status: -1, time: -1, memory: -1 };
if (ths.length > 0) {
for (let i = 0; i < ths.length; i++) {
const text = ths[i].textContent.trim().toLowerCase();
if (text.includes('状态') || text.includes('status')) map.status = i;
if (text.includes('耗时') || text.includes('时间') || text.includes('time')) map.time = i;
if (text.includes('内存') || text.includes('memory') || text.includes('空间')) map.memory = i;
}
}
const rows = table.querySelectorAll('tbody tr');
for (const row of rows) {
const cells = row.cells;
for (let i = 0; i < cells.length; i++) {
const t = cells[i].textContent.trim().toLowerCase();
if (/(error|line|read|expect|on line)/i.test(t)) continue;
if (map.time < 0 && /(\d+(\.\d+)?\s*(ms|sec|s|秒))/.test(t)) map.time = i;
if (map.memory < 0 && /(\d+(\.\d+)?\s*(mib|kib|mb|kb|gib|gb))/i.test(t)) map.memory = i;
}
if (map.time >= 0 && map.memory >= 0) break;
}
if (map.status < 0) map.status = 1;
if (map.time < 0) map.time = 3;
if (map.memory < 0) map.memory = 4;
return map;
},
extractTestCases: function(doc) {
const rows = doc.querySelectorAll('table tbody tr');
const testRows = [];
for (const row of rows) {
const firstCell = row.cells[0];
if (!firstCell) continue;
const id = firstCell.textContent.trim();
if (/^#\d+-\d+$/.test(id)) {
testRows.push(row); continue;
}
if (/^#\d+$/.test(id)) {
const rowText = row.textContent.toLowerCase();
if (/(ms|sec|s|mib|kib|mb|kb)/.test(rowText)) testRows.push(row);
}
}
if (testRows.length === 0) return null;
const table = testRows[0].closest('table');
const colMap = this.getColumnMap(table);
const cases = [];
for (const row of testRows) {
const cells = row.cells;
const id = cells[0]?.textContent.trim() || '?';
const rawFull = cells[colMap.status]?.textContent.trim() || '';
const status = this.extractStatus(rawFull); // 只取状态名
const time = cells[colMap.time]?.textContent.trim() || '';
const memory = cells[colMap.memory]?.textContent.trim() || '';
const key = this.normalizeStatus(status);
const info = this.getStatusInfo(key);
// 不再保留 fullStatus,直接使用 info.display 作为悬停的状态名
cases.push({ id, key, info, time, memory });
}
return cases;
},
updateContainerTheme: function() {
if (!this.containerElem) return;
const body = document.body;
let isLight = false;
if (body.classList.contains('dark') || body.classList.contains('theme-dark') ||
(body.getAttribute('data-theme') === 'dark')) {
isLight = false;
} else if (body.classList.contains('light') || body.classList.contains('theme-light') ||
(body.getAttribute('data-theme') === 'light')) {
isLight = true;
} else {
const bgColor = window.getComputedStyle(body).backgroundColor;
const rgb = bgColor.match(/\d+/g);
if (rgb) {
const brightness = (parseInt(rgb[0]) * 299 + parseInt(rgb[1]) * 587 + parseInt(rgb[2]) * 114) / 1000;
isLight = brightness > 128;
} else isLight = true;
}
this.containerElem.style.backgroundColor = isLight ? '#f5f7fa' : '#323334';
this.containerElem.style.border = isLight ? '1px solid #e2e4e8' : 'none';
},
updateBlocks: function(testcases) {
const tables = document.querySelectorAll('table');
for (const table of tables) {
const rows = table.querySelectorAll('tbody tr');
for (const row of rows) {
const first = row.cells[0]?.textContent.trim();
if (first && /^#\d+(-\d+)?$/.test(first)) { table.style.display = 'none'; break; }
}
}
let container = document.getElementById('bzoj-testcase-blocks');
if (!container) {
container = document.createElement('div');
container.id = 'bzoj-testcase-blocks';
container.style.cssText = `
display: flex; flex-wrap: wrap; gap: 10px; margin: 16px 0;
padding: 14px; border-radius: 0; align-items: flex-start;
transition: background-color 0.2s;
`;
const hiddenTable = Array.from(document.querySelectorAll('table')).find(t => t.style.display === 'none');
if (hiddenTable && hiddenTable.parentElement) {
hiddenTable.parentElement.insertBefore(container, hiddenTable);
} else {
(document.querySelector('.record-container') || document.body).prepend(container);
}
}
this.containerElem = container;
this.updateContainerTheme();
container.innerHTML = '';
let allFinished = true;
for (const tc of testcases) {
if (!this.isFinished(tc.key)) allFinished = false;
const block = document.createElement('div');
block.className = 'bzoj-testcase-block';
// 悬停仅显示状态全名、耗时、内存
block.title = `${tc.info.display}\n耗时: ${tc.time}\n内存: ${tc.memory}`;
block.style.cssText = `
display: flex; flex-direction: column; align-items: center; justify-content: center;
width: 100px; height: 100px; font-weight: bold;
background: ${tc.info.bg}; color: ${tc.info.color};
border-radius: 0; cursor: default;
font-family: system-ui, -apple-system, sans-serif;
position: relative; overflow: hidden;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
`;
const num = document.createElement('span');
num.style.cssText = `
position: absolute; top: 6px; left: 8px;
font-size: 11px; font-weight: 500;
color: rgba(255,255,255,0.8); line-height: 1;
max-width: calc(100% - 12px); overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
`;
num.textContent = tc.id;
block.appendChild(num);
const statusSpan = document.createElement('span');
statusSpan.style.cssText = 'font-size:24px; font-weight:normal; margin-bottom:8px;';
if (tc.info.spin) {
statusSpan.textContent = tc.info.text;
statusSpan.style.animation = 'bzoj-spin 1.5s linear infinite';
} else statusSpan.textContent = tc.info.text;
block.appendChild(statusSpan);
const detail = document.createElement('span');
detail.style.cssText = 'font-size:12px; font-weight:normal; text-align:center; white-space:nowrap;';
let dt = '';
if (tc.time && tc.memory) dt = `${tc.time} / ${tc.memory}`;
else if (tc.time) dt = tc.time;
else if (tc.memory) dt = tc.memory;
else if (tc.info.spin) dt = 'waiting...';
detail.textContent = dt;
block.appendChild(detail);
container.appendChild(block);
}
if (!allFinished) {
const hint = document.createElement('span');
hint.textContent = '⏳ 评测进行中...';
hint.style.cssText = 'margin-left:10px; color:#90caf9; font-size:14px; align-self:center;';
container.appendChild(hint);
}
return allFinished;
},
pollStatus: async function() {
const self = this;
try {
const resp = await fetch(window.location.href, { credentials: 'same-origin' });
const html = await resp.text();
const doc = new DOMParser().parseFromString(html, 'text/html');
const newCases = self.extractTestCases(doc);
if (newCases) {
const allDone = self.updateBlocks(newCases);
if (allDone && newCases.length > 0) {
clearInterval(self.pollTimer); self.pollTimer = null;
const final = self.getOverallStatusKey(doc) || self.getWorstStatus(newCases);
self.notifyAndBanner(final);
} else {
const firstKey = newCases[0].key;
if (firstKey === 'fetched') self.notifyAndBanner('fetched');
}
} else {
const overall = self.getOverallStatusKey(doc);
if (overall) {
if (self.isFinished(overall)) {
clearInterval(self.pollTimer); self.pollTimer = null;
self.notifyAndBanner(overall);
} else if (overall !== self.lastOverallStatus) {
self.notifyAndBanner(overall);
self.lastOverallStatus = overall;
}
}
}
} catch (e) { console.error('[轮询] 网络错误', e); }
},
startPolling: function() {
if (this.pollTimer) return;
const self = this;
this.pollTimer = setInterval(() => self.pollStatus(), this.POLL_INTERVAL * 1000);
},
installObserver: function() {
const self = this;
if (this.observer) return;
this.observer = new MutationObserver(() => {
const container = document.getElementById('bzoj-testcase-blocks');
if (!container) {
const cases = self.extractTestCases(document);
if (cases) self.updateBlocks(cases);
} else {
const tables = document.querySelectorAll('table');
for (const t of tables) {
const rows = t.querySelectorAll('tbody tr');
for (const row of rows) {
const first = row.cells[0]?.textContent.trim();
if (first && /^#\d+(-\d+)?$/.test(first)) { t.style.display = 'none'; break; }
}
}
}
});
this.observer.observe(document.body, { childList: true, subtree: true });
if (this.themeObserver) this.themeObserver.disconnect();
this.themeObserver = new MutationObserver(() => {
if (this.containerElem) this.updateContainerTheme();
});
this.themeObserver.observe(document.body, { attributes: true, attributeFilter: ['class', 'data-theme'] });
},
init: function() {
if (!/\/record\/[a-f0-9]+/i.test(window.location.pathname)) return;
const self = this;
GM_addStyle(`
@keyframes bzoj-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
.bzoj-testcase-block { transition: transform 0.2s; }
.bzoj-testcase-block:hover { transform: scale(1.1); }
table thead { display: none !important; }
`);
const initialCases = self.extractTestCases(document);
if (initialCases) {
const allDone = self.updateBlocks(initialCases);
if (!allDone) {
self.startPolling();
if (initialCases[0].key === 'fetched') self.notifyAndBanner('fetched');
} else {
const final = self.getOverallStatusKey() || self.getWorstStatus(initialCases);
self.notifyAndBanner(final);
}
} else {
const overall = self.getOverallStatusKey();
if (overall) {
if (self.isFinished(overall)) self.notifyAndBanner(overall);
else { self.notifyAndBanner(overall); self.startPolling(); }
} else {
setTimeout(() => {
const retry = self.getOverallStatusKey();
if (retry) {
if (self.isFinished(retry)) self.notifyAndBanner(retry);
else { self.notifyAndBanner(retry); self.startPolling(); }
}
}, 1000);
}
}
self.installObserver();
}
};
// ==================== 全局初始化 ====================
function init() {
FontModule.init();
TestcaseModule.init();
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})();