版本比较
OJ 代码对比器 2.0.0(插件)
正文
增加 62 行删除 141 行
112345678391011121381415161718155 行未改动全部展开174175176177172173174175176177178178180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222179180181182334 行未改动全部展开517518519520521522523524525526527528529530531532533571572573574575534535536537577578538539540541542543544545546547548549550551580581582583584585552553554555556557558559560561562563564565566567568501 行未改动全部展开10701071107210731096109710981099110011011102107410751076107723 行未改动110111021103110411051106110711081109111011111112213 行未改动全部展开132613271328132913561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405133013311332133312 行未改动13461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368878 行未改动全部展开22472248224922502312231323142315231623172318231923202321232223232324232523262327232823292251225222532254150 行未改动全部展开用 AI 做的,用于实现类似于 CF 的代码对比功能,实测洛谷、CF 较为稳定,AT 无法抓取提交代码(因此在 AT 上无法使用有关提交记录的功能)。请先[安装篡改猴](https://www.tampermonkey.net)再使用。(由于代码 $100\%$ 由 AI 生成,没敢放在公开推荐的“休闲·娱乐”或“科技·工程”区。)本插件是用 AI 做的,用于实现类似于 CF 的代码对比功能,实测在洛谷、CF 上使用时较为稳定,在 AT 使用时无法抓取提交代码(因此在 AT 上无法使用有关提交记录的功能)。请先[安装篡改猴](https://www.tampermonkey.net)再使用。(由于代码 $100\%$ 由 AI 生成且涉及 API 调用,没敢放在公开推荐的“休闲·娱乐”或“科技·工程”区。)
使用提示:
1. CF “与上次提交记录对比”最多只抓取同一个人前 $2000$ 个提交,如果你确定有个不在前 $2000$ 个提交之内的提交,请自行想办法找到那个提交;2. 受篇幅局限,此处没有实现“格式化代码”功能,如果想要格式化代码,可以自行将两份代码复制下来,自行格式化后用“两份代码对比”功能进行对比;3. 本插件并没有获得任何 OJ 的认可(虽然调用 API 次数较少),请不要**滥**用(我认为正常使用应该没问题)。
:::info[代码(提示:目前 $2000$ 多行,$100$ 多 KB)]:::info[代码(提示:目前 $2000$ 多行,约 $100$ KB)]```js// ==UserScript==// @name OJ 代码对比 (Luogu/AtCoder/Codeforces)// @namespace oj-code-diff// @version 2.0.0// @version 2.1.0// @description OJ 代码对比工具,支持洛谷、AtCoder、Codeforces 的提交记录对比,支持手动输入、字体/行距/缩进调节、亮暗模式// @author useluogu// @homepageURL https://github.com/useluogu/Code-Comparison-Plugin// @updateURL https://raw.githubusercontent.com/useluogu/Code-Comparison-Plugin/main/oj-code-diff.user.js155 行未改动全部展开 .replace(/>/g, '>') .replace(/"/g, '"'); }
/** * 格式化代码:归一化缩进、去除尾随空格、确保末尾换行 * 保留原 indent 风格(检测首行缩进,统一应用到全文) */ function formatCode(code) { if (!code) return code; const lines = code.split('\n');
// 1. 去除每行尾随空格 const trimmed = lines.map(l => l.replace(/\s+$/, ''));
// 2. 检测主缩进风格 let indentStr = ' '; // 默认 2 空格 for (const line of trimmed) { const m = line.match(/^(\s+)\S/); if (m && m[1].length > 0) { const detected = m[1]; // 如果检测到 tab 就保留 tab,否则用检测到的空格数 if (detected.startsWith('\t')) { indentStr = '\t'; } else { indentStr = detected; } break; } }
// 3. 重新规范化缩进(保留缩进层级,但统一 indent string) // 先计算每行原始缩进层级,再用新的 indentStr 重建 function measureIndent(line) { const m = line.match(/^(\s*)/); if (!m) return 0; const raw = m[1]; if (raw.length === 0) return 0; // 估算层级 if (raw.startsWith('\t')) return raw.length; // 空格:根据检测到的 indentStr 长度估算 const tabSize = indentStr === '\t' ? 4 : indentStr.length; return Math.round(raw.length / tabSize); }
const result = trimmed.map(line => { if (line.trim() === '') return ''; const level = measureIndent(line); return indentStr.repeat(level) + line.trimStart(); });
// 4. 确保末尾换行 while (result.length > 0 && result[result.length - 1] === '') { result.pop(); } return result.join('\n') + '\n'; }
/** * GM_xmlhttpRequest 封装(用于跨域请求) * 同源请求优先用 fetch(支持 cookies),跨域回退到 GM_xmlhttpRequest */334 行未改动全部展开 async findPrevRecord(submissionId, currentRecord) { const handle = currentRecord.handle; if (!handle) throw new Error('无法获取提交者 handle(请确认已登录 CF 且本提交为自己的)');
// 检查提交者是否为当前登录用户(避免拿别人的提交来找"上一次提交") const loggedInHandle = _unsafeWindow.CF?.currentUserHandle || document.querySelector('a.rated-user, a[href*="/profile/"]')?.textContent?.trim() || ''; if (loggedInHandle && loggedInHandle !== handle) { throw new Error(`此提交属于 ${handle},不是你本人的提交,无法查找上一次提交`); }
const curContestId = Number(currentRecord.contestId); const curProblemIdx = currentRecord.problemIndex; if (!curContestId || !curProblemIdx) { throw new Error('无法识别当前提交的题目信息,无法查找上一次提交'); }
// 拉取该用户最近提交列表(最多 500 条) const apiUrl = `https://codeforces.com/api/user.status?handle=${encodeURIComponent(handle)}&from=1&count=500`; const apiText = await gmFetch(apiUrl); const apiData = JSON.parse(apiText); if (apiData.status !== 'OK') throw new Error(`CF API 错误: ${apiData.comment}`); // 分页搜索:最多 2 页(每页 1000 条),覆盖约 2000 条提交记录 const PAGE_SIZE = 1000; const MAX_PAGES = 2;
const subs = apiData.result; // 按提交时间倒序 const currentIdx = subs.findIndex(s => s.id === Number(submissionId)); for (let page = 0; page < MAX_PAGES; page++) { const from = page * PAGE_SIZE + 1; const apiUrl = `https://codeforces.com/api/user.status?handle=${encodeURIComponent(handle)}&from=${from}&count=${PAGE_SIZE}`; const apiText = await gmFetch(apiUrl); const apiData = JSON.parse(apiText); if (apiData.status !== 'OK') throw new Error(`CF API 错误: ${apiData.comment}`);
const subs = apiData.result; // 按提交时间倒序
// 只在第 1 页查找当前提交的位置 const currentIdx = page === 0 ? subs.findIndex(s => s.id === Number(submissionId)) : -1;
// 从当前提交往后(即更早的提交)找同一 contest + 同一 problem 的提交 const start = currentIdx >= 0 ? currentIdx + 1 : 0; for (let i = start; i < subs.length; i++) { const s = subs[i]; if (s.problem.contestId === curContestId && s.problem.index === curProblemIdx) { return { id: String(s.id), contestId: String(s.contestId || curContestId) }; // 从当前提交往后(更早的提交)找同一题 const start = currentIdx >= 0 ? currentIdx + 1 : 0; for (let i = start; i < subs.length; i++) { const s = subs[i]; if (s.problem.contestId === curContestId && s.problem.index === curProblemIdx) { return { id: String(s.id), contestId: String(s.contestId || curContestId) }; } }
// 当前提交不在本页末尾 → 已全量搜索,无需下一页 if (currentIdx >= 0 && currentIdx + 1 < subs.length) break; // 当前提交未找到且本页未满 → 后面不会有更旧的了 if (currentIdx < 0 && subs.length < PAGE_SIZE) break; }
throw new Error(`未找到 ${handle} 对题目 ${curContestId}${curProblemIdx} 的上一次提交`); },501 行未改动全部展开 '</button>' +
'<span class="oj-diff-settings-divider">|</span>' +
'<button class="oj-diff-format-btn" id="oj-diff-format-btn" title="格式化代码(缩进归一化、去尾空格等)">' + '<span class="oj-diff-format-icon">✨</span>' + '<span class="oj-diff-format-label">格式化代码</span>' + '</button>' +
'<span class="oj-diff-settings-divider">|</span>' +
'<button class="oj-diff-view-toggle" id="oj-diff-view-btn" title="切换统一/并列视图">' + '<span class="oj-diff-view-icon"></span>' + '<span class="oj-diff-view-label"></span>' + '</button>';23 行未改动 '<button class="oj-diff-btn oj-diff-btn-secondary" id="oj-diff-record-compare">📋 两次提交记录对比</button>'; }
const footerRight = document.createElement('div'); footerRight.style.cssText = 'display:flex;gap:8px;align-items:center;'; footerRight.innerHTML = '<button class="oj-diff-btn oj-diff-btn-secondary" id="oj-diff-copy-old">📋 复制旧版</button>' + '<button class="oj-diff-btn oj-diff-btn-secondary" id="oj-diff-copy-new">📋 复制新版</button>' + '<button class="oj-diff-btn oj-diff-btn-primary" id="oj-diff-close-btn">关闭</button>';
footer.appendChild(footerLeft); footer.appendChild(footerRight);213 行未改动全部展开 }); // 初始如果是 split 也要加宽 if (currentViewMode === 'split') modal.style.maxWidth = '1400px';
// ---- 格式化代码(可切换) ---- const formatBtn = overlay.querySelector('#oj-diff-format-btn'); const origOldCode = oldCode, origNewCode = newCode; let formattedOldCode = null, formattedNewCode = null; let isFormatted = false;
function applyFormattedState() { if (isFormatted && formattedOldCode !== null) { oldCode = formattedOldCode; newCode = formattedNewCode; } else { oldCode = origOldCode; newCode = origNewCode; } const newOldLines = String(oldCode || '').split('\n'); const newNewLines = String(newCode || '').split('\n'); const newRawDiffs = lineDiff(newOldLines, newNewLines); expandedDiffs = newRawDiffs; const newDisplayDiffs = currentSettings.collapseUnchanged ? collapseUnchanged(newRawDiffs) : newRawDiffs; currentDiffs = newDisplayDiffs; codeArea.innerHTML = renderCodeHtml(newDisplayDiffs, currentViewMode); applyCodeSettings(codeArea, currentSettings); bindCollapseButtons(codeArea, newDisplayDiffs, newRawDiffs, currentSettings); refreshCollapseIcon(); formatBtn.classList.toggle('active', isFormatted); }
formatBtn.addEventListener('click', () => { if (isFormatted) { isFormatted = false; applyFormattedState(); showToast('已恢复原始代码', 'success'); return; } // 第一次格式化:计算并缓存格式化结果 if (formattedOldCode === null) { formattedOldCode = formatCode(String(origOldCode || '')); formattedNewCode = formatCode(String(origNewCode || '')); if (formattedOldCode === origOldCode && formattedNewCode === origNewCode) { showToast('代码无需格式化', 'success'); return; } } isFormatted = true; applyFormattedState(); showToast('代码已格式化', 'success'); });
// 亮暗模式切换 const THEME_CYCLE = ['auto', 'light', 'dark']; themeBtn.addEventListener('click', () => { const cur = currentSettings.themeMode || 'auto';12 行未改动 const hasParent = modalStack.length > 0;
closeBtn.addEventListener('click', closeBack); overlay.querySelector('#oj-diff-close-btn').addEventListener('click', closeBack); // 复制代码 overlay.querySelector('#oj-diff-copy-old').addEventListener('click', () => { navigator.clipboard.writeText(String(oldCode || '')).then(() => { showToast('旧版代码已复制到剪贴板', 'success'); }).catch(() => { showToast('复制失败(请检查剪贴板权限)', 'error'); }); }); overlay.querySelector('#oj-diff-copy-new').addEventListener('click', () => { navigator.clipboard.writeText(String(newCode || '')).then(() => { showToast('新版代码已复制到剪贴板', 'success'); }).catch(() => { showToast('复制失败(请检查剪贴板权限)', 'error'); }); }); overlay.addEventListener('click', (e) => { if (e.target === overlay) closeBack(); }); const escHandler = (e) => { if (e.key === 'Escape') { closeBack(); document.removeEventListener('keydown', escHandler); } };878 行未改动全部展开 .oj-diff-dark .oj-diff-view-toggle:hover { background: #21262d; border-color: #667eea; color: #667eea; } .oj-diff-dark .oj-diff-view-toggle.active, .oj-diff-dark .oj-diff-view-toggle.active:hover { border-color: #667eea; color: #667eea; background: #1a2332; }
/* Format button */ .oj-diff-format-btn { height: 32px; border: 1.5px solid; border-radius: 6px; cursor: pointer; font-size: 12px; display: flex; align-items: center; gap: 4px; flex-shrink: 0; transition: all 0.2s; padding: 0 8px; background: transparent; white-space: nowrap; } .oj-diff-format-icon { font-size: 14px; line-height: 1; } .oj-diff-format-label { font-size: 11px; line-height: 1; } .oj-diff-light .oj-diff-format-btn { color: #586069; border-color: #d1d5da; } .oj-diff-light .oj-diff-format-btn:hover { background: #f3f4f6; border-color: #667eea; color: #667eea; } .oj-diff-light .oj-diff-format-btn.active, .oj-diff-light .oj-diff-format-btn.active:hover { border-color: #667eea; color: #667eea; background: #eaf1fb; } .oj-diff-dark .oj-diff-format-btn { color: #8b949e; border-color: #30363d; } .oj-diff-dark .oj-diff-format-btn:hover { background: #21262d; border-color: #667eea; color: #667eea; } .oj-diff-dark .oj-diff-format-btn.active, .oj-diff-dark .oj-diff-format-btn.active:hover { border-color: #667eea; color: #667eea; background: #1a2332; }
/* Split view */ .oj-diff-split-container { display: flex; flex-direction: column; width: 100%; }
.oj-diff-split-row {150 行未改动全部展开