版本比较
网站字体更换器
正文
增加 1560 行删除 14 行
112345567878910111213141516171819192 行未改动全部展开21221321421521521621721821922040 行未改动26126226326426426526526626726826927027127227327427527627727827928028128228328428510 行未改动29629729829928428530030130230327 行未改动331332333334321335336337338339182 行未改动全部展开522523524525512513526527528529530531123 行未改动全部展开65565665765865966066166266366466566666766866967067167267367467567658 行未改动73573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278318 行未改动802803804805739806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122821,650 行未改动全部展开3933393439353936240039373938393939403941394239433944394539463947394839493950395139523953395439553956395739586 行未改动配置异常简单,下载油猴插件,谷歌浏览器开fq或者下载[安装包](https://pan.quark.cn/s/1ac7209c3f94#/list/share)\配置:下载油猴插件,谷歌浏览器开fq或者下载[安装包](https://pan.quark.cn/s/1ac7209c3f94#/list/share)\点击油猴-->添加新脚本->ctrl+a再ctrl+v然后ctrl+s就行了```js// ==UserScript==// @name BZOJ 增强工具 + 网页字体更换器// @name Hydro OJ 增强工具 + 网页字体更换器// @namespace https://bzoj.org/// @version 1.5.0// @description 整合 BZOJ 测试点大方块(自动轮询、完成通知、亮暗模式适配)与全站网页字体更换器,BZOJ 功能仅在 bzoj.org 下激活// @version 2.5.3// @description 整合 Hydro OJ 测试点大方块(自动轮询、完成通知、亮暗模式适配、总分数垂直对齐,兼容所有 Hydro 系 OJ)、全站网页字体更换器、题目 Markdown 块内查看/复制功能(右上角按钮,可撤销,兼容所有 Hydro 系 OJ,支持在线编程模式)、题目列表「提交」快捷列(仅在题库/比赛/作业/训练列表页显示)、以及比赛/作业成绩表增强(黄色高亮当前用户 + 详细状态方块)// @author bzoj-enhancer & FontSwitcher// @match *://*/*// @grant GM_notification// @grant GM_addStyle// @grant GM_getValue// @grant GM_setValue// @grant GM_setClipboard// @run-at document-idle// @license MIT// ==/UserScript==
192 行未改动全部展开 // ========== 检测是否存在 subtask 分组 ========== // 方式1:通过 CSS class 检测(Hydro OJ 标准 HTML) let hasSubtaskClass = false; for (const row of rows) { if (row.classList && (row.classList.contains('subtask') || row.classList.contains('case'))) { if (row.classList && (row.classList.contains('subtask') || row.classList.contains('case') || row.classList.contains('subtask-case'))) { hasSubtaskClass = true; break; } }40 行未改动 const cases = []; for (const row of testRows) { const cells = row.cells; const id = cells[0]?.textContent.trim() || '?'; let rawStatus = cells[colMap.status]?.textContent.trim() || ''; let score = cells[colMap.score]?.textContent.trim() || '0'; const statusCell = cells[colMap.status];
// 智能提取状态文本:优先从 .record-status--text span 获取(排除 .float-right 的分数) let rawStatus = ''; const statusSpan = statusCell?.querySelector('.record-status--text:not(.float-right)'); if (statusSpan) rawStatus = statusSpan.textContent.trim(); else rawStatus = statusCell?.textContent.trim() || '';
// 智能提取分数:优先从 .float-right span 获取 let score = '0'; const scoreSpan = statusCell?.querySelector('.float-right'); if (scoreSpan) score = scoreSpan.textContent.trim(); else { const m = rawStatus.match(/(\d+)\s*$/); if (m) { score = m[1]; rawStatus = rawStatus.replace(/\d+\s*$/, '').trim(); } }
let time = cells[colMap.time]?.textContent.trim() || ''; let memory = cells[colMap.memory]?.textContent.trim() || '';
if (!isTimeLike(time)) {10 行未改动 if (isMemLike(t)) { memory = t; break; } } }
const statusMatch = rawStatus.match(/^(\D+)\s*(\d+)$/); if (statusMatch) { rawStatus = statusMatch[1].trim(); score = statusMatch[2]; } cases.push({ id, key: self.normalizeStatus(rawStatus), score, time, memory }); } return { hasGroups: false, groups: [{ id: '', key: '', score: '', cases: cases }] }; },27 行未改动 ? (row.classList && row.classList.contains('subtask')) : (/^#\d+$/.test(first) && !isTimeLike(cells[colMap.time]?.textContent.trim() || '') && !isMemLike(cells[colMap.memory]?.textContent.trim() || ''));
const isCaseRow = useClassNames ? (row.classList && row.classList.contains('case')) ? (row.classList && (row.classList.contains('case') || row.classList.contains('subtask-case'))) : /^#\d+-\d+$/.test(first);
if (isSubtaskRow) { // 提取 subtask 状态和分数182 行未改动全部展开 num.style.cssText = `position: absolute; top: 6px; left: 8px; font-size: 11px; font-weight: 500; color: ${isDark ? 'rgba(255,255,255,0.65)' : 'rgba(0,0,0,0.45)'}; line-height: 1; max-width: calc(100% - 12px); overflow: hidden; text-overflow: ellipsis; white-space: nowrap;`; num.textContent = tc.id; block.appendChild(num);
// 得分标签(右上角) if (tc.score && tc.score !== '0') { // 得分标签(右上角,包括 0 分也显示) if (tc.score !== undefined && tc.score !== null && tc.score !== '') { const scoreTag = document.createElement('span'); scoreTag.style.cssText = `position: absolute; top: 5px; right: 7px; font-size: 11px; font-weight: 600; color: ${info.color}; opacity: 0.75; line-height: 1;`; scoreTag.textContent = tc.score; block.appendChild(scoreTag);123 行未改动全部展开 break; } } } // 隐藏粘性表头表格(Hydro OJ 会在数据表上方生成一个 position:sticky 的表头表) const headerTables = document.querySelectorAll('table.section__table-header'); for (const t of headerTables) { t.classList.add('bzoj-hide-table'); }
const tableContainers = document.querySelectorAll('.section__table-container'); for (const tc of tableContainers) { tc.classList.add('bzoj-hide-container'); }
// 隐藏包含测试点表格的 .section__body.no-padding(避免空表格留下空白) const noPaddingBodies = document.querySelectorAll('.section__body.no-padding'); for (const body of noPaddingBodies) { if (body.querySelector('table') || body.querySelector('.section__table-container')) { body.classList.add('bzoj-hide-section-body'); } } },
/** 周期性验证容器是否仍然存在(兜底机制) */ _startVerifyTimer: function () {58 行未改动 table thead { display: none !important; } /* 用 CSS !important 强制隐藏测试点表格及容器,即使 Hydro 重建 DOM 也立即生效,避免闪烁 */ .bzoj-hide-table { display: none !important; } .bzoj-hide-container { display: none !important; } .bzoj-hide-section-body { display: none !important; }
/* ============ 修复 record 状态栏框太扁的问题 ============ */ /* Hydro 的 record 状态栏 <h1 class="section__title"> 内有图标、分数、状态文本, 默认 section__header 的 padding 不足,导致框太扁、内容显得没居中。 策略:增加 section__header 的上下 padding,让框变高,内容自然垂直居中。 */
/* 1. 增加 section__header 的上下 padding,让框变高 */ #status > .section__header, .section[data-status] > .section__header { padding-top: 14px !important; padding-bottom: 14px !important; }
/* 2. 让状态栏 h1 使用 flex 居中 */ #status .section__title, .section[data-status] > .section__header > .section__title { display: flex !important; align-items: center !important; gap: 8px !important; line-height: 1.4 !important; margin: 0 !important; }
/* 3. 所有子元素统一为 inline-block + 垂直居中 */ #status .section__title > *, .section[data-status] > .section__header > .section__title > * { display: inline-block !important; vertical-align: middle !important; align-self: center !important; line-height: 1.4 !important; margin-top: 0 !important; margin-bottom: 0 !important; }
/* 4. 图标保留 Hydro 原有尺寸 */ #status .section__title .record-status--icon, .section[data-status] .section__title .record-status--icon { flex-shrink: 0 !important; line-height: 1 !important; } `);
const initialResult = self.extractTestCases(document); if (initialResult) {18 行未改动 } };
// ================================================================ // 模块二:网页字体更换器(所有站点运行) // 模块二:BZOJ 题目 Markdown 查看/复制(仅题目详情页运行) // 适用页面: // - https://bzoj.org/p/<id> (独立题目页,<id> 可为 P06668 或 1576 等形式) // - https://bzoj.org/p/<id>?tid=<hex>(比赛题目页,例如 ?tid=69e2d8fe07068fa389942a8a) // 在题目页面右侧菜单注入「查看 / 复制 Markdown」入口; // 点击后弹出模态框显示题面 HTML 转换得到的 Markdown 源码, // 支持「复制到剪贴板」「下载 .md」「在线编辑」。 // ================================================================
const BZOJ_ProblemMarkdownModule = { _modal: null, _lastMarkdown: '',
init: function () { // 自动检测 Hydro OJ 题目详情页(兼容 bzoj.org / hydro.ac 及所有 Hydro 系 OJ) // 1. 路径匹配:/p/[id] 或 /d/[domain]/p/[id](排除 /p/[id]/submit、/p/[id]/solution 等子路径) const path = window.location.pathname; const match = path.match(/\/p\/([^\/]+)$/); if (!match) return;
// 2. 结构检测:页面是否有 Hydro 题目特征元素 const hasHydroElements = document.querySelector('.problem-content') || document.querySelector('[data-fragment-id="problem-description"]') || document.querySelector('.problem-content-container'); if (!hasHydroElements) return;
// 3. 排除 iframe 等嵌套文档 if (window.top !== window.self) return;
const self = this;
GM_addStyle(` .bzoj-md-fab { position: fixed; right: 24px; bottom: 96px; z-index: 9999; padding: 10px 18px; border: none; border-radius: 22px; background: #56758f; color: #fff; font-size: 13px; font-weight: 600; cursor: pointer; box-shadow: 0 4px 12px rgba(0,0,0,0.2); transition: transform .15s, box-shadow .15s, background .15s; font-family: "Segoe UI", "Microsoft YaHei", Arial, sans-serif; letter-spacing: .3px; } .bzoj-md-fab:hover { transform: translateY(-2px); box-shadow: 0 6px 16px rgba(0,0,0,0.3); background: #46637a; } .bzoj-md-modal-backdrop { position: fixed; inset: 0; z-index: 10000; background: rgba(0,0,0,0.55); display: flex; align-items: center; justify-content: center; opacity: 0; transition: opacity .2s ease; padding: 24px 16px; } .bzoj-md-modal-backdrop.bzoj-show { opacity: 1; } .bzoj-md-modal { background: #fff; color: #333; width: min(960px, 100%); height: min(82vh, 760px); border-radius: 12px; display: flex; flex-direction: column; overflow: hidden; box-shadow: 0 24px 60px rgba(0,0,0,0.35); transform: translateY(8px); transition: transform .2s ease; } .bzoj-md-modal-backdrop.bzoj-show .bzoj-md-modal { transform: translateY(0); } .bzoj-md-modal-header { padding: 14px 18px; border-bottom: 1px solid #eee; display: flex; align-items: center; justify-content: space-between; background: #fafafa; flex-shrink: 0; } .bzoj-md-modal-title { font-size: 15px; font-weight: 600; color: #333; display: flex; align-items: center; gap: 8px; } .bzoj-md-modal-title .bzoj-md-title-tag { display: inline-block; padding: 1px 8px; border-radius: 4px; background: #56758f; color: #fff; font-size: 11px; font-weight: 600; letter-spacing: .5px; } .bzoj-md-modal-subtitle { font-size: 12px; color: #888; font-weight: 400; margin-left: 6px; } .bzoj-md-modal-close { background: transparent; border: none; cursor: pointer; font-size: 22px; color: #999; line-height: 1; padding: 4px 8px; border-radius: 6px; font-family: inherit; } .bzoj-md-modal-close:hover { background: #eee; color: #333; } .bzoj-md-modal-toolbar { padding: 10px 14px; border-bottom: 1px solid #f0f0f0; display: flex; gap: 8px; background: #fafafa; flex-wrap: wrap; align-items: center; flex-shrink: 0; } .bzoj-md-btn { padding: 6px 14px; border: 1px solid #d9d9d9; border-radius: 6px; background: #fff; color: #333; font-size: 13px; cursor: pointer; transition: all .15s; font-family: inherit; line-height: 1.4; } .bzoj-md-btn:hover { border-color: #56758f; color: #56758f; } .bzoj-md-btn--primary { background: #56758f; color: #fff; border-color: #56758f; } .bzoj-md-btn--primary:hover { background: #46637a; color: #fff; border-color: #46637a; } .bzoj-md-btn--ghost { background: transparent; } .bzoj-md-modal-toolbar .bzoj-md-spacer { flex: 1; } .bzoj-md-modal-toolbar .bzoj-md-meta { font-size: 12px; color: #888; } .bzoj-md-modal-body { flex: 1; overflow: auto; padding: 0; min-height: 0; } .bzoj-md-textarea { width: 100%; height: 100%; border: none; outline: none; resize: none; padding: 16px 18px; font-family: "JetBrains Mono", "Cascadia Code", Consolas, "Source Code Pro", "Microsoft YaHei", monospace; font-size: 13px; line-height: 1.6; color: #333; background: #fff; white-space: pre; overflow-wrap: normal; tab-size: 4; } .bzoj-md-toast { position: fixed; bottom: 32px; left: 50%; transform: translateX(-50%) translateY(20px); background: #333; color: #fff; padding: 10px 20px; border-radius: 24px; font-size: 13px; z-index: 10001; opacity: 0; transition: all .25s ease; box-shadow: 0 6px 20px rgba(0,0,0,0.25); pointer-events: none; font-family: "Segoe UI", "Microsoft YaHei", Arial, sans-serif; } .bzoj-md-toast.bzoj-show { opacity: 1; transform: translateX(-50%) translateY(0); } /* 暗色模式适配 —— Hydro 使用 .theme--dark 或 data-mantine-color-scheme="dark" */ .theme--dark .bzoj-md-modal, html[data-mantine-color-scheme="dark"] .bzoj-md-modal, .theme--dark.bzoj-md-modal { background: #1f1f1f; color: #ddd; box-shadow: 0 24px 60px rgba(0,0,0,0.6); } .theme--dark .bzoj-md-modal-header, html[data-mantine-color-scheme="dark"] .bzoj-md-modal-header, .theme--dark .bzoj-md-modal-toolbar { background: #262626; border-color: #333; } .theme--dark .bzoj-md-modal-title, html[data-mantine-color-scheme="dark"] .bzoj-md-modal-title { color: #eee; } .theme--dark .bzoj-md-modal-subtitle, html[data-mantine-color-scheme="dark"] .bzoj-md-modal-subtitle { color: #999; } .theme--dark .bzoj-md-textarea, html[data-mantine-color-scheme="dark"] .bzoj-md-textarea { background: #1f1f1f; color: #ddd; } .theme--dark .bzoj-md-btn, html[data-mantine-color-scheme="dark"] .bzoj-md-btn { background: #333; color: #ddd; border-color: #444; } .theme--dark .bzoj-md-btn:hover, html[data-mantine-color-scheme="dark"] .bzoj-md-btn:hover { border-color: #56758f; color: #8eb3d0; } .theme--dark .bzoj-md-btn--primary, html[data-mantine-color-scheme="dark"] .bzoj-md-btn--primary { background: #56758f; color: #fff; border-color: #56758f; } .theme--dark .bzoj-md-btn--primary:hover, html[data-mantine-color-scheme="dark"] .bzoj-md-btn--primary:hover { background: #46637a; color: #fff; border-color: #46637a; } .theme--dark .bzoj-md-modal-close, html[data-mantine-color-scheme="dark"] .bzoj-md-modal-close { color: #888; } .theme--dark .bzoj-md-modal-close:hover, html[data-mantine-color-scheme="dark"] .bzoj-md-modal-close:hover { background: #333; color: #ddd; } .theme--dark .bzoj-md-toast, html[data-mantine-color-scheme="dark"] .bzoj-md-toast { background: #ddd; color: #222; }
/* ============ 题目块右上角浮动按钮组 ============ */ .bzoj-md-actions { position: absolute; top: 8px; right: 10px; z-index: 50; display: flex; gap: 6px; align-items: center; font-family: "Segoe UI", "Microsoft YaHei", Arial, sans-serif; } .bzoj-md-action-btn { display: inline-flex; align-items: center; gap: 4px; padding: 4px 10px; border: 1px solid rgba(86,117,143,0.35); border-radius: 5px; background: rgba(255,255,255,0.92); color: #56758f; font-size: 12px; font-weight: 600; cursor: pointer; transition: all .15s; font-family: inherit; line-height: 1.4; backdrop-filter: blur(4px); box-shadow: 0 1px 3px rgba(0,0,0,0.08); } .bzoj-md-action-btn:hover { background: #56758f; color: #fff; border-color: #56758f; box-shadow: 0 2px 6px rgba(86,117,143,0.3); } .bzoj-md-action-btn--active { background: #56758f; color: #fff; border-color: #56758f; } .bzoj-md-action-btn .bzoj-md-action-icon { display: inline-flex; align-items: center; justify-content: center; width: 12px; height: 12px; font-size: 11px; font-weight: 700; line-height: 1; } /* 暗色模式适配 */ .theme--dark .bzoj-md-action-btn, html[data-mantine-color-scheme="dark"] .bzoj-md-action-btn { background: rgba(42,42,42,0.92); color: #8eb3d0; border-color: rgba(142,179,208,0.35); } .theme--dark .bzoj-md-action-btn:hover, html[data-mantine-color-scheme="dark"] .bzoj-md-action-btn:hover, .theme--dark .bzoj-md-action-btn--active, html[data-mantine-color-scheme="dark"] .bzoj-md-action-btn--active { background: #56758f; color: #fff; border-color: #56758f; }
/* ============ 块内 MD 源码视图(替换题面 HTML) ============ */ /* 透明背景 + 继承字号,直接融入题目块容器,不出现单独的「灰色框」 */ .bzoj-md-inline-view { padding: 0; margin: 0; font-family: "JetBrains Mono", "Cascadia Code", Consolas, "Source Code Pro", "Microsoft YaHei", monospace; font-size: inherit; line-height: inherit; white-space: pre-wrap; word-break: break-word; overflow-wrap: anywhere; background: transparent; border: none; border-radius: 0; color: inherit; overflow: visible; } .theme--dark .bzoj-md-inline-view, html[data-mantine-color-scheme="dark"] .bzoj-md-inline-view { background: transparent; color: inherit; } .bzoj-md-restored-banner { display: flex; align-items: center; gap: 8px; padding: 8px 14px; margin-bottom: 10px; background: rgba(86,117,143,0.08); border-radius: 6px; font-size: 12px; color: #56758f; font-weight: 500; font-family: "Segoe UI", "Microsoft YaHei", Arial, sans-serif; } .theme--dark .bzoj-md-restored-banner, html[data-mantine-color-scheme="dark"] .bzoj-md-restored-banner { background: rgba(255,255,255,0.06); color: #8eb3d0; } `);
// 在题目块右上角注入两个浮动按钮 self.addActionButtons();
// 在题目右侧菜单注入入口;若没有侧边栏则降级为悬浮按钮 const menu = document.querySelector('.section--problem-sidebar .menu'); if (menu) { self.addSidebarButton(menu); } else { self.addFloatingButton(); }
// 监听 DOM 变化:用户进入/退出在线编程模式(scratchpad)时重新注入按钮 self._installModeObserver(); },
/** 在题目块右上角注入两个浮动按钮:「显示 MD」「复制 MD」 */ addActionButtons: function () { const self = this; // 移除已存在但已失效的按钮(如 scratchpad 模式切换导致旧按钮在隐藏容器中) const existing = document.querySelector('.bzoj-md-actions'); if (existing) { const parent = existing.parentElement; if (parent) { const cs = getComputedStyle(parent); const invisible = cs.display === 'none' || parseFloat(cs.opacity) < 0.1; if (invisible) existing.remove(); else return; // 已有可见按钮,不重复注入 } }
// 定位题目内容容器:优先 scratchpad 模式下的可见 .problem-content, // 其次普通模式的 .problem-content-container const scratchpadContent = document.querySelector('.scratchpad__problem .problem-content, .scratchpad__problem [data-fragment-id="problem-description"]'); const anchor = scratchpadContent || document.querySelector('.problem-content-container') || (document.querySelector('.problem-content')?.closest('.section')) || document.querySelector('.problem-content'); if (!anchor) return;
// 确保锚点容器支持相对定位(让按钮的 absolute 生效) const computedPos = getComputedStyle(anchor).position; if (computedPos === 'static' || !computedPos) { anchor.style.position = 'relative'; }
const actions = document.createElement('div'); actions.className = 'bzoj-md-actions';
// 按钮 1:显示 MD —— 在块内切换显示 Markdown 源码(可撤销) const viewBtn = document.createElement('button'); viewBtn.type = 'button'; viewBtn.className = 'bzoj-md-action-btn'; viewBtn.innerHTML = '<span class="bzoj-md-action-icon">M</span> 显示 MD'; viewBtn.title = '在题面块内直接显示 Markdown 源码(再次点击恢复原题面)'; viewBtn.addEventListener('click', function () { self.toggleInlineMd(viewBtn); }); actions.appendChild(viewBtn);
// 按钮 2:复制 MD —— 直接复制到剪贴板 const copyBtn = document.createElement('button'); copyBtn.type = 'button'; copyBtn.className = 'bzoj-md-action-btn'; copyBtn.innerHTML = '<span class="bzoj-md-action-icon">\u2398</span> 复制 MD'; copyBtn.title = '将题目的 Markdown 源码复制到剪贴板'; copyBtn.addEventListener('click', function () { self.copyMarkdownDirectly(); }); actions.appendChild(copyBtn);
anchor.appendChild(actions); },
/** 安装模式切换监听器:scratchpad 模式切换时重新注入按钮 */ _installModeObserver: function () { const self = this; if (self._mdObserver) return;
self._mdObserver = new MutationObserver(function () { clearTimeout(self._mdObserverDebounce); self._mdObserverDebounce = setTimeout(function () { self.addActionButtons(); }, 200); }); self._mdObserver.observe(document.body, { attributes: true, attributeFilter: ['class'] }); self._mdObserver.observe(document.body, { childList: true, subtree: true }); },
/** * 在题面块内切换 Markdown 源码视图(可撤销)。 * - 首次点击:保存原始 HTML,将题面正文替换为 <pre class="bzoj-md-inline-view"> 显示 MD 源码 * - 再次点击:恢复原始 HTML */ _inlineMdState: null, // { originalHtml, viewEl, anchor } toggleInlineMd: function (btn) { const self = this;
// 定位题面正文容器(优先 scratchpad 模式下的可见题面) const fragment = document.querySelector('.scratchpad__problem [data-fragment-id="problem-description"]') || document.querySelector('.scratchpad__problem .problem-content .section__body') || document.querySelector('.scratchpad__problem .problem-content') || document.querySelector('[data-fragment-id="problem-description"]') || document.querySelector('.problem-content .section__body') || document.querySelector('.problem-content'); if (!fragment) { self.showToast('未找到题面内容', 'error'); return; }
// 如果当前已是 MD 视图,则恢复原题面 if (self._inlineMdState && self._inlineMdState.active) { self._restoreInlineMd(btn); return; }
// 生成 Markdown 源码 const md = self.getProblemMarkdown(); if (!md || !md.trim()) { self.showToast('未提取到题面内容', 'error'); return; }
// 保存原始 HTML,用于撤销 self._inlineMdState = { active: true, originalHtml: fragment.innerHTML, fragment: fragment, };
// 用 MD 源码替换题面内容 fragment.innerHTML = ''; const pre = document.createElement('pre'); pre.className = 'bzoj-md-inline-view'; pre.textContent = md; fragment.appendChild(pre);
// 按钮状态切换 btn.classList.add('bzoj-md-action-btn--active'); btn.innerHTML = '<span class="bzoj-md-action-icon">\u21BA</span> 恢复原题'; btn.title = '恢复题面原始 HTML 渲染';
self.showToast('已切换为 Markdown 源码视图'); },
/** 恢复题面原始 HTML */ _restoreInlineMd: function (btn) { const self = this; if (!self._inlineMdState || !self._inlineMdState.active) return;
const state = self._inlineMdState; try { state.fragment.innerHTML = state.originalHtml; } catch (e) { console.error('[BZOJ-MD] 恢复题面失败', e); }
self._inlineMdState = null;
// 按钮状态切换回「显示 MD」 btn.classList.remove('bzoj-md-action-btn--active'); btn.innerHTML = '<span class="bzoj-md-action-icon">M</span> 显示 MD'; btn.title = '在题面块内直接显示 Markdown 源码(再次点击恢复原题面)';
self.showToast('已恢复题面原始渲染'); },
/** 暗色模式检测:优先检查 Hydro 的 theme class,再回退到 body 背景亮度判断 */ _detectDarkMode: function () { // 1. 优先检查 Hydro 的显式 class / 属性(最可靠,且在首帧即可用) const html = document.documentElement; if (html.classList.contains('theme--dark')) return true; if (html.classList.contains('theme--light')) return false; if (html.getAttribute('data-mantine-color-scheme') === 'dark') return true; if (html.getAttribute('data-mantine-color-scheme') === 'light') return false; if (document.body.classList.contains('theme--dark')) return true;
// 2. 兜底:通过 body 背景亮度判断 try { const bgColor = getComputedStyle(document.body).backgroundColor; const match = bgColor.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/); if (match) { const r = parseInt(match[1]); const g = parseInt(match[2]); const b = parseInt(match[3]); const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255; return luminance < 0.5; } } catch (e) { /* ignore */ } return false; },
/** 直接复制 Markdown 到剪贴板(不弹模态框) */ copyMarkdownDirectly: function () { const self = this; const md = self.getProblemMarkdown(); if (!md || !md.trim()) { self.showToast('未提取到题面内容', 'error'); return; } self.copyToClipboard(md, null); },
addSidebarButton: function (menu) { const self = this; if (menu.querySelector('[data-bzoj-md-btn]')) return; // 防止重复注入 const li = document.createElement('li'); li.className = 'menu__item scratchpad--hide'; const a = document.createElement('a'); a.className = 'menu__link'; a.href = 'javascript:;'; a.setAttribute('data-bzoj-md-btn', '1'); a.title = '查看题目正文的 Markdown 源码,并复制到剪贴板'; a.innerHTML = '<span class="icon" style="display:inline-block;width:14px;text-align:center;font-weight:700;font-size:12px;">M</span> 查看 / 复制 Markdown'; a.addEventListener('click', function (e) { e.preventDefault(); self.showModal(); }); li.appendChild(a); menu.appendChild(li); },
addFloatingButton: function () { const self = this; if (document.querySelector('.bzoj-md-fab')) return; const btn = document.createElement('button'); btn.type = 'button'; btn.className = 'bzoj-md-fab'; btn.textContent = '查看 MD'; btn.addEventListener('click', function () { self.showModal(); }); document.body.appendChild(btn); },
/** 提取题面 HTML 并转换为 Markdown */ getProblemMarkdown: function () { // 优先 scratchpad 模式下的可见题面,其次普通模式 const fragment = document.querySelector('.scratchpad__problem [data-fragment-id="problem-description"]') || document.querySelector('.scratchpad__problem .problem-content .section__body') || document.querySelector('.scratchpad__problem .problem-content') || document.querySelector('[data-fragment-id="problem-description"]') || document.querySelector('.problem-content .section__body') || document.querySelector('.problem-content'); if (!fragment) return '';
// 克隆后剔除工具栏(Copy / 填充到自测 等按钮)以及 KaTeX 渲染层,只保留源 LaTeX const clone = fragment.cloneNode(true); clone.querySelectorAll('.toolbar, .scratchpad-fill-button, .toolbar-item').forEach(function (el) { el.remove(); });
// 让 KaTeX 保留原始 LaTeX:把 <annotation> 的文本塞入 katex 容器,并移除其余渲染节点 clone.querySelectorAll('.katex').forEach(function (katex) { const anno = katex.querySelector('annotation[encoding="application/x-tex"]'); if (anno) { const tex = anno.textContent; katex.innerHTML = ''; katex.textContent = tex; } }); // MathJax 类似的处理:保留 <script type="math/tex"> 内容 clone.querySelectorAll('script[type="math/tex"], script[type="math/tex; mode=display"]').forEach(function (s) { const txt = s.textContent; const span = document.createElement('span'); span.textContent = txt; s.parentNode.replaceChild(span, s); });
return this.htmlToMarkdown(clone).trim() + '\n'; },
/** 简易 HTML→Markdown 转换器,覆盖 Hydro 题面常见元素 */ htmlToMarkdown: function (root) { const self = this;
function absolutize(url) { try { return new URL(url, location.href).href; } catch (e) { return url; } }
function convertNode(node) { if (node.nodeType === Node.TEXT_NODE) { const text = node.textContent; // 块级元素之间的 HTML 缩进(仅含空白且含换行)应当忽略, // 避免出现「# 标题\n\n 正文」这样被 Markdown 误判为代码块的输出。 // <pre> 不走此分支(PRE 分支直接取 textContent),所以代码块缩进安全。 if (!text.trim() && text.indexOf('\n') !== -1) return ''; return text; } if (node.nodeType !== Node.ELEMENT_NODE) return ''; const tag = node.tagName.toUpperCase(); const kids = function () { return Array.from(node.childNodes).map(convertNode).join(''); };
switch (tag) { case 'H1': return '\n# ' + kids().trim() + '\n\n'; case 'H2': return '\n## ' + kids().trim() + '\n\n'; case 'H3': return '\n### ' + kids().trim() + '\n\n'; case 'H4': return '\n#### ' + kids().trim() + '\n\n'; case 'H5': return '\n##### ' + kids().trim() + '\n\n'; case 'H6': return '\n###### ' + kids().trim() + '\n\n'; case 'P': return kids().trim() + '\n\n'; case 'BR': return ' \n'; case 'STRONG': case 'B': return '**' + kids() + '**'; case 'EM': case 'I': return '*' + kids() + '*'; case 'DEL': case 'S': case 'STRIKE': return '~~' + kids() + '~~'; case 'SUB': return '~' + kids() + '~'; case 'SUP': return '^' + kids() + '^'; case 'U': return kids(); case 'CODE': { const text = node.textContent; // 行内 code 不允许跨行;若出现换行则交由 PRE 处理 if (text.indexOf('\n') !== -1) return '``' + text + '``'; if (text.indexOf('`') !== -1) return '`` ' + text + ' ``'; return '`' + text + '`'; } case 'PRE': { const code = node.querySelector('code'); const raw = code ? code.textContent : node.textContent; const text = raw.replace(/\n+$/, ''); const cls = code ? (code.className || '') : ''; const m = cls.match(/language-([\w-]+)/); const lang = m ? m[1] : ''; return '\n```' + lang + '\n' + text + '\n```\n\n'; } case 'UL': { let out = '\n'; Array.from(node.children).forEach(function (li) { if (li.tagName === 'LI') { out += '- ' + convertNode(li).trim() + '\n'; } }); return out + '\n'; } case 'OL': { let out = '\n'; let i = 1; Array.from(node.children).forEach(function (li) { if (li.tagName === 'LI') { out += i + '. ' + convertNode(li).trim() + '\n'; i++; } }); return out + '\n'; } case 'LI': return kids(); case 'A': { const href = node.getAttribute('href') || ''; const text = kids().trim() || href; if (!href || href === 'javascript:;' || href === '#') return text; return '[' + text + '](' + absolutize(href) + ')'; } case 'IMG': { const src = node.getAttribute('src') || ''; const alt = node.getAttribute('alt') || ''; return ' + ')'; } case 'BLOCKQUOTE': { const inner = kids().trim(); return inner.split('\n').map(function (l) { return '> ' + l; }).join('\n') + '\n\n'; } case 'HR': return '\n---\n\n'; case 'TABLE': return self.convertTable(node); case 'INPUT': { if (node.type === 'checkbox') return node.checked ? '[x] ' : '[ ] '; return ''; } case 'DETAILS': { const summary = node.querySelector('summary'); const sumText = summary ? summary.textContent.trim() : ''; const inner = kids().replace(/^[\s\S]*?<\/summary>/i, ''); return '\n<details>\n<summary>' + sumText + '</summary>\n\n' + inner.trim() + '\n\n</details>\n\n'; } case 'SCRIPT': case 'STYLE': case 'NOSCRIPT': return ''; case 'SPAN': { // KaTeX/MathJax 已被预处理为纯文本;这里只透传 return kids(); } default: return kids(); } }
let md = convertNode(root); md = md .replace(/\r\n/g, '\n') .replace(/\u00a0/g, ' ') // -> space .replace(/[ \t]+\n/g, '\n') // 行尾空格(保留 Markdown 强制换行的两个空格会损失,但更干净) .replace(/\n{3,}/g, '\n\n') // 折叠多余空行 .trim(); return md + '\n'; },
convertTable: function (table) { const self = this; const rows = Array.from(table.querySelectorAll('tr')); if (!rows.length) return ''; const cellNodes = rows.map(function (r) { return Array.from(r.querySelectorAll('th,td')).map(function (c) { return self._convertNodeForTable(c).trim().replace(/\|/g, '\\|').replace(/\n+/g, ' '); }); }); const colCount = Math.max.apply(null, cellNodes.map(function (r) { return r.length; })); if (!colCount) return ''; // 补齐每行列数 const aligned = cellNodes.map(function (r) { while (r.length < colCount) r.push(''); return r; }); const header = aligned[0]; const sep = Array(colCount).fill('---'); const body = aligned.slice(1); let out = '\n'; out += '| ' + header.join(' | ') + ' |\n'; out += '| ' + sep.join(' | ') + ' |\n'; body.forEach(function (r) { out += '| ' + r.join(' | ') + ' |\n'; }); return out + '\n'; },
/** 表格单元格内转换器(与 htmlToMarkdown 内部的 convertNode 行为一致) */ _convertNodeForTable: function (node) { const self = this; function rec(n) { if (n.nodeType === Node.TEXT_NODE) return n.textContent; if (n.nodeType !== Node.ELEMENT_NODE) return ''; const tag = n.tagName.toUpperCase(); const kids = function () { return Array.from(n.childNodes).map(rec).join(''); }; switch (tag) { case 'BR': return ' '; case 'STRONG': case 'B': return '**' + kids() + '**'; case 'EM': case 'I': return '*' + kids() + '*'; case 'CODE': return '`' + n.textContent + '`'; case 'A': { const href = n.getAttribute('href') || ''; const text = kids().trim() || href; if (!href || href === 'javascript:;' || href === '#') return text; return '[' + text + '](' + href + ')'; } case 'SCRIPT': case 'STYLE': case 'NOSCRIPT': return ''; default: return kids(); } } return rec(node); },
showModal: function () { const self = this; const md = self.getProblemMarkdown(); self._lastMarkdown = md;
// 题目 ID 与标题,用于显示与下载文件名 const titleEl = document.querySelector('.problem-content .section__title, .problem-content-container .section__title'); const titleText = titleEl ? titleEl.textContent.trim() : 'problem'; const pid = (location.pathname.match(/^\/p\/([^\/]+)$/) || [])[1] || 'problem'; const tid = new URLSearchParams(location.search).get('tid') || ''; const safeName = (titleText || pid).replace(/[\\/:*?"<>|]/g, '_').slice(0, 80);
// 清理已存在的旧模态框 if (self._modal) { self._modal.remove(); self._modal = null; }
const backdrop = document.createElement('div'); backdrop.className = 'bzoj-md-modal-backdrop'; backdrop.innerHTML = '<div class="bzoj-md-modal" role="dialog" aria-modal="true" aria-label="题目 Markdown">' + '<div class="bzoj-md-modal-header">' + '<div class="bzoj-md-modal-title">' + '<span class="bzoj-md-title-tag">MD</span>' + '<span>题目 Markdown</span>' + '<span class="bzoj-md-modal-subtitle">' + self._escapeHtml(pid + (tid ? ' · tid=' + tid : '')) + '</span>' + '</div>' + '<button type="button" class="bzoj-md-modal-close" aria-label="关闭">×</button>' + '</div>' + '<div class="bzoj-md-modal-toolbar">' + '<button type="button" class="bzoj-md-btn bzoj-md-btn--primary" data-act="copy">复制到剪贴板</button>' + '<button type="button" class="bzoj-md-btn" data-act="download">下载 .md</button>' + '<button type="button" class="bzoj-md-btn bzoj-md-btn--ghost" data-act="select">全选</button>' + '<span class="bzoj-md-spacer"></span>' + '<span class="bzoj-md-meta">' + md.length + ' 字符</span>' + '</div>' + '<div class="bzoj-md-modal-body">' + '<textarea class="bzoj-md-textarea" spellcheck="false" readonly></textarea>' + '</div>' + '</div>'; document.body.appendChild(backdrop); self._modal = backdrop;
const textarea = backdrop.querySelector('.bzoj-md-textarea'); textarea.value = md;
// 打开动效 requestAnimationFrame(function () { backdrop.classList.add('bzoj-show'); }); setTimeout(function () { textarea.focus(); textarea.setSelectionRange(0, 0); textarea.scrollTop = 0; }, 60);
// 关闭逻辑 function close() { backdrop.classList.remove('bzoj-show'); setTimeout(function () { if (backdrop.parentNode) backdrop.remove(); self._modal = null; }, 220); } backdrop.querySelector('.bzoj-md-modal-close').addEventListener('click', close); backdrop.addEventListener('click', function (e) { if (e.target === backdrop) close(); }); document.addEventListener('keydown', function onKey(e) { if (e.key === 'Escape' && self._modal === backdrop) { close(); document.removeEventListener('keydown', onKey); } });
// 工具栏按钮 backdrop.querySelector('[data-act="copy"]').addEventListener('click', function () { self.copyToClipboard(textarea.value, close); }); backdrop.querySelector('[data-act="download"]').addEventListener('click', function () { self.downloadFile(safeName + '.md', textarea.value); }); backdrop.querySelector('[data-act="select"]').addEventListener('click', function () { textarea.focus(); textarea.select(); }); },
copyToClipboard: function (text, onClose) { const self = this; let done = false; function succeed() { if (done) return; done = true; self.showToast('已复制 Markdown 到剪贴板'); if (onClose) onClose(); } function fail(msg) { if (done) return; done = true; self.showToast('复制失败:' + (msg || '请手动全选复制'), 'error'); }
try { if (typeof GM_setClipboard === 'function') { GM_setClipboard(text, 'text'); succeed(); return; } } catch (e) { /* fall through */ }
if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(text).then(succeed).catch(function () { fallbackExec(); }); } else { fallbackExec(); }
function fallbackExec() { try { const ta = document.createElement('textarea'); ta.value = text; ta.style.position = 'fixed'; ta.style.opacity = '0'; ta.style.top = '0'; ta.style.left = '0'; document.body.appendChild(ta); ta.focus(); ta.select(); const ok = document.execCommand('copy'); document.body.removeChild(ta); if (ok) succeed(); else fail('execCommand 返回 false'); } catch (e) { fail(e && e.message); } } },
downloadFile: function (filename, content) { try { const blob = new Blob([content], { type: 'text/markdown;charset=utf-8' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); document.body.removeChild(a); setTimeout(function () { URL.revokeObjectURL(url); }, 200); this.showToast('已开始下载 ' + filename); } catch (e) { this.showToast('下载失败:' + (e && e.message ? e.message : ''), 'error'); } },
_toastEl: null, _toastTimer: null, showToast: function (msg, type) { const self = this; if (self._toastTimer) clearTimeout(self._toastTimer); if (!self._toastEl) { self._toastEl = document.createElement('div'); self._toastEl.className = 'bzoj-md-toast'; document.body.appendChild(self._toastEl); } self._toastEl.textContent = msg; if (type === 'error') self._toastEl.style.background = '#b03a3a'; else self._toastEl.style.background = ''; // 强制重排以重启动效 void self._toastEl.offsetWidth; self._toastEl.classList.add('bzoj-show'); self._toastTimer = setTimeout(function () { self._toastEl.classList.remove('bzoj-show'); }, 2200); },
_escapeHtml: function (s) { return String(s).replace(/[&<>"']/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]; }); } };
// ================================================================ // 模块三:题目列表「提交」快捷列 // 仅在以下页面运行: // - /contest/<hex>/problems (比赛题目列表) // - /p (题库) // - /p?page=<num> (题库分页) // - /homework/<hex> (作业题目列表) // - /training/<hex> (训练题目列表) // 在题目列表表格中新增一列「提交」,显示指向 /p/<id>/submit 的链接。 // 兼容所有 Hydro 系 OJ。 // ================================================================
const BZOJ_SubmitLinkModule = { /** 判断当前页面是否应该启用此模块 */ shouldRun: function () { const path = window.location.pathname; // /contest/<hex>/problems if (/\/contest\/[^\/]+\/problems\/?$/.test(path)) return true; // /p 或 /p?page=<num>(精确匹配 /p 结尾,排除 /p/<id> 详情页) if (/^\/p\/?$/.test(path)) return true; // /homework/<hex> if (/\/homework\/[^\/]+\/?$/.test(path)) return true; // /training/<hex> if (/\/training\/[^\/]+\/?$/.test(path)) return true; return false; },
init: function () { const self = this; if (!self.shouldRun()) return;
GM_addStyle(` .bzoj-submit-col-link { display: inline-block; padding: 2px 12px; border-radius: 4px; background: rgba(86,117,143,0.1); color: #56758f; font-size: 13px; font-weight: 600; text-decoration: none; font-family: "Segoe UI", "Microsoft YaHei", Arial, sans-serif; transition: all .15s; } .bzoj-submit-col-link:hover { background: #56758f; color: #fff; text-decoration: none; } .theme--dark .bzoj-submit-col-link, html[data-mantine-color-scheme="dark"] .bzoj-submit-col-link { background: rgba(142,179,208,0.15); color: #8eb3d0; } .theme--dark .bzoj-submit-col-link:hover, html[data-mantine-color-scheme="dark"] .bzoj-submit-col-link:hover { background: #56758f; color: #fff; } `);
self.injectColumns();
// 监听 DOM 变化(Hydro 可能动态加载/重建表格) self._installObserver(); },
/** 判断一个 URL 是否是题目链接:/p/<id>(排除 submit 等子路径) */ isProblemLink: function (href) { if (!href) return false; if (/\/p\/[^\/]+\/(submit|solution|edit|files|manage)/.test(href)) return false; return /\/p\/[^\/]+/.test(href); },
/** 从题目链接 href 构建 submit URL(保留 tid 参数) */ buildSubmitUrl: function (href) { const url = new URL(href, location.href); return url.pathname.replace(/\/$/, '') + '/submit' + (url.search || ''); },
/** 在题目列表表格中新增「提交」列(不修改原有列,只在最右侧追加) */ injectColumns: function () { const self = this; // 第一步:移除页面中所有 Hydro 自带的「递交」链接(class="typo-a" 且指向 submit), // 这些链接通常是 float:right 的纯文字+图标,样式较陋,用我们新增的列替代。 // 独立于表格处理执行,确保即使行已被标记也能清理。 const allOldLinks = document.querySelectorAll('a.typo-a[href*="/submit"]'); for (const oldLink of allOldLinks) { oldLink.remove(); }
// 查找所有包含题目链接的表格 const tables = document.querySelectorAll('table.data-table'); let count = 0;
for (const table of tables) { if (table.dataset.bzojSubmitCol === '1') continue; // 已处理
const tbody = table.querySelector('tbody'); if (!tbody) continue;
// 检查表格是否包含题目链接(决定是否处理此表格) const rows = tbody.querySelectorAll('tr'); let hasProblemRow = false; for (const row of rows) { const link = row.querySelector('a[href*="/p/"]'); if (link && self.isProblemLink(link.getAttribute('href') || '')) { hasProblemRow = true; break; } } if (!hasProblemRow) continue;
// 找到表头行(thead > tr),也在表头加一列 let headerRow = null; const thead = table.querySelector('thead'); if (thead) headerRow = thead.querySelector('tr');
// Hydro 可能还有独立的 sticky 表头表(section__table-header),也要同步加列 let stickyHeaderRow = null; const container = table.closest('.section__body, .section, .problem-list-container, .col-container'); if (container) { const stickyTable = container.querySelector('table.section__table-header'); if (stickyTable) { const stickyThead = stickyTable.querySelector('thead'); if (stickyThead) stickyHeaderRow = stickyThead.querySelector('tr'); } }
// 同步 colgroup:如果有 <colgroup>,需要加一个 <col> 保持列数一致 const colgroup = table.querySelector('colgroup'); if (colgroup && !colgroup.dataset.bzojSubmitCol) { const col = document.createElement('col'); col.style.width = '80px'; colgroup.appendChild(col); colgroup.dataset.bzojSubmitCol = '1'; } // sticky 表头的 colgroup 也要同步 if (container) { const stickyTable = container.querySelector('table.section__table-header'); if (stickyTable) { const stickyColgroup = stickyTable.querySelector('colgroup'); if (stickyColgroup && !stickyColgroup.dataset.bzojSubmitCol) { const col = document.createElement('col'); col.style.width = '80px'; stickyColgroup.appendChild(col); stickyColgroup.dataset.bzojSubmitCol = '1'; } } }
// 在表头加一列「提交」 // 表头文字右对齐,padding-right 设为 28px(= td 的 16px + 按钮自身的 12px padding), // 使「提交」文字与下方按钮内文字的垂直中线对齐 if (headerRow && !headerRow.dataset.bzojSubmitHeader) { const th = document.createElement('th'); th.textContent = '提交'; th.style.cssText = 'text-align: right; white-space: nowrap; width: 80px; padding-right: 28px;'; headerRow.appendChild(th); headerRow.dataset.bzojSubmitHeader = '1'; } // sticky 表头也加一列 if (stickyHeaderRow && !stickyHeaderRow.dataset.bzojSubmitHeader) { const th = document.createElement('th'); th.textContent = '提交'; th.style.cssText = 'text-align: right; white-space: nowrap; width: 80px; padding-right: 28px;'; stickyHeaderRow.appendChild(th); stickyHeaderRow.dataset.bzojSubmitHeader = '1'; }
// 遍历所有行:有题目链接的加「提交」链接,无题目链接的(如 * 占位行)补空 td 保持列数一致 for (const row of rows) { if (row.dataset.bzojSubmitCell === '1') continue;
const link = row.querySelector('a[href*="/p/"]'); const isValidProblem = link && self.isProblemLink(link.getAttribute('href') || '');
const td = document.createElement('td'); td.style.cssText = 'text-align: right; white-space: nowrap; padding-right: 16px;'; if (isValidProblem) { // 有题目链接:加「提交」按钮 const href = link.getAttribute('href') || ''; const submitUrl = self.buildSubmitUrl(href); const a = document.createElement('a'); a.href = submitUrl; a.className = 'bzoj-submit-col-link'; a.textContent = '提交'; a.title = '递交此题'; a.target = link.target || '_self'; td.appendChild(a); count++; } else { // 无题目链接(如 * 占位行):补空 td,保持列数一致,不破坏行的灰色背景 td.innerHTML = ' '; } row.appendChild(td); row.dataset.bzojSubmitCell = '1'; }
table.dataset.bzojSubmitCol = '1'; } return count; },
_observer: null, _debounce: null, _installObserver: function () { const self = this; if (self._observer) return; self._observer = new MutationObserver(function () { clearTimeout(self._debounce); self._debounce = setTimeout(function () { self.injectColumns(); }, 300); }); self._observer.observe(document.body, { childList: true, subtree: true }); } };
// ================================================================ // 模块四:比赛/作业成绩表增强(scoreboard) // 适用页面: // - /contest/<hex>/scoreboard // - /homework/<hex>/scoreboard // 功能: // 1. 黄色高亮当前登录用户所在行 // 2. 对当前用户行的每道题,异步 fetch 该题的提交记录页面, // 提取最新一次提交的详细信息(状态、分数、耗时、内存), // 用直角状态方块显示在单元格内。 // 兼容所有 Hydro 系 OJ。 // ================================================================
const BZOJ_ScoreboardModule = { /** 状态信息(复用 testcase 模块的颜色定义,方块改为直角) */ STATUS_MAP: { 'accepted': { bg: '#f6ffed', text: 'AC', color: '#389e0d', border: '#b7eb8f' }, 'wrong answer': { bg: '#fff2f0', text: 'WA', color: '#cf1322', border: '#ffccc7' }, 'time limit exceeded': { bg: '#e6f7ff', text: 'TLE', color: '#0958d9', border: '#91d5ff' }, 'memory limit exceeded': { bg: '#e6f7ff', text: 'MLE', color: '#0958d9', border: '#91d5ff' }, 'runtime error': { bg: '#f9f0ff', text: 'RE', color: '#722ed1', border: '#d3adf7' }, 'compile error': { bg: '#fffbe6', text: 'CE', color: '#d48806', border: '#ffe58f' }, 'output limit exceeded': { bg: '#e6f7ff', text: 'OLE', color: '#0958d9', border: '#91d5ff' }, 'system error': { bg: '#f5f5f5', text: 'SE', color: '#434343', border: '#d9d9d9' }, 'judging': { bg: '#e6f7ff', text: '⟳', color: '#0958d9', border: '#91d5ff', spin: true }, 'compiling': { bg: '#e6f7ff', text: '⟳', color: '#0958d9', border: '#91d5ff', spin: true }, 'waiting': { bg: '#e6f7ff', text: '⟳', color: '#0958d9', border: '#91d5ff', spin: true }, 'running': { bg: '#e6f7ff', text: '⟳', color: '#0958d9', border: '#91d5ff', spin: true }, }, DARK_STATUS_MAP: { 'accepted': { bg: '#1e3a1e', text: 'AC', color: '#95de64', border: '#389e0d' }, 'wrong answer': { bg: '#3d1f22', text: 'WA', color: '#ff9c9c', border: '#a8071a' }, 'time limit exceeded': { bg: '#1a2d42', text: 'TLE', color: '#69c0ff', border: '#003a8c' }, 'memory limit exceeded': { bg: '#1a2d42', text: 'MLE', color: '#69c0ff', border: '#003a8c' }, 'runtime error': { bg: '#2d1f3d', text: 'RE', color: '#c9a0f5', border: '#531dab' }, 'compile error': { bg: '#3d321e', text: 'CE', color: '#ffd666', border: '#ad6800' }, 'output limit exceeded': { bg: '#1a2d42', text: 'OLE', color: '#69c0ff', border: '#003a8c' }, 'system error': { bg: '#2e2e2e', text: 'SE', color: '#d9d9d9', border: '#434343' }, },
/** 判断当前页面是否是成绩表页 */ shouldRun: function () { const path = window.location.pathname; return /\/(contest|homework)\/[^\/]+\/scoreboard\/?$/.test(path); },
/** 从 URL 提取 tid(比赛/作业 ID) */ getTid: function () { const m = window.location.pathname.match(/\/(contest|homework)\/([^\/]+)\/scoreboard/); return m ? m[2] : ''; },
/** 检测暗色模式 */ isDarkMode: function () { const html = document.documentElement; if (html.classList.contains('theme--dark')) return true; if (html.classList.contains('theme--light')) return false; if (html.getAttribute('data-mantine-color-scheme') === 'dark') return true; if (html.getAttribute('data-mantine-color-scheme') === 'light') return false; try { const bgColor = getComputedStyle(document.body).backgroundColor; const match = bgColor.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/); if (match) { return (0.299 * +match[1] + 0.587 * +match[2] + 0.114 * +match[3]) / 255 < 0.5; } } catch (e) {} return false; },
/** 获取当前登录用户的 uid */ getCurrentUid: function () { // Hydro 导航栏: nav .nav__list--secondary a[href^="/user/"] const userLink = document.querySelector('nav .nav__list--secondary a[href^="/user/"]'); if (userLink) { const m = userLink.getAttribute('href').match(/\/user\/(\w+)/); if (m) return m[1]; } // 兜底 const altLink = document.querySelector('a[href^="/user/"][class*="user-profile"], a.uname[href^="/user/"]'); if (altLink) { const m = altLink.getAttribute('href').match(/\/user\/(\w+)/); if (m) return m[1]; } return null; },
init: function () { const self = this; if (!self.shouldRun()) return;
GM_addStyle(` /* 当前用户行高亮 */ .bzoj-scoreboard-highlight { background-color: rgba(255, 230, 0, 0.25) !important; } .theme--dark .bzoj-scoreboard-highlight, html[data-mantine-color-scheme="dark"] .bzoj-scoreboard-highlight { background-color: rgba(255, 200, 0, 0.18) !important; } /* 详细状态方块(直角,填满单元格,契合表格) */ .bzoj-score-cell { display: flex; flex-direction: column; align-items: center; justify-content: center; width: 100%; box-sizing: border-box; padding: 4px 2px; border: 1px solid; border-radius: 0; font-family: system-ui, -apple-system, sans-serif; font-weight: 600; line-height: 1.2; cursor: default; transition: transform 0.1s; text-decoration: none; } .bzoj-score-cell:hover { transform: scale(1.05); } /* 让 td 本身也成为 flex 容器,确保方块填满 */ td.col--problem:has(.bzoj-score-cell) { padding: 2px !important; } .bzoj-score-cell__text { font-size: 11px; font-weight: 700; } .bzoj-score-cell__score { font-size: 13px; font-weight: 700; } .bzoj-score-cell__detail { font-size: 9px; font-weight: 400; opacity: 0.8; white-space: nowrap; } @keyframes bzoj-score-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } .bzoj-score-cell__text--spin { animation: bzoj-score-spin 1.5s linear infinite; } /* 加载中占位 */ .bzoj-score-loading { display: inline-block; width: 14px; height: 14px; border: 2px solid rgba(86,117,143,0.2); border-top-color: #56758f; border-radius: 50%; animation: bzoj-score-spin 0.8s linear infinite; } `);
self.enhanceScoreboard(); self._installObserver(); },
/** 标准化状态文本 */ normalizeStatus: function (raw) { if (!raw) return ''; const text = raw.trim().toLowerCase(); const aliases = { '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', }; if (aliases[text]) return aliases[text]; for (const key of Object.keys(this.STATUS_MAP)) { if (text.includes(key)) return key; } return text; },
/** 获取状态信息 */ getStatusInfo: function (key) { const isDark = this.isDarkMode(); const map = isDark ? this.DARK_STATUS_MAP : this.STATUS_MAP; return map[key] || { bg: isDark ? '#2e2e2e' : '#f5f5f5', text: key.substring(0, 3).toUpperCase(), color: isDark ? '#d9d9d9' : '#434343', border: isDark ? '#434343' : '#d9d9d9', }; },
/** 从表头提取每道题的 pid 列表 */ extractProblemIds: function () { // Hydro 成绩表表头在独立的 sticky 表 (table.section__table-header) 或同表 thead const headerLinks = document.querySelectorAll( 'table.section__table-header thead th.col--problem a[href*="/p/"], ' + 'table thead th.col--problem a[href*="/p/"]' ); const pids = []; for (const a of headerLinks) { const m = a.getAttribute('href').match(/\/p\/([^\/?]+)/); if (m) pids.push(m[1]); } return pids; },
/** 增强成绩表:高亮当前用户行 + 异步加载提交详情 */ enhanceScoreboard: function () { const self = this; const uid = self.getCurrentUid(); const tid = self.getTid();
// 查找成绩表 tbody(Hydro 用 table.data-table,tbody 里有行) const tables = document.querySelectorAll('table.data-table'); for (const table of tables) { const tbody = table.querySelector('tbody'); if (!tbody) continue; const rows = tbody.querySelectorAll('tr'); if (rows.length === 0) continue; // 检查是否是成绩表(有 col--rank / col--user 列) if (!table.querySelector('col.col--rank, col.col--user, td.col--rank, td.col--user')) continue; if (table.dataset.bzojScoreboard === '1') continue; table.dataset.bzojScoreboard = '1';
// 提取每题 pid(从表头) const pids = self.extractProblemIds();
for (const row of rows) { if (row.dataset.bzojScoreRow === '1') continue; row.dataset.bzojScoreRow = '1';
// 高亮当前用户行 if (uid) { const userBtn = row.querySelector('[data-uid]'); const userLink = row.querySelector('a[href^="/user/"]'); let rowUid = null; if (userBtn) rowUid = userBtn.getAttribute('data-uid'); else if (userLink) { const m = userLink.getAttribute('href').match(/\/user\/(\w+)/); if (m) rowUid = m[1]; } if (rowUid && rowUid === uid) { row.classList.add('bzoj-scoreboard-highlight'); // 对当前用户行,异步加载每题提交详情 self._loadUserSubmissionDetails(row, uid, tid, pids); } } } } },
/** 异步加载当前用户每道题的提交详情 */ _loadUserSubmissionDetails: async function (row, uid, tid, pids) { const self = this; // 获取当前行的题目单元格(col--problem) const problemCells = row.querySelectorAll('td.col--problem'); if (problemCells.length === 0) return;
// 为每个题目单元格先放加载占位 problemCells.forEach((cell, idx) => { if (cell.querySelector('.bzoj-score-cell, .bzoj-score-loading')) return; // 保留原始分数文本 const originalScore = cell.textContent.trim(); cell.dataset.bzojOriginalScore = originalScore; const loader = document.createElement('span'); loader.className = 'bzoj-score-loading'; cell.innerHTML = ''; cell.appendChild(loader); });
// 逐题 fetch 提交记录 for (let i = 0; i < problemCells.length && i < pids.length; i++) { const cell = problemCells[i]; const pid = pids[i]; try { await self._fetchAndShowDetail(cell, pid, uid, tid); } catch (e) { self._restoreCell(cell); } } },
/** fetch 单题提交记录,提取最新提交的 record 链接,再 fetch record 详情 */ _fetchAndShowDetail: async function (cell, pid, uid, tid) { const self = this; // Hydro 提交记录列表: /record?pid=<pid>&uidOrName=<uid>&tid=<tid> const listUrl = `/record?pid=${encodeURIComponent(pid)}&uidOrName=${encodeURIComponent(uid)}${tid ? '&tid=' + tid : ''}`; const resp = await fetch(listUrl, { credentials: 'same-origin' }); const html = await resp.text(); const doc = new DOMParser().parseFromString(html, 'text/html');
// 找到第一条提交记录的链接 /record/<rid> const recordLink = doc.querySelector('a[href^="/record/"]'); if (!recordLink) { self._restoreCell(cell); return; } const ridMatch = recordLink.getAttribute('href').match(/\/record\/(\w+)/); if (!ridMatch) { self._restoreCell(cell); return; } const rid = ridMatch[1];
// fetch record 详情页 const recordUrl = `/record/${rid}`; const resp2 = await fetch(recordUrl, { credentials: 'same-origin' }); const html2 = await resp2.text(); const doc2 = new DOMParser().parseFromString(html2, 'text/html');
// 从 record 页面提取状态、分数、耗时、内存 const detail = self._extractRecordDetail(doc2); self._renderDetailCell(cell, detail, recordUrl); },
/** 从 record 详情页提取状态/分数/耗时/内存 * 页面结构: * 顶栏 #status .section__title 内含 .record-status--text(状态文字,如 Accepted) * 和 .float-right 或无 class 的 span(分数,如 60) * 侧边栏 #summary 的 dl.horizontal 内: * <dt>分数</dt><dd>60</dd> * <dt>总耗时</dt><dd>39ms</dd> * <dt>峰值时间</dt><dd>1ms</dd> * <dt>峰值内存</dt><dd>768 KiB</dd> */ _extractRecordDetail: function (doc) { const self = this;
// 状态:顶栏的 .record-status--text(排除 .float-right 分数部分) let statusKey = ''; const statusEls = doc.querySelectorAll('#status .record-status--text, .record-status--text'); for (const el of statusEls) { // 克隆后移除 .float-right 子元素,只取状态文字 const clone = el.cloneNode(true); clone.querySelectorAll('.float-right').forEach(e => e.remove()); const text = clone.textContent.trim(); if (text) { statusKey = self.normalizeStatus(text); if (statusKey) break; } }
// 从 #summary 的 dl.horizontal 提取分数/时间/内存 let score = '', time = '', memory = ''; const summaryDl = doc.querySelector('#summary, dl#summary'); if (summaryDl) { const dts = summaryDl.querySelectorAll('dt'); const dds = summaryDl.querySelectorAll('dd'); for (let i = 0; i < dts.length && i < dds.length; i++) { const label = dts[i].textContent.trim().toLowerCase(); const value = dds[i].textContent.trim(); if (label === '分数' || label === 'score') { score = value; } else if (label === '峰值时间' || label === '总耗时' || label.includes('时间') || label.includes('time')) { if (!time) time = value; // 优先取峰值时间/总耗时 } else if (label === '峰值内存' || label.includes('内存') || label.includes('memory')) { memory = value; } } }
// 兜底:分数从顶栏 .float-right 或 section__title 提取 if (!score) { const floatRight = doc.querySelector('#status .float-right, .record-status--text .float-right'); if (floatRight) { score = floatRight.textContent.trim(); } } if (!score) { const titleEl = doc.querySelector('#status .section__title'); if (titleEl) { const m = titleEl.textContent.match(/(\d+)/); if (m) score = m[1]; } }
return { statusKey, score, time, memory }; },
/** 渲染详细状态方块到单元格 */ _renderDetailCell: function (cell, detail, recordUrl) { const self = this; const originalScore = cell.dataset.bzojOriginalScore || ''; cell.innerHTML = '';
if (!detail.statusKey && !detail.score && !originalScore) { self._restoreCell(cell); return; }
const statusKey = detail.statusKey || ''; const info = statusKey ? self.getStatusInfo(statusKey) : { bg: this.isDarkMode() ? '#2e2e2e' : '#f5f5f5', text: '', color: this.isDarkMode() ? '#d9d9d9' : '#434343', border: this.isDarkMode() ? '#434343' : '#d9d9d9', };
const block = document.createElement('a'); block.href = recordUrl; block.target = '_blank'; block.className = 'bzoj-score-cell'; block.style.background = info.bg; block.style.color = info.color; block.style.borderColor = info.border;
// 状态缩写 if (info.text) { const textEl = document.createElement('span'); textEl.className = 'bzoj-score-cell__text'; if (info.spin) textEl.classList.add('bzoj-score-cell__text--spin'); textEl.textContent = info.text; block.appendChild(textEl); } // 分数 const scoreVal = detail.score || originalScore; if (scoreVal) { const scoreEl = document.createElement('span'); scoreEl.className = 'bzoj-score-cell__score'; scoreEl.textContent = scoreVal; block.appendChild(scoreEl); } // 耗时 / 内存 if (detail.time || detail.memory) { const detailEl = document.createElement('span'); detailEl.className = 'bzoj-score-cell__detail'; detailEl.textContent = [detail.time, detail.memory].filter(Boolean).join(' / '); block.appendChild(detailEl); } cell.appendChild(block); },
/** 恢复原始分数显示 */ _restoreCell: function (cell) { const original = cell.dataset.bzojOriginalScore; if (original !== undefined) { cell.innerHTML = ''; cell.textContent = original; } },
_observer: null, _debounce: null, _installObserver: function () { const self = this; if (self._observer) return; self._observer = new MutationObserver(function () { clearTimeout(self._debounce); self._debounce = setTimeout(function () { self.enhanceScoreboard(); }, 500); }); self._observer.observe(document.body, { childList: true, subtree: true }); } };
// ================================================================ // 模块五:网页字体更换器(所有站点运行) // ================================================================
// ==================== 默认常量 ====================
const FS_DEFAULT_BTN_SIZE = 42; const FS_COLLAPSED_VISIBLE = 6;1,650 行未改动全部展开 fsResetIdleTimer(); }
// ================================================================ // 主入口:初始化两个模块 // 主入口:初始化五个模块 // ================================================================
function main() { // 字体更换器:所有站点运行 fsInit();
// BZOJ 测试点模块:仅 bzoj.org 下运行(init 内部有双重判断) BZOJ_TestcaseModule.init();
// BZOJ 题目 Markdown 查看/复制:仅 /p/<id> 题目详情页运行(init 内部有路径与结构双重判断) BZOJ_ProblemMarkdownModule.init();
// BZOJ 题目列表「提交」快捷列:仅题库/比赛/作业/训练列表页运行 BZOJ_SubmitLinkModule.init();
// BZOJ 成绩表增强:仅 /contest/<hex>/scoreboard 和 /homework/<hex>/scoreboard 运行 BZOJ_ScoreboardModule.init(); }
if (document.readyState === 'complete' || document.readyState === 'interactive') { main();6 行未改动