标题
增加 1 行删除 1 行
1洛谷代码对比器 1.01OJ 代码对比器 2.2.1(插件)
正文
增加 2171 行删除 1076 行
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427用 AI 做的,用于实现类似于 CF 的代码对比功能,不一定没有问题。请先安装篡改猴再使用。~~链接自己去搜。~~:::info[提示:请不要随意展开,这玩意 $41$ KB,$1.4$k 行]``````// ==UserScript==// @name 洛谷代码对比// @namespace luogu-code-diff// @version 1.3.0// @description 在洛谷记录详情页添加代码对比功能// @match https://www.luogu.com.cn/record/*// @match https://www.luogu.com.cn/recordlist*// @grant GM_addStyle// @run-at document-idle// @license MIT// ==/UserScript==(function () {'use strict';const _unsafeWindow = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window;// ======================== 常量配置 ========================const LUOGU_BASE = 'https://www.luogu.com.cn';const COLORS = {light: {addedBg: '#e6ffed',addedLineNum: '#22863a',addedText: '#24292e',removedBg: '#ffeef0',removedLineNum: '#cb2431',removedText: '#24292e',unchangedBg: '#ffffff',unchangedText: '#24292e',lineNumText: '#959da5',lineNumBg: '#f6f8fa',border: '#e1e4e8',modalBg: '#ffffff',overlayBg: 'rgba(0, 0, 0, 0.5)',},dark: {addedBg: '#1b3a1f',addedLineNum: '#3fb950',addedText: '#e6edf3',removedBg: '#3d1a1a',removedLineNum: '#f85149',removedText: '#e6edf3',unchangedBg: '#0d1117',unchangedText: '#e6edf3',lineNumText: '#484f58',lineNumBg: '#161b22',border: '#30363d',modalBg: '#161b22',overlayBg: 'rgba(0, 0, 0, 0.7)',},};// ======================== 用户设置 ========================const SETTINGS_KEY = 'lg-diff-settings';const DEFAULT_SETTINGS = {fontSize: 13, // 字体大小 pxlineHeight: 1.5, // 行间距倍数(1.5 = 1行代码 + 0.5行空行)};/** 加载用户设置 */function loadSettings() {try {const raw = localStorage.getItem(SETTINGS_KEY);if (raw) {const parsed = JSON.parse(raw);return { ...DEFAULT_SETTINGS, ...parsed };}} catch (e) {console.warn('[洛谷代码对比] 读取设置失败:', e);}return { ...DEFAULT_SETTINGS };}/** 保存用户设置 */function saveSettings(settings) {try {localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));} catch (e) {console.warn('[洛谷代码对比] 保存设置失败:', e);}}/** 应用设置到代码区域 */function applyCodeSettings(codeEl, settings) {if (!codeEl) return;codeEl.style.fontSize = settings.fontSize + 'px';codeEl.style.lineHeight = String(settings.lineHeight);// 同步行号区域const lineNums = codeEl.querySelectorAll('.lg-diff-ln-old, .lg-diff-ln-new');lineNums.forEach(el => {el.style.fontSize = Math.max(settings.fontSize - 1, 10) + 'px';el.style.lineHeight = String(settings.lineHeight);});}// ======================== 工具函数 ========================/** 判断当前是否为暗色模式 */function isDarkMode() {return (document.documentElement.getAttribute('data-theme') === 'dark' ||document.body?.getAttribute('data-theme') === 'dark' ||window.matchMedia('(prefers-color-scheme: dark)').matches);}/** 获取当前配色方案 */function getColors() {return isDarkMode() ? COLORS.dark : COLORS.light;}/** HTML 转义 */function escapeHtml(str) {if (str === null || str === undefined) return '';return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');}/** 从当前 URL 提取记录 ID */function getRecordIdFromUrl() {const match = window.location.pathname.match(/\/record\/(\d+)/);return match ? match[1] : null;}/** 发起洛谷 API 请求(同源 fetch,自动携带 Cookie)* 使用 _contentOnly 参数让洛谷返回 JSON 数据而非 HTML*/function fetchLuogu(url) {// 构建带 _contentOnly 参数的 URLconst fullUrl = url.startsWith('http') ? url : LUOGU_BASE + url;const separator = fullUrl.includes('?') ? '&' : '?';const jsonUrl = `${fullUrl}${separator}_contentOnly=1`;return fetch(jsonUrl, {method: 'GET',credentials: 'same-origin',headers: {Accept: 'application/json',},}).then((response) => {if (!response.ok) {throw new Error(`HTTP ${response.status}: ${response.statusText}`);}return response.json();}).catch((e) => {throw new Error(`请求失败: ${e.message}`);});}/** 从洛谷页面响应中提取数据* 洛谷 _contentOnly 返回格式:* { code: 200, currentData: {...}, currentTemplate: "...", currentUser: {...} }*/function extractData(response) {// 检查返回码if (response.code !== undefined && response.code !== 200) {throw new Error(`洛谷返回错误码: ${response.code}`);}// _contentOnly 格式:数据在 currentData 中if (response.currentData) return response.currentData;// Lentille 格式:数据在 data 中if (response.data) return response.data;// 记录详情可能直接在顶层if (response.record) return response;// 记录列表的 records 字段if (response.records) return response;console.log('[洛谷代码对比] 未识别的响应格式:', response);throw new Error('无法从响应中提取数据');}// ======================== Diff 算法 ========================/*** 基于行级的 LCS diff 算法* 返回 [{type: 'added'|'removed'|'unchanged', oldLine, newLine, content}]*/function lineDiff(oldLines, newLines) {const m = oldLines.length;const n = newLines.length;// 构建 LCS DP 表const dp = new Array(m + 1);for (let i = 0; i <= m; i++) {dp[i] = new Array(n + 1).fill(0);}for (let i = 1; i <= m; i++) {for (let j = 1; j <= n; j++) {if (oldLines[i - 1] === newLines[j - 1]) {dp[i][j] = dp[i - 1][j - 1] + 1;} else {dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);}}}// 回溯 diff 结果const result = [];let i = m,j = n;const rawDiffs = [];while (i > 0 || j > 0) {if (i > 0 && j > 0 && oldLines[i - 1] === newLines[j - 1]) {rawDiffs.push({ type: 'unchanged', oldIdx: i - 1, newIdx: j - 1, content: oldLines[i - 1] });i--;j--;} else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) {rawDiffs.push({ type: 'added', newIdx: j - 1, content: newLines[j - 1] });j--;} else {rawDiffs.push({ type: 'removed', oldIdx: i - 1, content: oldLines[i - 1] });i--;}}rawDiffs.reverse();// 合并相邻的删除和新增为"修改"const merged = [];let k = 0;while (k < rawDiffs.length) {if (rawDiffs[k].type === 'removed' &&k + 1 < rawDiffs.length &&rawDiffs[k + 1].type === 'added') {// 收集连续的 removed + added 对const removedGroup = [];const addedGroup = [];while (k < rawDiffs.length &&(rawDiffs[k].type === 'removed' ||(rawDiffs[k].type === 'added' && removedGroup.length > 0))) {if (rawDiffs[k].type === 'removed') {removedGroup.push(rawDiffs[k]);} else {addedGroup.push(rawDiffs[k]);}k++;}// 先输出删除行,再输出新增行for (const item of removedGroup) {merged.push({ ...item, pairedWithAdd: true });}for (const item of addedGroup) {merged.push({ ...item, pairedWithRemove: true });}} else {merged.push(rawDiffs[k]);k++;}}return merged;}// ======================== UI 组件 ========================/** 创建加载遮罩 */function createLoadingOverlay(message) {const overlay = document.createElement('div');overlay.id = 'lg-diff-loading';overlay.style.cssText = `position: fixed; top: 0; left: 0; right: 0; bottom: 0;background: rgba(0,0,0,0.5); z-index: 100000;display: flex; align-items: center; justify-content: center;flex-direction: column; gap: 16px;`;overlay.innerHTML = `<div style="background: ${getColors().modalBg}; border-radius: 12px;padding: 32px 48px; text-align: center;box-shadow: 0 8px 32px rgba(0,0,0,0.3);color: ${isDarkMode() ? '#e6edf3' : '#24292e'};font-size: 16px;"><div class="lg-diff-spinner" style="width: 36px; height: 36px; margin: 0 auto 16px;border: 3px solid ${isDarkMode() ? '#30363d' : '#e1e4e8'};border-top-color: #3498db; border-radius: 50%;animation: lg-diff-spin 0.8s linear infinite;"></div><div>${escapeHtml(message)}</div></div>`;document.body.appendChild(overlay);return overlay;}/** 移除加载遮罩 */function removeLoadingOverlay() {const overlay = document.getElementById('lg-diff-loading');if (overlay) overlay.remove();}/** 渲染 Diff 结果到模态框 */function showDiffModal(oldCode, newCode, oldRecordId, newRecordId) {const colors = getColors();const dark = isDarkMode();// 执行 diff(确保 sourceCode 是字符串)const oldLines = String(oldCode || '').split('\n');const newLines = String(newCode || '').split('\n');const diffs = lineDiff(oldLines, newLines);// 构建代码行 HTMLlet codeHtml = '';let oldLineNum = 0;let newLineNum = 0;for (const diff of diffs) {if (diff.type === 'unchanged') {oldLineNum++;newLineNum++;codeHtml += '<div class="lg-diff-line lg-diff-unchanged">' +'<span class="lg-diff-ln-old">' + oldLineNum + '</span>' +'<span class="lg-diff-ln-new">' + newLineNum + '</span>' +'<span class="lg-diff-content">' + escapeHtml(diff.content) + '</span>' +'</div>';} else if (diff.type === 'removed') {oldLineNum++;codeHtml += '<div class="lg-diff-line lg-diff-removed">' +'<span class="lg-diff-ln-old">' + oldLineNum + '</span>' +'<span class="lg-diff-ln-new"></span>' +'<span class="lg-diff-marker">-</span>' +'<span class="lg-diff-content">' + escapeHtml(diff.content) + '</span>' +'</div>';} else if (diff.type === 'added') {newLineNum++;codeHtml += '<div class="lg-diff-line lg-diff-added">' +'<span class="lg-diff-ln-old"></span>' +'<span class="lg-diff-ln-new">' + newLineNum + '</span>' +'<span class="lg-diff-marker">+</span>' +'<span class="lg-diff-content">' + escapeHtml(diff.content) + '</span>' +'</div>';}}// 统计变更const addedCount = diffs.filter((d) => d.type === 'added').length;const removedCount = diffs.filter((d) => d.type === 'removed').length;// 加载用户设置const settings = loadSettings();// 创建模态框const overlay = document.createElement('div');overlay.id = 'lg-diff-modal-overlay';overlay.innerHTML = `<div class="lg-diff-modal ${dark ? 'lg-diff-dark' : 'lg-diff-light'}"><div class="lg-diff-header"><div class="lg-diff-title"><span class="lg-diff-title-icon">📋</span>代码对比</div><div class="lg-diff-ids"><a href="${LUOGU_BASE}/record/${escapeHtml(oldRecordId)}" target="_blank" class="lg-diff-record-link old">#${escapeHtml(String(oldRecordId))}</a><span class="lg-diff-arrow">→</span><a href="${LUOGU_BASE}/record/${escapeHtml(newRecordId)}" target="_blank" class="lg-diff-record-link new">#${escapeHtml(String(newRecordId))}</a></div><div class="lg-diff-stats"><span class="lg-diff-stat-added">+${addedCount} 行</span><span class="lg-diff-stat-removed">-${removedCount} 行</span></div><button class="lg-diff-close" title="关闭">✕</button></div><div class="lg-diff-body"><div class="lg-diff-code" id="lg-diff-code-area">${codeHtml}</div></div><div class="lg-diff-settings-bar" id="lg-diff-settings-bar"><span class="lg-diff-settings-label">字号</span><button class="lg-diff-settings-btn" id="lg-diff-font-dec" title="缩小字体">A−</button><span class="lg-diff-settings-value" id="lg-diff-font-value">${settings.fontSize}px</span><button class="lg-diff-settings-btn" id="lg-diff-font-inc" title="放大字体">A+</button><span class="lg-diff-settings-divider">|</span><span class="lg-diff-settings-label">行距</span><button class="lg-diff-settings-btn" id="lg-diff-lh-dec" title="缩小行距">−</button><span class="lg-diff-settings-value" id="lg-diff-lh-value">${settings.lineHeight}x</span><button class="lg-diff-settings-btn" id="lg-diff-lh-inc" title="放大行距">+</button></div><div class="lg-diff-footer"><button class="lg-diff-btn lg-diff-btn-secondary" id="lg-diff-custom-compare">对比其他提交</button><button class="lg-diff-btn lg-diff-btn-primary" id="lg-diff-close-btn">关闭</button></div></div>`;document.body.appendChild(overlay);// 应用用户设置const codeArea = overlay.querySelector('#lg-diff-code-area');applyCodeSettings(codeArea, settings);// 字体大小调节let currentSettings = { ...settings };const fontDecBtn = overlay.querySelector('#lg-diff-font-dec');const fontIncBtn = overlay.querySelector('#lg-diff-font-inc');const fontValueEl = overlay.querySelector('#lg-diff-font-value');const lhDecBtn = overlay.querySelector('#lg-diff-lh-dec');const lhIncBtn = overlay.querySelector('#lg-diff-lh-inc');const lhValueEl = overlay.querySelector('#lg-diff-lh-value');fontDecBtn.addEventListener('click', () => {currentSettings.fontSize = Math.max(currentSettings.fontSize - 1, 8);fontValueEl.textContent = currentSettings.fontSize + 'px';applyCodeSettings(codeArea, currentSettings);saveSettings(currentSettings);});fontIncBtn.addEventListener('click', () => {currentSettings.fontSize = Math.min(currentSettings.fontSize + 1, 28);fontValueEl.textContent = currentSettings.fontSize + 'px';applyCodeSettings(codeArea, currentSettings);saveSettings(currentSettings);});lhDecBtn.addEventListener('click', () => {currentSettings.lineHeight = Math.max(+(currentSettings.lineHeight - 0.1).toFixed(1), 1.0);lhValueEl.textContent = currentSettings.lineHeight + 'x';applyCodeSettings(codeArea, currentSettings);saveSettings(currentSettings);});lhIncBtn.addEventListener('click', () => {currentSettings.lineHeight = Math.min(+(currentSettings.lineHeight + 0.1).toFixed(1), 3.0);lhValueEl.textContent = currentSettings.lineHeight + 'x';applyCodeSettings(codeArea, currentSettings);saveSettings(currentSettings);});// 事件绑定const close = () => overlay.remove();overlay.querySelector('.lg-diff-close').addEventListener('click', close);overlay.querySelector('#lg-diff-close-btn').addEventListener('click', close);overlay.addEventListener('click', (e) => {if (e.target === overlay) close();});// 自定义对比overlay.querySelector('#lg-diff-custom-compare').addEventListener('click', () => {close();promptCustomCompare(newRecordId);});// ESC 关闭const escHandler = (e) => {if (e.key === 'Escape') {close();document.removeEventListener('keydown', escHandler);}};document.addEventListener('keydown', escHandler);}/** 提示用户输入自定义提交 ID */function promptCustomCompare(currentRecordId) {const existing = document.getElementById('lg-diff-custom-dialog');if (existing) existing.remove();const dark = isDarkMode();const colors = getColors();const dialog = document.createElement('div');dialog.id = 'lg-diff-custom-dialog';dialog.innerHTML = `<div class="lg-diff-modal ${dark ? 'lg-diff-dark' : 'lg-diff-light'}" style="max-width: 480px;"><div class="lg-diff-header"><div class="lg-diff-title">输入对比提交 ID</div><button class="lg-diff-close" title="关闭">✕</button></div><div class="lg-diff-body" style="padding: 24px;"><p style="margin: 0 0 16px; color: ${dark ? '#8b949e' : '#586069'}; font-size: 14px;">输入要与当前提交 (#${escapeHtml(String(currentRecordId))}) 对比的提交记录 ID</p><input type="text" id="lg-diff-custom-id" placeholder="例如 12345678" style="width: 100%; padding: 10px 14px; border-radius: 8px;border: 1px solid ${dark ? '#30363d' : '#e1e4e8'};background: ${dark ? '#0d1117' : '#ffffff'};color: ${dark ? '#e6edf3' : '#24292e'};font-size: 15px; outline: none; box-sizing: border-box;" /><div id="lg-diff-custom-error" style="color: #cb2431; font-size: 13px; margin-top: 8px; display: none;"></div></div><div class="lg-diff-footer"><button class="lg-diff-btn lg-diff-btn-secondary" id="lg-diff-custom-cancel">取消</button><button class="lg-diff-btn lg-diff-btn-primary" id="lg-diff-custom-ok">开始对比</button></div></div>`;document.body.appendChild(dialog);const closeDialog = () => dialog.remove();dialog.querySelector('.lg-diff-close').addEventListener('click', closeDialog);dialog.querySelector('#lg-diff-custom-cancel').addEventListener('click', closeDialog);dialog.addEventListener('click', (e) => {if (e.target === dialog) closeDialog();});const input = dialog.querySelector('#lg-diff-custom-id');input.focus();const doCompare = async () => {const targetId = input.value.trim();if (!targetId || !/^\d+$/.test(targetId)) {const errEl = dialog.querySelector('#lg-diff-custom-error');errEl.textContent = '请输入有效的数字 ID';errEl.style.display = 'block';return;}closeDialog();await runCompare(currentRecordId, targetId);};dialog.querySelector('#lg-diff-custom-ok').addEventListener('click', doCompare);input.addEventListener('keydown', (e) => {if (e.key === 'Enter') doCompare();});}// ======================== 核心逻辑 ========================/** 获取记录详情(包含源代码)* 请求 /record/{id}?_contentOnly=1* 返回格式: { code: 200, currentData: { record: RecordDetails, ... } }*/async function fetchRecordDetail(recordId) {const url = `${LUOGU_BASE}/record/${recordId}`;const response = await fetchLuogu(url);console.log('[洛谷代码对比] 记录详情响应:', response);const data = extractData(response);// _contentOnly 返回的数据在 currentData 中,record 直接在 data 下if (!data.record) {console.error('[洛谷代码对比] 响应中没有 record 字段,响应数据:', JSON.stringify(data).slice(0, 500));throw new Error('无法获取记录信息(response 中缺少 record 字段)');}return data.record;}/** 获取提交记录列表* 请求 /record/list?pid=P1001&user=123&_contentOnly=1* 返回格式: { code: 200, currentData: { records: [...], ... } }* 注意: records 可能是分页对象 { result: [...], count, perPage } 或直接数组*/async function fetchRecordList(params) {const query = new URLSearchParams();if (params.pid) query.set('pid', params.pid);if (params.user) query.set('user', params.user);if (params.page) query.set('page', String(params.page));const url = `${LUOGU_BASE}/record/list?${query.toString()}`;const response = await fetchLuogu(url);console.log('[洛谷代码对比] 记录列表响应:', response);const data = extractData(response);console.log('[洛谷代码对比] 记录列表 data.records 类型:', typeof data.records, Array.isArray(data.records), JSON.stringify(data.records).slice(0, 300));//洛谷 records 字段可能是:// 1. 直接数组: [record1, record2, ...]// 2. 分页对象: { result: [...], count: N, perPage: M }// 3. 其他嵌套结构: { records: [...] }(较少见但防御性处理)let records = data.records;if (Array.isArray(records)) {// 直接数组,无需处理return records;}if (records && typeof records === 'object') {// 分页对象:result 字段包含实际数组if (Array.isArray(records.result)) {console.log('[洛谷代码对比] records 是分页对象,使用 result 字段');return records.result;}// 嵌套 records 字段if (Array.isArray(records.records)) {console.log('[洛谷代码对比] records 是嵌套对象,使用 records.records 字段');return records.records;}// records 对象的 values 或 data 字段if (Array.isArray(records.values)) {return records.values;}if (Array.isArray(records.data)) {return records.data;}}// records 为 null/undefined 或无法识别的结构console.error('[洛谷代码对比] 无法识别 records 格式:', records);return [];}/** 查找同一用户同一题目的上一次提交 */async function findPrevRecord(currentRecordId, pid, uid) {// 洛谷记录列表默认按时间倒序排列(最新的在前)// 遍历前两页查找for (let page = 1; page <= 2; page++) {const records = await fetchRecordList({ pid, user: String(uid), page });const currentIdx = records.findIndex((r) => String(r.id) === String(currentRecordId));if (currentIdx !== -1) {// 当前提交在本页找到,返回列表中它之后的第一个(即时间上更早的)if (currentIdx + 1 < records.length) {return records[currentIdx + 1];}// 当前提交在列表末尾,需要看下一页continue;}// 当前提交不在本页,如果当前页的记录提交时间都早于当前提交,// 则返回本页第一条(最新的早于当前的)if (records.length > 0) {// 检查本页是否有不是当前提交的记录for (const record of records) {if (String(record.id) !== String(currentRecordId)) {return record;}}}}throw new Error('未找到该题目的上一次提交记录');}/** 执行对比 */async function runCompare(currentRecordId, targetRecordId) {const loading = createLoadingOverlay('正在获取代码,请稍候...');try {let currentRecord;let targetRecord;// 优先从页面内嵌数据获取当前提交信息(零延迟)const pageData = _unsafeWindow._feInjection?.currentData;if (pageData?.record) {currentRecord = pageData.record;console.log('[洛谷代码对比] 从页面内嵌数据获取当前记录成功');}if (targetRecordId) {// 有指定的对比 IDif (!currentRecord) {updateLoadingMessage(loading, '正在获取当前提交代码...');currentRecord = await fetchRecordDetail(currentRecordId);}updateLoadingMessage(loading, '正在获取对比提交代码...');targetRecord = await fetchRecordDetail(targetRecordId);} else {// 自动查找上一次提交if (!currentRecord) {updateLoadingMessage(loading, '正在获取当前提交信息...');currentRecord = await fetchRecordDetail(currentRecordId);}// 洛谷 problem 对象结构:{ pid: "P1001", title: "...", ... }// 也可能嵌套在其他结构中const problem = currentRecord.problem;const pid =problem?.pid ||problem?.id ||problem?.problemId ||(typeof problem === 'string' ? problem : null);// 用户 ID 可能直接在 record 层级或 user 对象中const uid = currentRecord.user?.uid || currentRecord.uid;if (!pid) throw new Error('无法获取题目 ID(problem 字段缺失)');if (!uid) throw new Error('无法获取用户信息(可能需要登录)');updateLoadingMessage(loading, '正在查找上一次提交记录...');const prevRecordBase = await findPrevRecord(currentRecordId, pid, uid);updateLoadingMessage(loading, '正在获取上一次提交代码...');targetRecord = await fetchRecordDetail(prevRecordBase.id);}// 检查源代码是否可访问if (!currentRecord.sourceCode && currentRecord.sourceCode !== '') {throw new Error('当前提交的代码不可访问(可能是隐私设置)');}if (!targetRecord.sourceCode && targetRecord.sourceCode !== '') {throw new Error('对比提交的代码不可访问(可能是隐私设置)');}removeLoadingOverlay();// 展示 diff 结果(targetRecord 是旧代码,currentRecord 是新代码)showDiffModal(String(targetRecord.sourceCode ?? ''),String(currentRecord.sourceCode ?? ''),String(targetRecord.id),String(currentRecord.id));} catch (err) {removeLoadingOverlay();showError(err.message);}}/** 更新加载提示文字 */function updateLoadingMessage(overlay, message) {const textEl = overlay.querySelector('div > div:last-child');if (textEl) textEl.textContent = message;}/** 显示错误提示 */function showError(message) {const dark = isDarkMode();const toast = document.createElement('div');toast.style.cssText = `position: fixed; top: 20px; left: 50%; transform: translateX(-50%);z-index: 200000; background: ${dark ? '#3d1a1a' : '#ffeef0'};color: ${dark ? '#f85149' : '#cb2431'}; padding: 12px 24px;border-radius: 8px; font-size: 14px; box-shadow: 0 4px 16px rgba(0,0,0,0.2);border: 1px solid ${dark ? '#f8514940' : '#cb243140'};max-width: 480px; text-align: center;`;toast.textContent = `❌ ${message}`;document.body.appendChild(toast);setTimeout(() => {toast.style.transition = 'opacity 0.3s';toast.style.opacity = '0';setTimeout(() => toast.remove(), 300);}, 4000);}// ======================== 按钮注入 ========================/** 注入对比按钮到页面 */function injectCompareButton() {// 避免重复注入if (document.getElementById('lg-diff-compare-btn')) return;const recordId = getRecordIdFromUrl();if (!recordId) return;// 查找合适的插入位置// 尝试多种选择器以适配不同版本的洛谷页面const insertTargets = [// 操作栏按钮区域'.header-actions','.operation-panel','.record-operations',// 代码区域旁'.markdown-renderer',// 通用信息区域'.card','.main-container',// 更通用的选择器'main','#main-content','.content',];let targetEl = null;for (const selector of insertTargets) {targetEl = document.querySelector(selector);if (targetEl) break;}// 如果找不到特定容器,尝试在页面顶部创建浮动按钮const btn = document.createElement('button');btn.id = 'lg-diff-compare-btn';btn.textContent = '⇄ 对比代码';btn.title = '与同题上一次提交进行代码对比';const dark = isDarkMode();btn.style.cssText = `position: fixed;bottom: 24px;right: 24px;z-index: 99999;padding: 12px 20px;border: none;border-radius: 24px;background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);color: #ffffff;font-size: 15px;font-weight: 600;cursor: pointer;box-shadow: 0 4px 16px rgba(102, 126, 234, 0.4);transition: all 0.2s ease;letter-spacing: 0.5px;`;// 悬停效果btn.addEventListener('mouseenter', () => {btn.style.transform = 'scale(1.05)';btn.style.boxShadow = '0 6px 24px rgba(102, 126, 234, 0.6)';});btn.addEventListener('mouseleave', () => {btn.style.transform = 'scale(1)';btn.style.boxShadow = '0 4px 16px rgba(102, 126, 234, 0.4)';});btn.addEventListener('click', async () => {btn.style.pointerEvents = 'none';btn.style.opacity = '0.6';try {await runCompare(recordId, null);} finally {btn.style.pointerEvents = 'auto';btn.style.opacity = '1';}});document.body.appendChild(btn);// 同时尝试在页面内注入一个次要按钮injectInlineButton(recordId);}/** 在页面内注入行内对比按钮 */function injectInlineButton(recordId) {// 尝试在代码块上方或操作区域添加按钮const codeBlock = document.querySelector('pre') || document.querySelector('code');if (!codeBlock) return;const container = document.createElement('div');container.style.cssText = `display: flex; gap: 8px; margin: 8px 0; align-items: center;`;const inlineBtn = document.createElement('button');inlineBtn.className = 'lg-diff-inline-btn';inlineBtn.textContent = '⇄ 与上次提交对比';inlineBtn.style.cssText = `padding: 6px 16px; border: 1px solid #667eea; border-radius: 6px;background: transparent; color: #667eea; font-size: 13px;cursor: pointer; transition: all 0.2s;`;inlineBtn.addEventListener('mouseenter', () => {inlineBtn.style.background = '#667eea';inlineBtn.style.color = '#fff';});inlineBtn.addEventListener('mouseleave', () => {inlineBtn.style.background = 'transparent';inlineBtn.style.color = '#667eea';});inlineBtn.addEventListener('click', async () => {inlineBtn.style.pointerEvents = 'none';try {await runCompare(recordId, null);} finally {inlineBtn.style.pointerEvents = 'auto';}});const customBtn = document.createElement('button');customBtn.className = 'lg-diff-inline-btn';customBtn.textContent = '⇄ 对比指定提交';customBtn.style.cssText = `padding: 6px 16px; border: 1px solid #8b5cf6; border-radius: 6px;background: transparent; color: #8b5cf6; font-size: 13px;cursor: pointer; transition: all 0.2s;`;customBtn.addEventListener('mouseenter', () => {customBtn.style.background = '#8b5cf6';customBtn.style.color = '#fff';});customBtn.addEventListener('mouseleave', () => {customBtn.style.background = 'transparent';customBtn.style.color = '#8b5cf6';});customBtn.addEventListener('click', () => {promptCustomCompare(recordId);});container.appendChild(inlineBtn);container.appendChild(customBtn);// 插入到代码块之前const preParent = codeBlock.closest('pre') || codeBlock.parentElement;if (preParent && preParent.parentElement) {preParent.parentElement.insertBefore(container, preParent);}}// ======================== 样式注入 ========================function injectStyles() {GM_addStyle(`/* 旋转动画 */@keyframes lg-diff-spin {to { transform: rotate(360deg); }}/* 模态框遮罩 */#lg-diff-modal-overlay,#lg-diff-custom-dialog {position: fixed;top: 0; left: 0; right: 0; bottom: 0;z-index: 150000;display: flex;align-items: center;justify-content: center;background: rgba(0, 0, 0, 0.5);}/* 模态框 */.lg-diff-modal {width: 90vw;max-width: 960px;max-height: 85vh;border-radius: 16px;overflow: hidden;display: flex;flex-direction: column;box-shadow: 0 16px 64px rgba(0, 0, 0, 0.3);}.lg-diff-modal.lg-diff-light {background: #ffffff;}.lg-diff-modal.lg-diff-dark {background: #161b22;}/* 头部 */.lg-diff-header {display: flex;align-items: center;gap: 16px;padding: 16px 24px;border-bottom: 1px solid;}.lg-diff-light .lg-diff-header {border-color: #e1e4e8;background: #f6f8fa;}.lg-diff-dark .lg-diff-header {border-color: #30363d;background: #0d1117;}.lg-diff-title {font-size: 18px;font-weight: 700;display: flex;align-items: center;gap: 8px;}.lg-diff-light .lg-diff-title { color: #24292e; }.lg-diff-dark .lg-diff-title { color: #e6edf3; }.lg-diff-title-icon {font-size: 20px;}.lg-diff-ids {display: flex;align-items: center;gap: 8px;font-size: 14px;}.lg-diff-record-link {text-decoration: none;font-weight: 600;padding: 2px 8px;border-radius: 4px;transition: opacity 0.2s;}.lg-diff-record-link:hover { opacity: 0.8; }.lg-diff-record-link.old {color: #cb2431;background: #ffeef0;}.lg-diff-dark .lg-diff-record-link.old {color: #f85149;background: #3d1a1a;}.lg-diff-record-link.new {color: #22863a;background: #e6ffed;}.lg-diff-dark .lg-diff-record-link.new {color: #3fb950;background: #1b3a1f;}.lg-diff-arrow {color: #959da5;font-weight: 700;}.lg-diff-stats {margin-left: auto;display: flex;gap: 12px;font-size: 13px;font-weight: 600;}.lg-diff-stat-added { color: #22863a; }.lg-diff-stat-removed { color: #cb2431; }.lg-diff-dark .lg-diff-stat-added { color: #3fb950; }.lg-diff-dark .lg-diff-stat-removed { color: #f85149; }.lg-diff-close {width: 32px; height: 32px;border: none; border-radius: 8px;cursor: pointer; font-size: 18px;display: flex; align-items: center; justify-content: center;transition: background 0.2s;}.lg-diff-light .lg-diff-close {background: #f0f0f0; color: #586069;}.lg-diff-light .lg-diff-close:hover {background: #d0d0d0;}.lg-diff-dark .lg-diff-close {background: #21262d; color: #8b949e;}.lg-diff-dark .lg-diff-close:hover {background: #30363d;}/* 代码区域 */.lg-diff-body {flex: 1;overflow: auto;padding: 0;}.lg-diff-code {font-family: 'Cascadia Code', 'Fira Code', 'JetBrains Mono', 'Consolas', monospace;font-size: 13px;line-height: 1.5;white-space: pre;}/* 代码行 */.lg-diff-line {display: flex;min-height: 0;}.lg-diff-ln-old,.lg-diff-ln-new {display: inline-block;width: 48px;min-width: 48px;text-align: right;padding-right: 10px;user-select: none;font-size: 12px;line-height: 1.5;}.lg-diff-marker {display: inline-block;width: 20px;min-width: 20px;text-align: center;user-select: none;font-weight: 700;}.lg-diff-content {flex: 1;white-space: pre;padding-left: 8px;}/* 未变更行 */.lg-diff-unchanged {background: transparent;}.lg-diff-light .lg-diff-unchanged .lg-diff-ln-old,.lg-diff-light .lg-diff-unchanged .lg-diff-ln-new {color: #959da5;background: #f6f8fa;}.lg-diff-light .lg-diff-unchanged .lg-diff-content {color: #24292e;}.lg-diff-dark .lg-diff-unchanged .lg-diff-ln-old,.lg-diff-dark .lg-diff-unchanged .lg-diff-ln-new {color: #484f58;background: #161b22;}.lg-diff-dark .lg-diff-unchanged .lg-diff-content {color: #e6edf3;}/* 删除行 */.lg-diff-removed {background: #ffeef0;}.lg-diff-light .lg-diff-removed .lg-diff-ln-old {color: #cb2431;background: #f8d7da;}.lg-diff-light .lg-diff-removed .lg-diff-ln-new {background: #ffeef0;}.lg-diff-light .lg-diff-removed .lg-diff-marker {color: #cb2431;}.lg-diff-light .lg-diff-removed .lg-diff-content {color: #24292e;}.lg-diff-dark .lg-diff-removed {background: #3d1a1a;}.lg-diff-dark .lg-diff-removed .lg-diff-ln-old {color: #f85149;background: #4d2020;}.lg-diff-dark .lg-diff-removed .lg-diff-ln-new {background: #3d1a1a;}.lg-diff-dark .lg-diff-removed .lg-diff-marker {color: #f85149;}.lg-diff-dark .lg-diff-removed .lg-diff-content {color: #e6edf3;}/* 新增行 */.lg-diff-added {background: #e6ffed;}.lg-diff-light .lg-diff-added .lg-diff-ln-new {color: #22863a;background: #cdffd8;}.lg-diff-light .lg-diff-added .lg-diff-ln-old {background: #e6ffed;}.lg-diff-light .lg-diff-added .lg-diff-marker {color: #22863a;}.lg-diff-light .lg-diff-added .lg-diff-content {color: #24292e;}.lg-diff-dark .lg-diff-added {background: #1b3a1f;}.lg-diff-dark .lg-diff-added .lg-diff-ln-new {color: #3fb950;background: #245028;}.lg-diff-dark .lg-diff-added .lg-diff-ln-old {background: #1b3a1f;}.lg-diff-dark .lg-diff-added .lg-diff-marker {color: #3fb950;}.lg-diff-dark .lg-diff-added .lg-diff-content {color: #e6edf3;}/* 设置工具栏 */.lg-diff-settings-bar {display: flex;align-items: center;gap: 8px;padding: 8px 24px;border-top: 1px solid;flex-shrink: 0;}.lg-diff-light .lg-diff-settings-bar {border-color: #e1e4e8;background: #ffffff;}.lg-diff-dark .lg-diff-settings-bar {border-color: #30363d;background: #161b22;}.lg-diff-settings-label {font-size: 12px;font-weight: 600;user-select: none;}.lg-diff-light .lg-diff-settings-label { color: #586069; }.lg-diff-dark .lg-diff-settings-label { color: #8b949e; }.lg-diff-settings-btn {width: 28px;height: 28px;border: 1px solid;border-radius: 6px;background: transparent;cursor: pointer;font-size: 13px;font-weight: 700;display: flex;align-items: center;justify-content: center;transition: all 0.15s;padding: 0;line-height: 1;}.lg-diff-light .lg-diff-settings-btn {border-color: #d1d5da;color: #586069;}.lg-diff-light .lg-diff-settings-btn:hover {background: #f3f4f6;border-color: #667eea;color: #667eea;}.lg-diff-dark .lg-diff-settings-btn {border-color: #30363d;color: #8b949e;}.lg-diff-dark .lg-diff-settings-btn:hover {background: #21262d;border-color: #667eea;color: #667eea;}.lg-diff-settings-btn:active {transform: scale(0.92);}.lg-diff-settings-value {font-size: 12px;min-width: 36px;text-align: center;font-variant-numeric: tabular-nums;user-select: none;}.lg-diff-light .lg-diff-settings-value { color: #24292e; }.lg-diff-dark .lg-diff-settings-value { color: #e6edf3; }.lg-diff-settings-divider {color: #d1d5da;user-select: none;font-size: 12px;}.lg-diff-dark .lg-diff-settings-divider {color: #30363d;}/* 底部 */.lg-diff-footer {display: flex;justify-content: flex-end;gap: 12px;padding: 16px 24px;border-top: 1px solid;}.lg-diff-light .lg-diff-footer {border-color: #e1e4e8;background: #f6f8fa;}.lg-diff-dark .lg-diff-footer {border-color: #30363d;background: #0d1117;}/* 按钮 */.lg-diff-btn {padding: 8px 20px;border-radius: 8px;font-size: 14px;font-weight: 600;cursor: pointer;transition: all 0.2s;border: none;}.lg-diff-btn-primary {background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);color: #ffffff;}.lg-diff-btn-primary:hover {opacity: 0.9;transform: translateY(-1px);}.lg-diff-btn-secondary {background: transparent;border: 1px solid;}.lg-diff-light .lg-diff-btn-secondary {border-color: #d1d5da;color: #586069;}.lg-diff-light .lg-diff-btn-secondary:hover {background: #f3f4f6;}.lg-diff-dark .lg-diff-btn-secondary {border-color: #30363d;color: #8b949e;}.lg-diff-dark .lg-diff-btn-secondary:hover {background: #21262d;}`);}// ======================== 初始化 ========================function init() {injectStyles();// 使用 MutationObserver 监听页面加载const observer = new MutationObserver((mutations, obs) => {const recordId = getRecordIdFromUrl();if (!recordId) return;// 检查页面是否已充分加载const hasContent = document.querySelector('pre') || document.querySelector('code') || document.querySelector('.markdown-renderer');if (hasContent || document.readyState === 'complete') {injectCompareButton();// 不停止观察,因为页面可能会动态更新}});observer.observe(document.body, {childList: true,subtree: true,});// 也在 DOMContentLoaded 时尝试注入if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', () => {setTimeout(injectCompareButton, 1000);});} else {setTimeout(injectCompareButton, 1000);}// 监听主题切换const themeObserver = new MutationObserver(() => {// 主题切换时移除旧按钮并重新注入const btn = document.getElementById('lg-diff-compare-btn');if (btn) {btn.remove();injectCompareButton();}});themeObserver.observe(document.documentElement, {attributes: true,attributeFilter: ['data-theme'],});}// 启动if (document.body) {init();} else {document.addEventListener('DOMContentLoaded', init);}})();``````:::12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522本插件是用 AI 做的,用于实现类似于 CF 的代码对比功能,实测在洛谷、CF 上使用时较为稳定,在 AT 使用时无法抓取提交代码(因此在 AT 上无法使用有关提交记录的功能)。请先[安装篡改猴](https://www.tampermonkey.net)再使用。(由于代码 $100\%$ 由 AI 生成且涉及 API 调用,没敢放在公开推荐的“休闲·娱乐”或“科技·工程”区。)使用提示:1. CF “与上次提交记录对比”最多只抓取自己(其他人的会失败,请自行想办法解决)前 $2000$ 个提交,如果你确定有个不在前 $2000$ 个提交之内的提交,请自行想办法找到那个提交;2. 受篇幅局限,此处没有实现“格式化代码”功能,如果想要格式化代码,可以自行将两份代码复制下来,自行格式化后用“两份代码对比”功能进行对比;3. 插件按钮可能挡住信息,如 AT 右下角的时钟,你可以拖动按钮到合适的位置。4. 本插件并没有获得任何 OJ 的认可(虽然调用 API 次数较少),请不要**滥**用(我认为正常使用应该没问题)。:::info[代码(提示:目前 $2000$ 多行,约 $100$ KB)]```js// ==UserScript==// @name OJ 代码对比 (Luogu/AtCoder/Codeforces)// @namespace oj-code-diff// @version 2.2.1// @description 洛谷/Codeforces 提交记录代码对比,AtCoder 手动输入对比。支持并列视图、折叠未变更行、复制代码// @author useluogu// @homepageURL https://github.com/useluogu/Code-Comparison-Plugin// @updateURL https://raw.githubusercontent.com/useluogu/Code-Comparison-Plugin/main/oj-code-diff.user.js// @downloadURL https://raw.githubusercontent.com/useluogu/Code-Comparison-Plugin/main/oj-code-diff.user.js// @match https://www.luogu.com.cn/*// @match https://atcoder.jp/contests/*// @match https://codeforces.com/*/submission/*// @match https://codeforces.com/contest/*// @match https://codeforces.com/problemset/*// @grant GM_addStyle// @grant GM_xmlhttpRequest// @connect atcoder.jp// @connect codeforces.com// @run-at document-idle// @license MIT// ==/UserScript==(function () {'use strict';const _unsafeWindow = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window;// ======================== 平台检测 ========================const PLATFORMS = {LUOGU: { id: 'luogu', name: '洛谷', base: 'https://www.luogu.com.cn' },ATCODER: { id: 'atcoder', name: 'AtCoder', base: 'https://atcoder.jp' },CF: { id: 'cf', name: 'Codeforces', base: 'https://codeforces.com' },};/** 检测当前平台 */function detectPlatform() {const h = window.location.hostname;if (h === 'www.luogu.com.cn') return PLATFORMS.LUOGU;if (h === 'atcoder.jp') return PLATFORMS.ATCODER;if (h.endsWith('codeforces.com')) return PLATFORMS.CF;return null;}const CURRENT_PLATFORM = detectPlatform();// ======================== 常量配置 ========================const COLORS = {light: {addedBg: '#e6ffed', addedLineNum: '#22863a', addedText: '#24292e',removedBg: '#ffeef0', removedLineNum: '#cb2431', removedText: '#24292e',unchangedBg: '#ffffff', unchangedText: '#24292e',lineNumText: '#959da5', lineNumBg: '#f6f8fa', border: '#e1e4e8',modalBg: '#ffffff', overlayBg: 'rgba(0, 0, 0, 0.5)',textPrimary: '#24292e', textSecondary: '#586069', bgSecondary: '#f6f8fa',inputBg: '#ffffff', inputBorder: '#e1e4e8',btnSecBorder: '#d1d5da', btnSecColor: '#586069', btnSecHover: '#f3f4f6',sliderTrack: '#d1d5da',},dark: {addedBg: '#1b3a1f', addedLineNum: '#3fb950', addedText: '#e6edf3',removedBg: '#3d1a1a', removedLineNum: '#f85149', removedText: '#e6edf3',unchangedBg: '#0d1117', unchangedText: '#e6edf3',lineNumText: '#484f58', lineNumBg: '#161b22', border: '#30363d',modalBg: '#161b22', overlayBg: 'rgba(0, 0, 0, 0.7)',textPrimary: '#e6edf3', textSecondary: '#8b949e', bgSecondary: '#0d1117',inputBg: '#0d1117', inputBorder: '#30363d',btnSecBorder: '#30363d', btnSecColor: '#8b949e', btnSecHover: '#21262d',sliderTrack: '#30363d',},};// ======================== 模态框导航堆栈 ========================const modalStack = [];function pushAndHide(el) {if (!el) return;el.style.display = 'none';modalStack.push(el);}function popAndRestore() {if (modalStack.length === 0) return false;const prev = modalStack.pop();prev.style.display = '';const codeArea = prev.querySelector('.oj-diff-code');if (codeArea) codeArea.focus();return true;}// ======================== 用户设置 ========================const SETTINGS_KEY = 'oj-diff-settings';const DEFAULT_SETTINGS = {fontSize: 13,lineHeight: 1.5,tabSize: 4,themeMode: 'auto',collapseUnchanged: true,viewMode: 'unified', // 'unified' | 'split'};function loadSettings() {try {const raw = localStorage.getItem(SETTINGS_KEY);if (raw) return { ...DEFAULT_SETTINGS, ...JSON.parse(raw) };} catch (e) {console.warn('[OJ代码对比] 读取设置失败:', e);}return { ...DEFAULT_SETTINGS };}function saveSettings(settings) {try {localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));} catch (e) {console.warn('[OJ代码对比] 保存设置失败:', e);}}function applyCodeSettings(codeEl, settings) {if (!codeEl) return;const fs = settings.fontSize;const lhPx = (fs * settings.lineHeight).toFixed(1) + 'px';codeEl.style.fontSize = fs + 'px';codeEl.style.lineHeight = lhPx;codeEl.style.tabSize = String(settings.tabSize);codeEl.style.MozTabSize = String(settings.tabSize);const lnFs = Math.max(fs - 1, 9) + 'px';codeEl.querySelectorAll('.oj-diff-ln-old, .oj-diff-ln-new').forEach(el => {el.style.fontSize = lnFs;el.style.lineHeight = lhPx;});}// ======================== 主题 ========================function isDarkMode(themeMode) {const mode = themeMode || loadSettings().themeMode;if (mode === 'dark') return true;if (mode === 'light') return false;// auto:跟随各平台或系统if (CURRENT_PLATFORM && CURRENT_PLATFORM.id === 'luogu') {return (document.documentElement.getAttribute('data-theme') === 'dark' ||document.body?.getAttribute('data-theme') === 'dark' ||window.matchMedia('(prefers-color-scheme: dark)').matches);}return window.matchMedia('(prefers-color-scheme: dark)').matches;}function getColors(dark) {return dark ? COLORS.dark : COLORS.light;}// ======================== 工具函数 ========================function escapeHtml(str) {if (str === null || str === undefined) return '';return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');}/** 让浮动按钮可拖动(mousedown → mousemove 拖动,>5px 视为拖动不触发点击) */function makeDraggable(btn) {let dragging = false, dragStartX, dragStartY;btn.addEventListener('mousedown', (e) => {dragging = false;dragStartX = e.clientX; dragStartY = e.clientY;const openMenu = document.getElementById('oj-diff-float-menu') || document.getElementById('oj-diff-universal-menu');btn.style.cursor = 'grabbing';btn.style.transition = 'none';const accDx = btn._dx || 0, accDy = btn._dy || 0;let dx = accDx, dy = accDy;const onMove = (ev) => {dx = accDx + (ev.clientX - dragStartX);dy = accDy + (ev.clientY - dragStartY);if (Math.abs(dx - accDx) > 5 || Math.abs(dy - accDy) > 5) dragging = true;// 用 transform 移动——不影响布局尺寸btn.style.transform = `translate(${dx}px, ${dy}px)`;// 边界约束(使用 documentElement.clientWidth/Height 排除滚动条区域)const r = btn.getBoundingClientRect();const vw = document.documentElement.clientWidth;const vh = document.documentElement.clientHeight;let cx = 0, cy = 0;if (r.left < 0) cx = -r.left;else if (r.right > vw) cx = vw - r.right;if (r.top < 0) cy = -r.top;else if (r.bottom > vh) cy = vh - r.bottom;if (cx || cy) {dx += cx; dy += cy;btn.style.transform = `translate(${dx}px, ${dy}px)`;}// 剩余 transform 偏移量用于下次拖动btn._dx = dx; btn._dy = dy;// 菜单实时跟随if (openMenu) {const mw = openMenu.offsetWidth || 220;const mh = openMenu.offsetHeight || 200;const br = btn.getBoundingClientRect();let ml = br.right - mw;if (ml < 4) ml = Math.max(4, br.left);if (ml + mw > vw - 4) ml = vw - mw - 4;let mt;if (br.top > mh + 12) { mt = br.top - 8 - mh; }else { mt = br.bottom + 8; }mt = Math.max(4, Math.min(mt, vh - mh - 4));openMenu.style.left = ml + 'px';openMenu.style.top = mt + 'px';}};const onUp = () => {document.removeEventListener('mousemove', onMove);document.removeEventListener('mouseup', onUp);btn.style.cursor = 'pointer';btn.style.transition = 'all 0.2s ease';if (dragging) {// 保持 transform 偏移,不转成 bottom/right(避免定位冲突压窄按钮)const noClick = (ce) => { ce.stopImmediatePropagation(); btn.removeEventListener('click', noClick, true); };btn.addEventListener('click', noClick, true);}};document.addEventListener('mousemove', onMove);document.addEventListener('mouseup', onUp);});}/*** GM_xmlhttpRequest 封装(用于跨域请求)* 同源请求优先用 fetch(支持 cookies),跨域回退到 GM_xmlhttpRequest*/function gmFetch(url, options) {options = options || {};// 判断是否同源let isSameOrigin;try {const urlObj = new URL(url, location.href);isSameOrigin = urlObj.origin === location.origin;} catch (e) {isSameOrigin = false;}if (isSameOrigin && typeof fetch !== 'undefined') {// 同源请求使用原生 fetch(自动带 cookies)const headers = options.headers || {};headers.Accept = headers.Accept || 'text/html,application/json,*/*';return fetch(url, { method: options.method || 'GET', headers, credentials: 'same-origin' }).then(r => {if (!r.ok) throw new Error(`HTTP ${r.status}: ${r.statusText}`);return r.text();});}// 跨域请求:使用 GM_xmlhttpRequestreturn new Promise((resolve, reject) => {if (typeof GM_xmlhttpRequest === 'undefined') {reject(new Error('GM_xmlhttpRequest 不可用(请确保脚本有 @grant GM_xmlhttpRequest)'));return;}GM_xmlhttpRequest({method: options.method || 'GET',url: url,headers: options.headers || {},onload: (response) => {resolve(response.responseText);},onerror: (error) => {reject(new Error(`GM_xmlhttpRequest 失败: ${error.message || '未知错误'}`));},ontimeout: () => {reject(new Error('GM_xmlhttpRequest 请求超时'));},});});}/*** 解析 HTML 字符串为 DOM Document(用于从页面中提取数据)*/function parseHtml(htmlStr) {const parser = new DOMParser();return parser.parseFromString(htmlStr, 'text/html');}// ======================== 各平台 Adapter ========================// ---------- Luogu Adapter ----------const LuoguAdapter = {platform: PLATFORMS.LUOGU,/** 从 URL 中提取记录 ID */getRecordIdFromUrl() {const match = window.location.pathname.match(/\/record\/(\d+)/);return match ? match[1] : null;},isRecordPage() {return /^\/record\/\d+/.test(window.location.pathname);},async fetchRecordDetail(recordId) {const base = this.platform.base;const url = `${base}/record/${recordId}`;const sep = url.includes('?') ? '&' : '?';const jsonUrl = `${url}${sep}_contentOnly=1`;const text = await gmFetch(jsonUrl, {headers: { Accept: 'application/json' }});const response = JSON.parse(text);if (response.code !== undefined && response.code !== 200)throw new Error(`洛谷返回错误码: ${response.code}`);const data = response.currentData || response.data || response.record || response;// 验证返回的记录 ID 是否与请求一致(防止 Luogu 缓存/重定向导致返回错误记录)if (data.record && String(data.record.id) !== String(recordId)) {console.warn(`[Luogu] 返回记录 ID(${data.record.id}) 与请求 ID(${recordId}) 不一致,重新获取`);// 强制再请求一次const text2 = await gmFetch(jsonUrl + '&_t=' + Date.now(), {headers: { Accept: 'application/json' }});const response2 = JSON.parse(text2);const data2 = response2.currentData || response2.data || response2.record || response2;if (data2.record && String(data2.record.id) === String(recordId)) {return data2.record;}throw new Error(`洛谷 API 返回了提交 #${data.record?.id}(而非 #${recordId}),可能因缓存导致`);}if (!data.record) throw new Error('无法获取记录信息(response 中缺少 record 字段)');return data.record;},async fetchRecordList(params) {const base = this.platform.base;const query = new URLSearchParams();if (params.pid) query.set('pid', params.pid);if (params.user) query.set('user', params.user);if (params.page) query.set('page', String(params.page));query.set('_contentOnly', '1');const url = `${base}/record/list?${query.toString()}`;const text = await gmFetch(url, {headers: { Accept: 'application/json' }});const response = JSON.parse(text);const data = response.currentData || response.data || response;let records = data.records;if (!records) return [];if (Array.isArray(records)) return records;if (records.result) return records.result;if (records.records) return records.records;if (records.values) return records.values;if (records.data) return records.data;return [];},async findPrevRecord(currentRecordId, currentRecord) {// 从当前记录对象提取题目 ID 和用户 IDconst pid = this.getProblemId(currentRecord);const uid = this.getUserId(currentRecord);if (!pid || !uid) throw new Error('无法获取当前提交的题目/用户信息');for (let page = 1; page <= 5; page++) {const records = await this.fetchRecordList({ pid, user: String(uid), page });if (!records || records.length === 0) break;// 在当前页找当前记录const idx = records.findIndex(r => String(r.id) === String(currentRecordId));if (idx !== -1) {// 当前页找到——取后一个(更旧的)if (idx + 1 < records.length) return records[idx + 1];// 当前记录是此页最后一个,继续下一页continue;}}throw new Error('未找到该题目的上一次提交记录(当前记录可能是最新的一次,或已超出翻页范围)');},/** 获取当前页面已有的 record 数据(避免重复请求) */getPageData() {return _unsafeWindow._feInjection?.currentData?.record || null;},/** 构建记录 URL */recordUrl(recordId) {return `${this.platform.base}/record/${recordId}`;},/** 从 record 对象提取 sourceCode */getSourceCode(record) {return record.sourceCode ?? '';},/** 从 record 对象提取 problem ID */getProblemId(record) {const p = record.problem;return p?.pid || p?.id || p?.problemId || (typeof p === 'string' ? p : null);},/** 从 record 对象提取 user ID */getUserId(record) {return record.user?.uid || record.uid || null;},};// ---------- AtCoder Adapter(精简版:仅支持手动输入代码对比) ----------const AtCoderAdapter = {platform: PLATFORMS.ATCODER,getRecordIdFromUrl() {const m = window.location.pathname.match(/\/submissions\/(\d+)/);return m ? m[1] : null;},isRecordPage() {return /\/submissions\/\d+/.test(window.location.pathname);},/** 仅读取当前页 DOM 中的代码;非当前页抛错 */async fetchRecordDetail(submissionId) {const curId = this.getRecordIdFromUrl();if (curId && String(curId) === String(submissionId)) {const el = document.getElementById('program-source-text');if (el) return { sourceCode: el.textContent || '', id: submissionId };}throw new Error('AtCoder 仅支持对当前页提交操作,请使用"✏️两份代码对比"手动输入');},findPrevRecord() {throw new Error('AtCoder 暂不支持此功能,请使用"✏️两份代码对比"手动输入');},getPageData() {const el = document.getElementById('program-source-text');return el ? { sourceCode: el.textContent || '', id: this.getRecordIdFromUrl() } : null;},recordUrl(submissionId) {const slug = (window.location.pathname.match(/\/contests\/([^/]+)/) || [])[1] || '';return slug ? `https://atcoder.jp/contests/${slug}/submissions/${submissionId}` : '#';},getSourceCode(record) { return record.sourceCode ?? ''; },getProblemId(record) { return record.problemId || null; },getUserId(record) { return record.userId || null; },};// ---------- Codeforces Adapter ----------const CfAdapter = {platform: PLATFORMS.CF,/** 从 URL 提取 submission ID */getRecordIdFromUrl() {// /contest/12345/submission/67890 or /submission/67890const match = window.location.pathname.match(/\/(?:submission|submissions)\/(\d+)/);return match ? match[1] : null;},isRecordPage() {return /\/(?:submission|submissions)\/\d+/.test(window.location.pathname);},/*** 获取提交详情。** 流程:* 1. 优先用 hint.contestId(findPrevRecord 已知)构建 URL;* 否则用 CF API 查该 submissionId 的 contestId,再构建 URL。* 这样保证每次都请求正确的页面,不依赖当前浏览器 URL。* 2. 拿到 HTML 后从 DOM 提取 sourceCode、handle、problemIndex。** 返回 { sourceCode, contestId, problemIndex, handle, id }*/async fetchRecordDetail(submissionId, hint) {// --- 第一步:确定正确的 contestId,再构建 URL ---let contestId = hint?.contestId || '';let handle = '';let problemIndex = '';if (!contestId) {// 用当前登录用户 handle 调 API,找到该 submissionId 的 contestIdconst cfHandle = _unsafeWindow.CF?.currentUserHandle ||document.querySelector('a.rated-user, a[href*="/profile/"]')?.textContent?.trim() ||'';if (cfHandle) {try {const apiUrl = `https://codeforces.com/api/user.status?handle=${encodeURIComponent(cfHandle)}&from=1&count=500`;const apiText = await gmFetch(apiUrl);const apiData = JSON.parse(apiText);if (apiData.status === 'OK') {const sub = apiData.result.find(s => s.id === Number(submissionId));if (sub) {contestId = String(sub.contestId || '');problemIndex = sub.problem.index || '';handle = sub.author.members[0]?.handle || cfHandle;}}} catch (e) {console.warn('[CF] API 查 contestId 失败,将用无 contest 路径:', e);}}// 如果 API 没命中,只有当 submissionId 就是当前页的提交时才用当前页 URL 里的 contestIdif (!contestId) {const curPageSubId = window.location.pathname.match(/\/submission\/(\d+)/)?.[1];if (curPageSubId && curPageSubId === String(submissionId)) {contestId = window.location.pathname.match(/\/contest\/(\d+)/)?.[1] || '';}// 否则不 fallback,用无 contest 路径(/submission/id)}}// --- 第二步:用准确的 contestId 拉页面 ---const pageUrl = this.buildSubmissionUrl(submissionId, contestId);const html = await gmFetch(pageUrl);const doc = parseHtml(html);// 提取源代码const sourceEl = doc.getElementById('program-source-text');if (!sourceEl) throw new Error(`CF 提交 #${submissionId} 的代码不可见(可能需要登录或不是自己的提交)`);const sourceCode = sourceEl.textContent || '';if (!sourceCode.trim()) throw new Error(`CF 提交 #${submissionId} 的代码为空(可能被折叠或需要登录查看)`);// --- 第三步:从页面 DOM 补全仍缺的 handle / problemIndex ---if (!handle) {const ratedLinks = doc.querySelectorAll('a[href*="/profile/"]');for (const link of ratedLinks) {const t = link.textContent.trim();if (t && !t.includes(' ')) { handle = t; break; }}}if (!problemIndex) {const titleEl = doc.querySelector('title');if (titleEl) {const m = titleEl.textContent.match(/Problem\s+([A-Z]\d*)/i);if (m) problemIndex = m[1].toUpperCase();}}if (!problemIndex) {const subInfoRows = doc.querySelectorAll('.info-table tr, table.table tr');for (const row of subInfoRows) {const cells = row.querySelectorAll('td');if (cells.length >= 2 && cells[0].textContent.trim().toLowerCase().includes('problem')) {const link = cells[1].querySelector('a');if (link) {const m = (link.textContent || link.href).match(/\/([A-Z]\d*)(?:[/?#]|$)/i);if (m) { problemIndex = m[1].toUpperCase(); break; }}}}}return { sourceCode, contestId, problemIndex, handle, id: submissionId };},/*** 构建 submission 详情页 URL。* 必须传入 contestId 才能访问正确页面;无 contestId 时用无 contest 路径(可能 404)。*/buildSubmissionUrl(submissionId, contestId) {if (contestId) {return `https://codeforces.com/contest/${contestId}/submission/${submissionId}`;}return `https://codeforces.com/submission/${submissionId}`;},/*** 通过 CF API 查找同一人、同一题的上一次提交。*/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('无法识别当前提交的题目信息,无法查找上一次提交');}// 分页搜索:最多 2 页(每页 1000 条),覆盖约 2000 条提交记录const PAGE_SIZE = 1000;const MAX_PAGES = 2;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;// 从当前提交往后(更早的提交)找同一题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} 的上一次提交`);},getPageData() {// CF 无注入数据return null;},recordUrl(submissionId, record) {// 如果有 record 对象,用其中的 contestId 构建精确 URLconst cid = record?.contestId;return this.buildSubmissionUrl(submissionId, cid);},getSourceCode(record) {return record.sourceCode ?? '';},getProblemId(record) {if (record.contestId && record.problemIndex) {return `${record.contestId}${record.problemIndex}`;}return null;},getUserId(record) {return record.handle || null;},};// 根据 URL 选择 adapterfunction getAdapter(platform) {platform = platform || CURRENT_PLATFORM;if (platform && platform.id === 'luogu') return LuoguAdapter;if (platform && platform.id === 'atcoder') return AtCoderAdapter;if (platform && platform.id === 'cf') return CfAdapter;return LuoguAdapter; // default}const ADAPTER = getAdapter();// ======================== Diff 算法 ========================function lineDiff(oldLines, newLines) {const m = oldLines.length;const n = newLines.length;if (m * n > 9000000) {console.warn('[OJ代码对比] 文件过大,使用简化 diff');return [...oldLines.map(c => ({ type: 'removed', content: c })),...newLines.map(c => ({ type: 'added', content: c })),];}const dp = Array.from({ length: m + 1 }, () => new Int32Array(n + 1));for (let i = 1; i <= m; i++) {for (let j = 1; j <= n; j++) {dp[i][j] = oldLines[i - 1] === newLines[j - 1]? dp[i - 1][j - 1] + 1: Math.max(dp[i - 1][j], dp[i][j - 1]);}}let i = m, j = n;const raw = [];while (i > 0 || j > 0) {if (i > 0 && j > 0 && oldLines[i - 1] === newLines[j - 1]) {raw.push({ type: 'unchanged', content: oldLines[i - 1] });i--; j--;} else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) {raw.push({ type: 'added', content: newLines[j - 1] });j--;} else {raw.push({ type: 'removed', content: oldLines[i - 1] });i--;}}raw.reverse();// 合并连续 removed+added 对const merged = [];let k = 0;while (k < raw.length) {if (raw[k].type === 'removed' &&k + 1 < raw.length &&raw[k + 1].type === 'added') {const rg = [], ag = [];while (k < raw.length &&(raw[k].type === 'removed' || (raw[k].type === 'added' && rg.length > 0))) {if (raw[k].type === 'removed') rg.push(raw[k]);else ag.push(raw[k]);k++;}for (const x of rg) merged.push({ ...x, pairedWithAdd: true });for (const x of ag) merged.push({ ...x, pairedWithRemove: true });} else {merged.push(raw[k++]);}}return merged;}function collapseUnchanged(diffs) {const n = diffs.length;const oldNums = new Int32Array(n);const newNums = new Int32Array(n);let oldNum = 0, newNum = 0;for (let i = 0; i < n; i++) {if (diffs[i].type === 'removed') { oldNum++; newNums[i] = 0; oldNums[i] = oldNum; }else if (diffs[i].type === 'added') { newNum++; oldNums[i] = 0; newNums[i] = newNum; }else { oldNum++; newNum++; oldNums[i] = oldNum; newNums[i] = newNum; }}const result = [];let i = 0;while (i < n) {if (diffs[i].type !== 'unchanged') {result.push(diffs[i]);i++;} else {let start = i;while (i < n && diffs[i].type === 'unchanged') i++;const count = i - start;result.push({type: 'collapsed',count: count,oldStart: oldNums[start],oldEnd: oldNums[i - 1],newStart: newNums[start],newEnd: newNums[i - 1],});}}return result;}// ======================== 代码 HTML 构建 ========================function buildCodeHtml(diffs, showFoldIcons) {const blockInfo = new Map();if (showFoldIcons) {let runStart = -1, runLen = 0;for (let i = 0; i <= diffs.length; i++) {if (i < diffs.length && diffs[i].type === 'unchanged') {if (runLen === 0) runStart = i;runLen++;} else {if (runLen >= 1) {for (let j = runStart; j < runStart + runLen; j++) {blockInfo.set(j, { blockStart: runStart, blockCount: runLen });}}runLen = 0;runStart = -1;}}}let html = '';let oldLineNum = 0;let newLineNum = 0;for (let di = 0; di < diffs.length; di++) {const diff = diffs[di];if (diff.type === 'collapsed') {const hasLineInfo = diff.oldStart != null && diff.oldEnd != null;const oldRange = hasLineInfo? (diff.oldStart === diff.oldEnd ? String(diff.oldStart) : diff.oldStart + '-' + diff.oldEnd): '';const newRange = hasLineInfo? (diff.newStart === diff.newEnd ? String(diff.newStart) : diff.newStart + '-' + diff.newEnd): '';html +='<div class="oj-diff-line oj-diff-collapsed" data-count="' + diff.count + '">' +'<span class="oj-diff-fold-icon-placeholder"></span>' +'<span class="oj-diff-ln-old' + (hasLineInfo ? ' oj-diff-ln-collapsed' : '') + '">' + oldRange + '</span>' +'<span class="oj-diff-ln-new' + (hasLineInfo ? ' oj-diff-ln-collapsed' : '') + '">' + newRange + '</span>' +'<span class="oj-diff-marker oj-diff-marker-empty"></span>' +'<span class="oj-diff-collapsed-btn" title="点击展开">⋯ ' + diff.count + ' 行相同代码' + (hasLineInfo && diff.oldStart !== diff.oldEnd ? '(' + diff.oldStart + '–' + diff.oldEnd + ' 行)' : '') + ' ⋯</span>' +'</div>';if (hasLineInfo) {oldLineNum = diff.oldEnd;newLineNum = diff.newEnd;} else {oldLineNum += diff.count;newLineNum += diff.count;}continue;}if (diff.type === 'unchanged') {oldLineNum++; newLineNum++;const info = blockInfo.get(di);const foldIcon = info? '<span class="oj-diff-fold-icon" data-fold-start="' + info.blockStart + '" data-fold-count="' + info.blockCount + '" title="折叠 ' + info.blockCount + ' 行相同代码">⌃</span>': '<span class="oj-diff-fold-icon-placeholder"></span>';html +='<div class="oj-diff-line oj-diff-unchanged' + (info ? ' oj-diff-unchanged-foldable' : '') + '">' +foldIcon +'<span class="oj-diff-ln-old">' + oldLineNum + '</span>' +'<span class="oj-diff-ln-new">' + newLineNum + '</span>' +'<span class="oj-diff-marker oj-diff-marker-empty"></span>' +'<span class="oj-diff-content">' + escapeHtml(diff.content) + '</span>' +'</div>';} else if (diff.type === 'removed') {oldLineNum++;html +='<div class="oj-diff-line oj-diff-removed">' +'<span class="oj-diff-fold-icon-placeholder"></span>' +'<span class="oj-diff-ln-old">' + oldLineNum + '</span>' +'<span class="oj-diff-ln-new"></span>' +'<span class="oj-diff-marker">-</span>' +'<span class="oj-diff-content">' + escapeHtml(diff.content) + '</span>' +'</div>';} else if (diff.type === 'added') {newLineNum++;html +='<div class="oj-diff-line oj-diff-added">' +'<span class="oj-diff-fold-icon-placeholder"></span>' +'<span class="oj-diff-ln-old"></span>' +'<span class="oj-diff-ln-new">' + newLineNum + '</span>' +'<span class="oj-diff-marker">+</span>' +'<span class="oj-diff-content">' + escapeHtml(diff.content) + '</span>' +'</div>';}}return html;}// ======================== 并列视图 HTML 构建 ========================/*** 将 rawDiffs 转为并列(side-by-side)视图的 HTML。* 左侧显示旧代码(removed + unchanged),右侧显示新代码(added + unchanged)。* removed/added 行对齐:连续的 removed/added 块按行数对齐,短的一侧用空占位行补齐。*/function buildSplitHtml(diffs) {// 先将 diffs 展开为对齐的行对 [{left, right}]// left/right: null(空占位)或 {type, content, lineNum}const pairs = [];let oldNum = 0, newNum = 0;let i = 0;while (i < diffs.length) {const d = diffs[i];if (d.type === 'collapsed') {pairs.push({ type: 'collapsed', data: d });if (d.oldEnd != null) { oldNum = d.oldEnd; newNum = d.newEnd; }else { oldNum += d.count; newNum += d.count; }i++;} else if (d.type === 'unchanged') {oldNum++; newNum++;pairs.push({ type: 'row', left: { type: 'unchanged', content: d.content, lineNum: oldNum }, right: { type: 'unchanged', content: d.content, lineNum: newNum } });i++;} else if (d.type === 'removed' || d.type === 'added') {// 收集连续的 removed / added 块,成对对齐const removedGroup = [], addedGroup = [];while (i < diffs.length && (diffs[i].type === 'removed' || diffs[i].type === 'added')) {if (diffs[i].type === 'removed') removedGroup.push(diffs[i]);else addedGroup.push(diffs[i]);i++;}const maxLen = Math.max(removedGroup.length, addedGroup.length);let lo = oldNum, ln = newNum;for (let j = 0; j < maxLen; j++) {const r = j < removedGroup.length ? removedGroup[j] : null;const a = j < addedGroup.length ? addedGroup[j] : null;if (r) lo++;if (a) ln++;pairs.push({type: 'row',left: r ? { type: 'removed', content: r.content, lineNum: lo } : null,right: a ? { type: 'added', content: a.content, lineNum: ln } : null,});}oldNum = lo; newNum = ln;} else {i++;}}// 渲染 pairs 为 HTML,左右各放入独立列容器(展开行各列独立水平滚动,折叠行左右各占半宽)let leftHtml = '', rightHtml = '';for (const p of pairs) {if (p.type === 'collapsed') {const d = p.data;const oldRange = d.oldStart != null ? (d.oldStart === d.oldEnd ? String(d.oldStart) : d.oldStart + '-' + d.oldEnd) : '';const newRange = d.newStart != null ? (d.newStart === d.newEnd ? String(d.newStart) : d.newStart + '-' + d.newEnd) : '';const label = '⋯ ' + d.count + ' 行相同代码' + (d.oldStart != null && d.oldStart !== d.oldEnd ? '(' + d.oldStart + '–' + d.oldEnd + ' 行)' : '') + ' ⋯';leftHtml += '<div class="oj-diff-split-row oj-diff-split-collapsed" data-count="' + d.count + '">' +'<span class="oj-diff-ln-old oj-diff-ln-collapsed">' + oldRange + '</span>' +'<span class="oj-diff-split-collapsed-inner oj-diff-collapsed-btn" title="点击展开">' + label + '</span></div>';rightHtml += '<div class="oj-diff-split-row oj-diff-split-collapsed" data-count="' + d.count + '">' +'<span class="oj-diff-ln-new oj-diff-ln-collapsed">' + newRange + '</span>' +'<span class="oj-diff-split-collapsed-inner"></span></div>';} else {const L = p.left, R = p.right;if (L) {leftHtml += '<div class="oj-diff-split-row oj-diff-split-' + L.type + '">' +'<span class="oj-diff-ln-old">' + (L.lineNum || '') + '</span>' +(L.type === 'removed' ? '<span class="oj-diff-marker">-</span>' : '<span class="oj-diff-marker oj-diff-marker-empty"></span>') +'<span class="oj-diff-content">' + escapeHtml(L.content) + '</span></div>';} else {leftHtml += '<div class="oj-diff-split-row oj-diff-split-empty"><span class="oj-diff-content"></span></div>';}if (R) {rightHtml += '<div class="oj-diff-split-row oj-diff-split-' + R.type + '">' +'<span class="oj-diff-ln-new">' + (R.lineNum || '') + '</span>' +(R.type === 'added' ? '<span class="oj-diff-marker">+</span>' : '<span class="oj-diff-marker oj-diff-marker-empty"></span>') +'<span class="oj-diff-content">' + escapeHtml(R.content) + '</span></div>';} else {rightHtml += '<div class="oj-diff-split-row oj-diff-split-empty"><span class="oj-diff-content"></span></div>';}}}const html = '<div class="oj-diff-split-container">' +'<div class="oj-diff-split-col" style="overflow-x:auto;width:50%"><div class="oj-diff-split-inner" style="min-width:100%;width:max-content">' + leftHtml + '</div></div>' +'<div class="oj-diff-split-divider"></div>' +'<div class="oj-diff-split-col" style="overflow-x:auto;width:50%"><div class="oj-diff-split-inner" style="min-width:100%;width:max-content">' + rightHtml + '</div></div>' +'</div>';return html;}// ======================== 加载遮罩 ========================function createLoadingOverlay(message) {const dark = isDarkMode();const overlay = document.createElement('div');overlay.id = 'oj-diff-loading';overlay.style.cssText ='position:fixed;top:0;left:0;right:0;bottom:0;' +'background:rgba(0,0,0,0.5);z-index:100000;' +'display:flex;align-items:center;justify-content:center;';overlay.innerHTML ='<div style="' +'background:' + getColors(dark).modalBg + ';border-radius:12px;' +'padding:32px 48px;text-align:center;' +'box-shadow:0 8px 32px rgba(0,0,0,0.3);' +'color:' + getColors(dark).textPrimary + ';font-size:16px;' +'">' +'<div class="oj-diff-spinner" style="' +'width:36px;height:36px;margin:0 auto 16px;' +'border:3px solid ' + getColors(dark).sliderTrack + ';' +'border-top-color:#3498db;border-radius:50%;' +'animation:oj-diff-spin 0.8s linear infinite;' +'"></div>' +'<div id="oj-diff-loading-msg">' + escapeHtml(message) + '</div>' +'</div>';document.body.appendChild(overlay);return overlay;}function removeLoadingOverlay() {const el = document.getElementById('oj-diff-loading');if (el) el.remove();}function updateLoadingMessage(overlay, message) {const el = overlay.querySelector('#oj-diff-loading-msg');if (el) el.textContent = message;}// ======================== 主对比模态框 ========================function showDiffModal(oldCode, newCode, oldLabel, newLabel, oldUrl, newUrl, currentRecordId, isPrevCompare) {const settings = loadSettings();const dark = isDarkMode(settings.themeMode);const C = getColors(dark);const hasRecordId = currentRecordId && String(currentRecordId).trim();const oldLines = String(oldCode || '').split('\n');const newLines = String(newCode || '').split('\n');const rawDiffs = lineDiff(oldLines, newLines);const addedCount = rawDiffs.filter(d => d.type === 'added').length;const removedCount = rawDiffs.filter(d => d.type === 'removed').length;const unchangedCount = rawDiffs.filter(d => d.type === 'unchanged').length;let displayDiffs = settings.collapseUnchanged? collapseUnchanged(rawDiffs): rawDiffs;let currentViewMode = settings.viewMode || 'unified';function renderCodeHtml(diffs, viewMode) {if (viewMode === 'split') return buildSplitHtml(diffs);return buildCodeHtml(diffs, true);}let codeHtml = renderCodeHtml(displayDiffs, currentViewMode);let expandedDiffs = rawDiffs;// ---- 构建 DOM ----const overlay = document.createElement('div');overlay.id = 'oj-diff-modal-overlay';const modal = document.createElement('div');modal.className = 'oj-diff-modal ' + (dark ? 'oj-diff-dark' : 'oj-diff-light');// ---- Header ----const header = document.createElement('div');header.className = 'oj-diff-header';// 标题(含平台标识)const titleDiv = document.createElement('div');titleDiv.className = 'oj-diff-title';const platformTag = CURRENT_PLATFORM ? '[' + CURRENT_PLATFORM.name + '] ' : '';titleDiv.innerHTML = '<span class="oj-diff-title-icon">📋</span>' + escapeHtml(platformTag) + '代码对比';// ID 对比链接区const idsDiv = document.createElement('div');idsDiv.className = 'oj-diff-ids';const oldLinkHtml = oldUrl? '<a href="' + escapeHtml(oldUrl) + '" target="_blank" class="oj-diff-record-link old">#' + escapeHtml(oldLabel) + '</a>': '<span class="oj-diff-record-link old">' + escapeHtml(oldLabel) + '</span>';const newLinkHtml = newUrl? '<a href="' + escapeHtml(newUrl) + '" target="_blank" class="oj-diff-record-link new">#' + escapeHtml(newLabel) + '</a>': '<span class="oj-diff-record-link new">' + escapeHtml(newLabel) + '</span>';idsDiv.innerHTML = oldLinkHtml + '<span class="oj-diff-arrow">→</span>' + newLinkHtml;// 统计const statsDiv = document.createElement('div');statsDiv.className = 'oj-diff-stats';statsDiv.innerHTML ='<span class="oj-diff-stat-added">+' + addedCount + ' 行</span>' +'<span class="oj-diff-stat-removed">-' + removedCount + ' 行</span>' +'<span class="oj-diff-stat-unchanged">' + unchangedCount + ' 行未变更</span>';// 亮暗模式切换按钮const themeBtn = document.createElement('button');themeBtn.className = 'oj-diff-theme-btn';themeBtn.title = '切换亮/暗模式(当前:自动)';themeBtn.setAttribute('data-theme-mode', settings.themeMode);function updateThemeBtnContent(mode) {const LABELS = { auto: '🖥 自动', light: '☀️ 亮色', dark: '🌙 暗色' };themeBtn.innerHTML = '<span class="oj-diff-theme-icon"></span><span class="oj-diff-theme-label">' + LABELS[mode] + '</span>';themeBtn.title = '切换亮/暗模式(当前:' + LABELS[mode] + ')';themeBtn.classList.remove('oj-diff-theme-auto', 'oj-diff-theme-light', 'oj-diff-theme-dark');themeBtn.classList.add('oj-diff-theme-' + mode);}updateThemeBtnContent(settings.themeMode);// 关闭按钮const closeBtn = document.createElement('button');closeBtn.className = 'oj-diff-close';closeBtn.title = '关闭';closeBtn.textContent = '✕';header.appendChild(titleDiv);header.appendChild(idsDiv);header.appendChild(statsDiv);header.appendChild(themeBtn);header.appendChild(closeBtn);// ---- Body ----const body = document.createElement('div');body.className = 'oj-diff-body';const codeArea = document.createElement('div');codeArea.className = 'oj-diff-code';codeArea.id = 'oj-diff-code-area';codeArea.innerHTML = codeHtml;body.appendChild(codeArea);// ---- Settings bar ----const settingsBar = document.createElement('div');settingsBar.className = 'oj-diff-settings-bar';settingsBar.innerHTML ='<span class="oj-diff-settings-label">字号</span>' +'<input type="range" class="oj-diff-slider" id="oj-diff-font-slider"' +' min="8" max="28" step="1" value="' + settings.fontSize + '" title="字体大小">' +'<span class="oj-diff-settings-value" id="oj-diff-font-value">' + settings.fontSize + 'px</span>' +'<span class="oj-diff-settings-divider">|</span>' +'<span class="oj-diff-settings-label">行距</span>' +'<input type="range" class="oj-diff-slider" id="oj-diff-lh-slider"' +' min="1.0" max="3.0" step="0.1" value="' + settings.lineHeight + '" title="行间距">' +'<span class="oj-diff-settings-value" id="oj-diff-lh-value">' + settings.lineHeight.toFixed(1) + 'x</span>' +'<span class="oj-diff-settings-divider">|</span>' +'<span class="oj-diff-settings-label">缩进</span>' +'<div class="oj-diff-tab-group" id="oj-diff-tab-group">' +[2, 4, 8].map(n =>'<button class="oj-diff-tab-btn' + (settings.tabSize === n ? ' active' : '') + '" data-tab="' + n + '">' + n + '</button>').join('') +'</div>' +'<span class="oj-diff-settings-divider">|</span>' +'<button class="oj-diff-collapse-toggle" id="oj-diff-collapse-btn" title="折叠/展开未变更行">' +'<span class="oj-diff-collapse-icon">📄</span>' +'<span class="oj-diff-collapse-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>';// ---- Footer ----const footer = document.createElement('div');footer.className = 'oj-diff-footer';const footerLeft = document.createElement('div');footerLeft.className = 'oj-diff-footer-left';const isAtCoder = CURRENT_PLATFORM?.id === 'atcoder';if (isAtCoder) {// AtCoder 只保留手动输入对比footerLeft.innerHTML ='<button class="oj-diff-btn oj-diff-btn-secondary" id="oj-diff-manual-compare">✏️ 两份代码对比</button>';} else if (hasRecordId) {footerLeft.innerHTML ='<button class="oj-diff-btn oj-diff-btn-secondary" id="oj-diff-prev-compare"' + (isPrevCompare ? ' disabled title="当前已在与上次提交对比"' : ' title="与上一次提交记录对比"') + '>⇄ 与上次提交对比</button>' +'<button class="oj-diff-btn oj-diff-btn-secondary" id="oj-diff-manual-compare">✏️ 两份代码对比</button>' +'<button class="oj-diff-btn oj-diff-btn-secondary" id="oj-diff-custom-compare">🔢 与指定提交对比</button>' +'<button class="oj-diff-btn oj-diff-btn-secondary" id="oj-diff-record-compare">📋 两次提交记录对比</button>';} else {footerLeft.innerHTML ='<button class="oj-diff-btn oj-diff-btn-secondary" id="oj-diff-manual-compare">✏️ 两份代码对比</button>' +'<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);modal.appendChild(header);modal.appendChild(body);modal.appendChild(settingsBar);modal.appendChild(footer);overlay.appendChild(modal);document.body.appendChild(overlay);applyCodeSettings(codeArea, settings);let currentSettings = { ...settings };// ---- 设置交互 ----const fontSlider = overlay.querySelector('#oj-diff-font-slider');const fontValueEl = overlay.querySelector('#oj-diff-font-value');const lhSlider = overlay.querySelector('#oj-diff-lh-slider');const lhValueEl = overlay.querySelector('#oj-diff-lh-value');fontSlider.addEventListener('input', () => {currentSettings.fontSize = parseInt(fontSlider.value, 10);fontValueEl.textContent = currentSettings.fontSize + 'px';applyCodeSettings(codeArea, currentSettings);saveSettings(currentSettings);});lhSlider.addEventListener('input', () => {currentSettings.lineHeight = parseFloat(parseFloat(lhSlider.value).toFixed(1));lhValueEl.textContent = currentSettings.lineHeight.toFixed(1) + 'x';applyCodeSettings(codeArea, currentSettings);saveSettings(currentSettings);});overlay.querySelector('#oj-diff-tab-group').addEventListener('click', (e) => {const btn = e.target.closest('.oj-diff-tab-btn');if (!btn) return;const tab = parseInt(btn.dataset.tab, 10);currentSettings.tabSize = tab;overlay.querySelectorAll('.oj-diff-tab-btn').forEach(b => {b.classList.toggle('active', parseInt(b.dataset.tab, 10) === tab);});applyCodeSettings(codeArea, currentSettings);saveSettings(currentSettings);});// 折叠/展开切换——三态const collapseBtn = overlay.querySelector('#oj-diff-collapse-btn');const collapseIcon = collapseBtn.querySelector('.oj-diff-collapse-icon');const collapseLabel = collapseBtn.querySelector('.oj-diff-collapse-label');function getCollapseState(diffs) {const hasCollapsed = diffs.some(d => d.type === 'collapsed');if (!hasCollapsed) return 'none';const hasUnchanged = diffs.some(d => d.type === 'unchanged');return hasUnchanged ? 'partial' : 'full';}function updateCollapseBtn(diffs) {const state = getCollapseState(diffs);collapseBtn.classList.toggle('active', state !== 'none');collapseBtn.classList.toggle('partial', state === 'partial');collapseBtn.classList.toggle('full', state === 'full');if (state === 'none') {collapseIcon.textContent = '📄'; collapseLabel.textContent = '未折叠';collapseBtn.title = '点击:折叠所有未变更行';} else if (state === 'partial') {collapseIcon.textContent = '🔀'; collapseLabel.textContent = '部分折叠';collapseBtn.title = '点击:折叠剩余未变更行';} else {collapseIcon.textContent = '🗂️'; collapseLabel.textContent = '已折叠';collapseBtn.title = '点击:展开所有行';}}let currentDiffs = displayDiffs;function refreshCollapseIcon() { updateCollapseBtn(currentDiffs); }refreshCollapseIcon();collapseBtn.addEventListener('click', () => {const state = getCollapseState(currentDiffs);let newDiffs;if (state === 'full') {currentSettings.collapseUnchanged = false;newDiffs = expandedDiffs;} else {currentSettings.collapseUnchanged = true;newDiffs = collapseUnchanged(expandedDiffs);}saveSettings(currentSettings);currentDiffs = newDiffs;codeArea.innerHTML = renderCodeHtml(newDiffs, currentViewMode);applyCodeSettings(codeArea, currentSettings);bindCollapseButtons(codeArea, newDiffs, expandedDiffs, currentSettings);refreshCollapseIcon();});// 绑定展开按钮和折叠图标事件function bindCollapseButtons(area, collapsedDiffs, allDiffs, s) {area.querySelectorAll('.oj-diff-collapsed-btn').forEach(btn => {btn.addEventListener('click', () => {const collapsedLine = btn.closest('.oj-diff-collapsed, .oj-diff-split-collapsed');if (!collapsedLine) return;const count = parseInt(collapsedLine.getAttribute('data-count'), 10);let collapsedIndex = -1;// 在 split 视图中每段折叠在左右列各有一个 DOM 元素,只取左列来匹配const sel = '.oj-diff-collapsed';const splitParent = collapsedLine.closest('.oj-diff-split-col');const allCollapsedLines = splitParent? splitParent.querySelectorAll(sel): area.querySelectorAll(sel);let collapsedCount = 0;for (let ci = 0; ci < collapsedDiffs.length; ci++) {if (collapsedDiffs[ci].type === 'collapsed') {if (allCollapsedLines[collapsedCount] === collapsedLine) {collapsedIndex = ci;break;}collapsedCount++;}}if (collapsedIndex === -1) return;const newCollapsedDiffs = collapsedDiffs.slice();newCollapsedDiffs.splice(collapsedIndex, 1);let rawOffset = 0;for (let ci = 0; ci < collapsedIndex; ci++) {const item = collapsedDiffs[ci];if (item.type === 'collapsed') { rawOffset += item.count; }else { rawOffset += 1; }}const expandedItems = allDiffs.slice(rawOffset, rawOffset + count);newCollapsedDiffs.splice(collapsedIndex, 0, ...expandedItems);const hasMoreCollapsed = newCollapsedDiffs.some(d => d.type === 'collapsed');if (!hasMoreCollapsed) { s.collapseUnchanged = false; saveSettings(s); }currentDiffs = newCollapsedDiffs;area.innerHTML = renderCodeHtml(newCollapsedDiffs, currentViewMode);applyCodeSettings(area, s);bindCollapseButtons(area, newCollapsedDiffs, allDiffs, s);refreshCollapseIcon();});});area.querySelectorAll('.oj-diff-fold-icon').forEach(icon => {icon.addEventListener('click', (e) => {e.stopPropagation();const foldStart = parseInt(icon.getAttribute('data-fold-start'), 10);const foldCount = parseInt(icon.getAttribute('data-fold-count'), 10);if (isNaN(foldStart) || isNaN(foldCount) || foldCount < 1) return;const newDiffs = collapsedDiffs.slice();let valid = true;for (let fi = 0; fi < foldCount; fi++) {if (foldStart + fi >= newDiffs.length || newDiffs[foldStart + fi].type !== 'unchanged') {valid = false; break;}}if (!valid) return;let oldNum = 0, newNum = 0;for (let pi = 0; pi < foldStart; pi++) {const d = newDiffs[pi];if (d.type === 'collapsed') { oldNum = d.oldEnd; newNum = d.newEnd; }else if (d.type === 'removed') { oldNum++; }else if (d.type === 'added') { newNum++; }else { oldNum++; newNum++; }}const cOldStart = oldNum + 1, cNewStart = newNum + 1;const cOldEnd = cOldStart + foldCount - 1, cNewEnd = cNewStart + foldCount - 1;newDiffs.splice(foldStart, foldCount, {type: 'collapsed', count: foldCount,oldStart: cOldStart, oldEnd: cOldEnd,newStart: cNewStart, newEnd: cNewEnd,});currentDiffs = newDiffs;area.innerHTML = renderCodeHtml(newDiffs, currentViewMode);applyCodeSettings(area, s);bindCollapseButtons(area, newDiffs, allDiffs, s);refreshCollapseIcon();});});}bindCollapseButtons(codeArea, displayDiffs, expandedDiffs, currentSettings);// 视图切换(unified / split)const viewBtn = overlay.querySelector('#oj-diff-view-btn');const viewIcon = viewBtn.querySelector('.oj-diff-view-icon');const viewLabel = viewBtn.querySelector('.oj-diff-view-label');function updateViewBtn(mode) {if (mode === 'split') {viewIcon.textContent = '⇔';viewLabel.textContent = '并列视图';viewBtn.title = '当前:并列视图,点击切换为统一视图';viewBtn.classList.add('active');} else {viewIcon.textContent = '☰';viewLabel.textContent = '统一视图';viewBtn.title = '当前:统一视图,点击切换为并列视图';viewBtn.classList.remove('active');}}updateViewBtn(currentViewMode);viewBtn.addEventListener('click', () => {currentViewMode = currentViewMode === 'split' ? 'unified' : 'split';currentSettings.viewMode = currentViewMode;saveSettings(currentSettings);updateViewBtn(currentViewMode);// split 视图不支持折叠图标,但支持折叠块(collapsed)codeArea.innerHTML = renderCodeHtml(currentDiffs, currentViewMode);applyCodeSettings(codeArea, currentSettings);bindCollapseButtons(codeArea, currentDiffs, expandedDiffs, currentSettings);});// 初始宽度modal.style.maxWidth = '1400px';// 亮暗模式切换const THEME_CYCLE = ['auto', 'light', 'dark'];themeBtn.addEventListener('click', () => {const cur = currentSettings.themeMode || 'auto';const next = THEME_CYCLE[(THEME_CYCLE.indexOf(cur) + 1) % 3];currentSettings.themeMode = next;updateThemeBtnContent(next);themeBtn.setAttribute('data-theme-mode', next);saveSettings(currentSettings);const newDark = isDarkMode(next);modal.classList.toggle('oj-diff-dark', newDark);modal.classList.toggle('oj-diff-light', !newDark);});// 关闭逻辑const closeBack = () => { overlay.remove(); popAndRestore(); };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); }};document.addEventListener('keydown', escHandler);if (hasParent) {closeBtn.title = '返回上级';closeBtn.textContent = '←';overlay.querySelector('#oj-diff-close-btn').textContent = '返回';}// 按钮事件绑定if (!isAtCoder && hasRecordId) {if (!isPrevCompare) {overlay.querySelector('#oj-diff-prev-compare').addEventListener('click', () => {pushAndHide(overlay);runCompare(currentRecordId, null);});}overlay.querySelector('#oj-diff-custom-compare').addEventListener('click', () => {pushAndHide(overlay);promptCustomCompare(currentRecordId);});}overlay.querySelector('#oj-diff-manual-compare').addEventListener('click', () => {pushAndHide(overlay);showManualInputDialog();});if (!isAtCoder) {overlay.querySelector('#oj-diff-record-compare').addEventListener('click', () => {pushAndHide(overlay);showRecordCompareDialog();});}}// ======================== 手动输入对比对话框 ========================function showManualInputDialog() {const existing = document.getElementById('oj-diff-manual-dialog');if (existing) existing.remove();const settings = loadSettings();const dark = isDarkMode(settings.themeMode);const C = getColors(dark);const dialog = document.createElement('div');dialog.id = 'oj-diff-manual-dialog';dialog.style.cssText ='position:fixed;top:0;left:0;right:0;bottom:0;z-index:150000;' +'display:flex;align-items:center;justify-content:center;' +'background:rgba(0,0,0,0.55);';dialog.innerHTML ='<div class="oj-diff-modal ' + (dark ? 'oj-diff-dark' : 'oj-diff-light') + '" style="max-width:860px;width:92vw;">' +'<div class="oj-diff-header">' +'<div class="oj-diff-title"><span class="oj-diff-title-icon">✏️</span>手动输入代码对比</div>' +'<button class="oj-diff-close" title="关闭">✕</button>' +'</div>' +'<div class="oj-diff-body" style="padding:20px;display:flex;gap:16px;overflow:auto;">' +'<div style="flex:1;display:flex;flex-direction:column;gap:8px;">' +'<label style="font-size:13px;font-weight:600;color:' + C.textSecondary + '">旧版本(左侧)</label>' +'<textarea id="oj-diff-manual-old" placeholder="粘贴或输入旧版本代码..." style="' +'flex:1;min-height:300px;padding:12px;border-radius:8px;' +'border:1px solid ' + C.inputBorder + ';' +'background:' + C.inputBg + ';color:' + C.textPrimary + ';' +'font-family:Consolas,monospace;font-size:13px;resize:vertical;' +'outline:none;box-sizing:border-box;tab-size:4;' +'"></textarea>' +'</div>' +'<div style="flex:1;display:flex;flex-direction:column;gap:8px;">' +'<label style="font-size:13px;font-weight:600;color:' + C.textSecondary + '">新版本(右侧)</label>' +'<textarea id="oj-diff-manual-new" placeholder="粘贴或输入新版本代码..." style="' +'flex:1;min-height:300px;padding:12px;border-radius:8px;' +'border:1px solid ' + C.inputBorder + ';' +'background:' + C.inputBg + ';color:' + C.textPrimary + ';' +'font-family:Consolas,monospace;font-size:13px;resize:vertical;' +'outline:none;box-sizing:border-box;tab-size:4;' +'"></textarea>' +'</div>' +'</div>' +'<div class="oj-diff-footer">' +'<div class="oj-diff-footer-left">' +'<button class="oj-diff-btn oj-diff-btn-secondary" id="oj-diff-manual-cancel">取消</button>' +'<button class="oj-diff-btn oj-diff-btn-secondary" id="oj-diff-manual-clear" title="清空两个输入框">🗑 清空</button>' +'</div>' +'<button class="oj-diff-btn oj-diff-btn-primary" id="oj-diff-manual-ok">开始对比</button>' +'</div>' +'</div>';document.body.appendChild(dialog);const close = () => { dialog.remove(); popAndRestore(); };dialog.querySelector('.oj-diff-close').addEventListener('click', close);dialog.querySelector('#oj-diff-manual-cancel').addEventListener('click', close);dialog.addEventListener('click', (e) => { if (e.target === dialog) close(); });dialog.querySelector('#oj-diff-manual-clear').addEventListener('click', () => {dialog.querySelector('#oj-diff-manual-old').value = '';dialog.querySelector('#oj-diff-manual-new').value = '';dialog.querySelector('#oj-diff-manual-old').focus();});const doCompare = () => {const oldCode = dialog.querySelector('#oj-diff-manual-old').value;const newCode = dialog.querySelector('#oj-diff-manual-new').value;dialog.remove();const parent = modalStack.length > 0 ? modalStack[modalStack.length - 1] : null;if (parent) { parent.remove(); modalStack.pop(); }showDiffModal(oldCode, newCode, '旧版本', '新版本', null, null, null, false);};dialog.querySelector('#oj-diff-manual-ok').addEventListener('click', doCompare);dialog.addEventListener('keydown', (e) => {if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) doCompare();if (e.key === 'Escape') close();});const xBtn = dialog.querySelector('.oj-diff-close');if (modalStack.length > 0) { xBtn.title = '返回上级'; xBtn.textContent = '←'; }[dialog.querySelector('#oj-diff-manual-old'), dialog.querySelector('#oj-diff-manual-new')].forEach(ta => {ta.addEventListener('keydown', (e) => {if (e.key === 'Tab') {e.preventDefault();const start = ta.selectionStart, end = ta.selectionEnd;ta.value = ta.value.slice(0, start) + ' ' + ta.value.slice(end);ta.selectionStart = ta.selectionEnd = start + 4;}});});setTimeout(() => dialog.querySelector('#oj-diff-manual-old').focus(), 50);}// ======================== 自定义 ID 对比对话框 ========================function promptCustomCompare(currentRecordId) {const existing = document.getElementById('oj-diff-custom-dialog');if (existing) existing.remove();const settings = loadSettings();const dark = isDarkMode(settings.themeMode);const C = getColors(dark);const dialog = document.createElement('div');dialog.id = 'oj-diff-custom-dialog';dialog.style.cssText ='position:fixed;top:0;left:0;right:0;bottom:0;z-index:150000;' +'display:flex;align-items:center;justify-content:center;' +'background:rgba(0,0,0,0.55);';dialog.innerHTML ='<div class="oj-diff-modal ' + (dark ? 'oj-diff-dark' : 'oj-diff-light') + '" style="max-width:480px;">' +'<div class="oj-diff-header">' +'<div class="oj-diff-title">输入对比提交 ID</div>' +'<button class="oj-diff-close" title="关闭">✕</button>' +'</div>' +'<div class="oj-diff-body" style="padding:24px;">' +'<p style="margin:0 0 16px;color:' + C.textSecondary + ';font-size:14px;">' +'输入要与当前提交 (#' + escapeHtml(String(currentRecordId)) + ') 对比的提交记录 ID' +'</p>' +'<input type="text" id="oj-diff-custom-id" placeholder="例如 12345678" style="' +'width:100%;padding:10px 14px;border-radius:8px;' +'border:1px solid ' + C.inputBorder + ';' +'background:' + C.inputBg + ';color:' + C.textPrimary + ';' +'font-size:15px;outline:none;box-sizing:border-box;' +'">' +'<div id="oj-diff-custom-error" style="color:#cb2431;font-size:13px;margin-top:8px;display:none;"></div>' +'</div>' +'<div class="oj-diff-footer">' +'<div class="oj-diff-footer-left">' +'<button class="oj-diff-btn oj-diff-btn-secondary" id="oj-diff-custom-cancel">取消</button>' +'</div>' +'<button class="oj-diff-btn oj-diff-btn-primary" id="oj-diff-custom-ok">开始对比</button>' +'</div>' +'</div>';document.body.appendChild(dialog);const close = () => { dialog.remove(); popAndRestore(); };dialog.querySelector('.oj-diff-close').addEventListener('click', close);dialog.querySelector('#oj-diff-custom-cancel').addEventListener('click', close);dialog.addEventListener('click', (e) => { if (e.target === dialog) close(); });const input = dialog.querySelector('#oj-diff-custom-id');input.focus();const doCompare = async () => {const targetId = input.value.trim();if (!targetId || !/^\d+$/.test(targetId)) {const errEl = dialog.querySelector('#oj-diff-custom-error');errEl.textContent = '请输入有效的数字 ID';errEl.style.display = 'block';return;}dialog.remove();const parent = modalStack.length > 0 ? modalStack[modalStack.length - 1] : null;if (parent) { parent.remove(); modalStack.pop(); }await runCompare(currentRecordId, targetId);};dialog.querySelector('#oj-diff-custom-ok').addEventListener('click', doCompare);input.addEventListener('keydown', (e) => { if (e.key === 'Enter') doCompare(); });const xBtn = dialog.querySelector('.oj-diff-close');if (modalStack.length > 0) { xBtn.title = '返回上级'; xBtn.textContent = '←'; }}// ======================== 对比两份提交记录对话框 ========================function showRecordCompareDialog() {const existing = document.getElementById('oj-diff-record-cmp-dialog');if (existing) existing.remove();const settings = loadSettings();const dark = isDarkMode(settings.themeMode);const C = getColors(dark);const dialog = document.createElement('div');dialog.id = 'oj-diff-record-cmp-dialog';dialog.style.cssText ='position:fixed;top:0;left:0;right:0;bottom:0;z-index:150000;' +'display:flex;align-items:center;justify-content:center;' +'background:rgba(0,0,0,0.55);';dialog.innerHTML ='<div class="oj-diff-modal ' + (dark ? 'oj-diff-dark' : 'oj-diff-light') + '" style="max-width:560px;">' +'<div class="oj-diff-header">' +'<div class="oj-diff-title"><span class="oj-diff-title-icon">🔢</span>对比两份提交记录</div>' +'<button class="oj-diff-close" title="关闭">✕</button>' +'</div>' +'<div class="oj-diff-body" style="padding:24px;display:flex;flex-direction:column;gap:16px;">' +'<p style="margin:0;color:' + C.textSecondary + ';font-size:14px;">' +'输入两份提交记录的 ID,获取代码后进行对比' +'</p>' +'<div style="display:flex;gap:12px;align-items:center;">' +'<div style="flex:1;display:flex;flex-direction:column;gap:4px;">' +'<label style="font-size:12px;font-weight:600;color:' + C.textSecondary + '">旧版本 ID(左侧)</label>' +'<input type="text" id="oj-diff-rcmp-old-id" placeholder="例如 12345678" style="' +'width:100%;padding:10px 14px;border-radius:8px;' +'border:1px solid ' + C.inputBorder + ';' +'background:' + C.inputBg + ';color:' + C.textPrimary + ';' +'font-size:15px;outline:none;box-sizing:border-box;' +'">' +'</div>' +'<span style="font-size:20px;color:' + C.textSecondary + ';margin-top:20px;">→</span>' +'<div style="flex:1;display:flex;flex-direction:column;gap:4px;">' +'<label style="font-size:12px;font-weight:600;color:' + C.textSecondary + '">新版本 ID(右侧)</label>' +'<input type="text" id="oj-diff-rcmp-new-id" placeholder="例如 87654321" style="' +'width:100%;padding:10px 14px;border-radius:8px;' +'border:1px solid ' + C.inputBorder + ';' +'background:' + C.inputBg + ';color:' + C.textPrimary + ';' +'font-size:15px;outline:none;box-sizing:border-box;' +'">' +'</div>' +'</div>' +'<div id="oj-diff-rcmp-error" style="color:#cb2431;font-size:13px;display:none;"></div>' +'</div>' +'<div class="oj-diff-footer">' +'<div class="oj-diff-footer-left">' +'<button class="oj-diff-btn oj-diff-btn-secondary" id="oj-diff-rcmp-cancel">取消</button>' +'</div>' +'<button class="oj-diff-btn oj-diff-btn-primary" id="oj-diff-rcmp-ok">开始对比</button>' +'</div>' +'</div>';document.body.appendChild(dialog);const close = () => { dialog.remove(); popAndRestore(); };dialog.querySelector('.oj-diff-close').addEventListener('click', close);dialog.querySelector('#oj-diff-rcmp-cancel').addEventListener('click', close);dialog.addEventListener('click', (e) => { if (e.target === dialog) close(); });const oldInput = dialog.querySelector('#oj-diff-rcmp-old-id');const newInput = dialog.querySelector('#oj-diff-rcmp-new-id');const xBtn = dialog.querySelector('.oj-diff-close');if (modalStack.length > 0) { xBtn.title = '返回上级'; xBtn.textContent = '←'; }const doCompare = async () => {const oldId = oldInput.value.trim();const newId = newInput.value.trim();const errEl = dialog.querySelector('#oj-diff-rcmp-error');if (!oldId || !/^\d+$/.test(oldId) || !newId || !/^\d+$/.test(newId)) {errEl.textContent = '请输入有效的数字 ID(两个 ID 均为必填)';errEl.style.display = 'block';return;}if (oldId === newId) {errEl.textContent = '两个 ID 不能相同';errEl.style.display = 'block';return;}errEl.style.display = 'none';dialog.remove();const parent = modalStack.length > 0 ? modalStack[modalStack.length - 1] : null;if (parent) { parent.remove(); modalStack.pop(); }await runRecordCompare(oldId, newId);};dialog.querySelector('#oj-diff-rcmp-ok').addEventListener('click', doCompare);oldInput.addEventListener('keydown', (e) => { if (e.key === 'Enter') newInput.focus(); });newInput.addEventListener('keydown', (e) => { if (e.key === 'Enter') doCompare(); });setTimeout(() => oldInput.focus(), 50);}// ======================== Toast 提示 ========================function showToast(message, type) {const dark = isDarkMode();const isError = type === 'error';const toast = document.createElement('div');toast.style.cssText ='position:fixed;top:20px;left:50%;transform:translateX(-50%);' +'z-index:200000;' +'background:' + (isError ? (dark ? '#3d1a1a' : '#ffeef0') : (dark ? '#1b3a1f' : '#e6ffed')) + ';' +'color:' + (isError ? (dark ? '#f85149' : '#cb2431') : (dark ? '#3fb950' : '#22863a')) + ';' +'padding:12px 24px;border-radius:8px;font-size:14px;' +'box-shadow:0 4px 16px rgba(0,0,0,0.2);max-width:480px;text-align:center;';toast.textContent = (isError ? '❌ ' : '✅ ') + message;document.body.appendChild(toast);setTimeout(() => {toast.style.transition = 'opacity 0.3s';toast.style.opacity = '0';setTimeout(() => toast.remove(), 300);}, isError ? 4000 : 2000);}// ======================== 核心逻辑(通用,通过 ADAPTER 多态调用) ========================/** 根据两份提交记录 ID 获取代码并对比 */async function runRecordCompare(oldId, newId) {const loading = createLoadingOverlay('正在获取代码,请稍候...');try {updateLoadingMessage(loading, '正在获取旧版本 #' + oldId + ' ...');const oldRecord = await ADAPTER.fetchRecordDetail(oldId);updateLoadingMessage(loading, '正在获取新版本 #' + newId + ' ...');const newRecord = await ADAPTER.fetchRecordDetail(newId);const oldCode = ADAPTER.getSourceCode(oldRecord);const newCode = ADAPTER.getSourceCode(newRecord);if (!oldCode) throw new Error('旧版本 #' + oldId + ' 的代码不可访问或为空');if (!newCode) throw new Error('新版本 #' + newId + ' 的代码不可访问或为空');removeLoadingOverlay();showDiffModal(String(oldCode), String(newCode),String(oldId), String(newId),ADAPTER.recordUrl(oldId, oldRecord), ADAPTER.recordUrl(newId, newRecord),ADAPTER.getRecordIdFromUrl(),false);} catch (err) {removeLoadingOverlay();showToast(err.message, 'error');}}/** 核心对比逻辑 */async function runCompare(currentRecordId, targetRecordId) {const loading = createLoadingOverlay('正在获取代码,请稍候...');try {let currentRecord;let targetRecord;if (targetRecordId) {// 指定提交 ID 对比——总是从 API 重新获取,避免 getPageData 可能缺少 sourceCodeupdateLoadingMessage(loading, '正在获取当前提交代码...');currentRecord = await ADAPTER.fetchRecordDetail(currentRecordId);updateLoadingMessage(loading, '正在获取对比提交代码...');targetRecord = await ADAPTER.fetchRecordDetail(targetRecordId);} else {// 与上次提交对比// 尝试从页面缓存获取(仅洛谷有效,快速获取当前记录信息)const pageData = ADAPTER.getPageData();if (pageData) {currentRecord = pageData;} else {updateLoadingMessage(loading, '正在获取当前提交信息...');currentRecord = await ADAPTER.fetchRecordDetail(currentRecordId);}updateLoadingMessage(loading, '正在查找上一次提交记录...');const prevBase = await ADAPTER.findPrevRecord(currentRecordId, currentRecord);updateLoadingMessage(loading, '正在获取上一次提交代码...');targetRecord = await ADAPTER.fetchRecordDetail(prevBase.id, prevBase);}const curCode = ADAPTER.getSourceCode(currentRecord);const tgtCode = ADAPTER.getSourceCode(targetRecord);if (!curCode) throw new Error('当前提交的代码不可访问或为空(可能是隐私设置或权限不足)');if (!tgtCode) throw new Error('对比提交的代码不可访问或为空(可能是隐私设置或权限不足)');removeLoadingOverlay();showDiffModal(String(tgtCode), String(curCode),String(targetRecord.id || targetRecordId),String(currentRecord.id || currentRecordId),ADAPTER.recordUrl(targetRecord.id || targetRecordId, targetRecord),ADAPTER.recordUrl(currentRecord.id || currentRecordId, currentRecord),String(currentRecordId),!targetRecordId);} catch (err) {removeLoadingOverlay();showToast(err.message, 'error');}}// ======================== 按钮注入 ========================function injectCompareButton() {if (document.getElementById('oj-diff-compare-btn')) return;const recordId = ADAPTER.getRecordIdFromUrl();if (!recordId) return;const btn = document.createElement('button');btn.id = 'oj-diff-compare-btn';btn.textContent = '⇄ 代码对比';btn.title = '代码对比工具';btn.style.cssText ='position:fixed;bottom:24px;right:24px;z-index:99999;' +'padding:12px 20px;border:none;border-radius:24px;' +'background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);' +'color:#ffffff;font-size:15px;font-weight:600;' +'cursor:pointer;box-shadow:0 4px 16px rgba(102,126,234,0.4);' +'transition:all 0.2s ease;letter-spacing:0.5px;';btn.addEventListener('mouseenter', () => {const ddx = btn._dx || 0, ddy = btn._dy || 0;btn.style.transform = `translate(${ddx}px, ${ddy}px) scale(1.05)`;btn.style.boxShadow = '0 6px 24px rgba(102,126,234,0.6)';});btn.addEventListener('mouseleave', () => {const ddx = btn._dx || 0, ddy = btn._dy || 0;btn.style.transform = `translate(${ddx}px, ${ddy}px) scale(1)`;btn.style.boxShadow = '0 4px 16px rgba(102,126,234,0.4)';});btn.addEventListener('click', () => showFloatingMenu(recordId));document.body.appendChild(btn);makeDraggable(btn);}function showFloatingMenu(recordId) {const existing = document.getElementById('oj-diff-float-menu');if (existing) { existing.remove(); return; }const btn = document.getElementById('oj-diff-compare-btn');if (!btn) return;const rect = btn.getBoundingClientRect();const dark = isDarkMode();const C = getColors(dark);const isAtCoder = CURRENT_PLATFORM?.id === 'atcoder';const items = isAtCoder? [ { text: '✏️ 两份代码对比', action: () => showManualInputDialog() } ]: [{ text: '⇄ 与上次提交记录对比', action: () => runCompare(recordId, null) },{ text: '🔢 与指定提交记录对比', action: () => promptCustomCompare(recordId) },{ text: '✏️ 两份代码对比', action: () => showManualInputDialog() },{ text: '📋 两次提交记录对比', action: () => showRecordCompareDialog() },];const menuW = 220;const menu = document.createElement('div');menu.id = 'oj-diff-float-menu';menu.style.cssText ='position:fixed;z-index:-1;top:0;left:0;visibility:hidden;' +'background:' + C.modalBg + ';border:1px solid ' + C.border + ';' +'border-radius:12px;box-shadow:0 8px 32px rgba(0,0,0,0.2);' +'padding:8px 0;min-width:' + menuW + 'px;';// 先装填项目、挂到 DOM 测量实际高度,再移除并重新定位for (const item of items) {const el = document.createElement('div');el.textContent = item.text;el.style.cssText ='padding:10px 20px;cursor:pointer;font-size:14px;' +'color:' + C.textPrimary + ';transition:background 0.15s;';el.addEventListener('mouseenter', () => el.style.background = C.bgSecondary);el.addEventListener('mouseleave', () => el.style.background = 'transparent');el.addEventListener('click', () => { menu.remove(); item.action(); });menu.appendChild(el);}document.body.appendChild(menu);const actualH = menu.offsetHeight;menu.remove();menu.style.visibility = '';menu.style.zIndex = '100001';// 水平位置:优先右对齐,太靠左则左对齐let ml = rect.right - menuW;if (ml < 4) ml = Math.max(4, rect.left);if (ml + menuW > window.innerWidth - 4) ml = window.innerWidth - menuW - 4;// 垂直位置:上方空间够则在按钮上方,否则在下方let mt;if (rect.top > actualH + 12) {mt = rect.top - 8 - actualH;} else {mt = rect.bottom + 8;}mt = Math.max(4, Math.min(mt, window.innerHeight - actualH - 4));menu.style.top = mt + 'px';menu.style.left = ml + 'px';document.body.appendChild(menu);document.body.appendChild(menu);const outsideClick = (e) => {if (!menu.contains(e.target)) { menu.remove(); document.removeEventListener('click', outsideClick); }};setTimeout(() => document.addEventListener('click', outsideClick), 0);}function injectInlineButton(recordId) {const existing = document.querySelector('[data-oj-diff-injected]');if (existing && document.body.contains(existing)) return;const codeBlock = document.querySelector('pre') || document.querySelector('code');if (!codeBlock) return;const container = document.createElement('div');container.setAttribute('data-oj-diff-injected', '1');container.style.cssText = 'display:flex;gap:8px;margin:8px 0;align-items:center;flex-wrap:wrap;';function makeBtn(text, color, onClick) {const b = document.createElement('button');b.textContent = text;b.style.cssText ='padding:6px 16px;border:1px solid ' + color + ';border-radius:6px;' +'background:transparent;color:' + color + ';font-size:13px;' +'cursor:pointer;transition:all 0.2s;';b.addEventListener('mouseenter', () => { b.style.background = color; b.style.color = '#fff'; });b.addEventListener('mouseleave', () => { b.style.background = 'transparent'; b.style.color = color; });b.addEventListener('click', onClick);return b;}const isAtCoder = CURRENT_PLATFORM?.id === 'atcoder';let buttons;if (isAtCoder) {buttons = [makeBtn('✏️ 两份代码对比', '#059669', () => showManualInputDialog())];} else {const b1 = makeBtn('⇄ 与上次提交对比', '#667eea', async () => {b1.style.pointerEvents = 'none';try { await runCompare(recordId, null); }finally { b1.style.pointerEvents = 'auto'; }});const b2 = makeBtn('🔢 与指定提交对比', '#8b5cf6', () => promptCustomCompare(recordId));const b3 = makeBtn('✏️ 两份代码对比', '#059669', () => showManualInputDialog());const b4 = makeBtn('📋 两次提交记录对比', '#d97706', () => showRecordCompareDialog());buttons = [b1, b2, b3, b4];}for (const b of buttons) container.appendChild(b);const preParent = codeBlock.closest('pre') || codeBlock.parentElement;if (preParent && preParent.parentElement) {preParent.parentElement.insertBefore(container, preParent);}}// ======================== 通用浮动按钮(非记录页) ========================function injectUniversalButton() {if (document.getElementById('oj-diff-universal-btn')) return;const dark = isDarkMode();const C = getColors(dark);const btn = document.createElement('button');btn.id = 'oj-diff-universal-btn';btn.innerHTML = '📋 代码对比';btn.title = '代码对比工具(手动输入 / 提交记录 ID 对比)';btn.style.cssText ='position:fixed;bottom:24px;right:24px;z-index:99999;' +'padding:12px 20px;border:none;border-radius:24px;' +'background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);' +'color:#ffffff;font-size:15px;font-weight:600;' +'cursor:pointer;box-shadow:0 4px 16px rgba(102,126,234,0.4);' +'transition:all 0.2s ease;letter-spacing:0.5px;';btn.addEventListener('mouseenter', () => {const ddx = btn._dx || 0, ddy = btn._dy || 0;btn.style.transform = `translate(${ddx}px, ${ddy}px) scale(1.05)`;btn.style.boxShadow = '0 6px 24px rgba(102,126,234,0.6)';});btn.addEventListener('mouseleave', () => {const ddx = btn._dx || 0, ddy = btn._dy || 0;btn.style.transform = `translate(${ddx}px, ${ddy}px) scale(1)`;btn.style.boxShadow = '0 4px 16px rgba(102,126,234,0.4)';});btn.addEventListener('click', () => showUniversalMenu(btn));document.body.appendChild(btn);makeDraggable(btn);}function showUniversalMenu(anchor) {const existing = document.getElementById('oj-diff-universal-menu');if (existing) { existing.remove(); return; }const rect = anchor.getBoundingClientRect();const dark = isDarkMode();const C = getColors(dark);const isAtCoder = CURRENT_PLATFORM?.id === 'atcoder';const items = isAtCoder? [{ text: '✏️ 两份代码对比', action: () => showManualInputDialog() }]: [{ text: '✏️ 两份代码对比', action: () => showManualInputDialog() },{ text: '📋 两次提交记录对比', action: () => showRecordCompareDialog() },];const menuW = 200;const menu = document.createElement('div');menu.id = 'oj-diff-universal-menu';menu.style.cssText ='position:fixed;z-index:-1;top:0;left:0;visibility:hidden;' +'background:' + C.modalBg + ';border:1px solid ' + C.border + ';' +'border-radius:12px;box-shadow:0 8px 32px rgba(0,0,0,0.2);' +'padding:8px 0;min-width:' + menuW + 'px;';for (const item of items) {const el = document.createElement('div');el.textContent = item.text;el.style.cssText ='padding:10px 20px;cursor:pointer;font-size:14px;' +'color:' + C.textPrimary + ';transition:background 0.15s;';el.addEventListener('mouseenter', () => el.style.background = C.bgSecondary);el.addEventListener('mouseleave', () => el.style.background = 'transparent');el.addEventListener('click', () => { menu.remove(); item.action(); });menu.appendChild(el);}document.body.appendChild(menu);const actualH = menu.offsetHeight;menu.remove();menu.style.visibility = '';menu.style.zIndex = '100001';let ml = rect.right - menuW;if (ml < 4) ml = Math.max(4, rect.left);if (ml + menuW > window.innerWidth - 4) ml = window.innerWidth - menuW - 4;let mt;if (rect.top > actualH + 12) {mt = rect.top - 8 - actualH;} else {mt = rect.bottom + 8;}mt = Math.max(4, Math.min(mt, window.innerHeight - actualH - 4));menu.style.top = mt + 'px';menu.style.left = ml + 'px';document.body.appendChild(menu);const outsideClick = (e) => {if (!menu.contains(e.target)) { menu.remove(); document.removeEventListener('click', outsideClick); }};setTimeout(() => document.addEventListener('click', outsideClick), 0);}// ======================== 样式注入 ========================function injectStyles() {GM_addStyle(`@keyframes oj-diff-spin { to { transform: rotate(360deg); } }#oj-diff-modal-overlay,#oj-diff-custom-dialog,#oj-diff-manual-dialog {position: fixed; top: 0; left: 0; right: 0; bottom: 0;z-index: 150000; display: flex; align-items: center; justify-content: center;background: rgba(0, 0, 0, 0.5);}.oj-diff-modal {width: 90vw; max-width: 1400px; max-height: 85vh;border-radius: 16px; overflow: hidden;display: flex; flex-direction: column;box-shadow: 0 16px 64px rgba(0, 0, 0, 0.3);}.oj-diff-modal.oj-diff-light { background: #ffffff; color: #24292e; }.oj-diff-modal.oj-diff-dark { background: #161b22; color: #e6edf3; }/* Header */.oj-diff-header {display: flex; align-items: center; gap: 12px;padding: 14px 20px; border-bottom: 1px solid;flex-shrink: 0; flex-wrap: wrap;}.oj-diff-light .oj-diff-header { border-color: #e1e4e8; background: #f6f8fa; }.oj-diff-dark .oj-diff-header { border-color: #30363d; background: #0d1117; }.oj-diff-title { font-size: 17px; font-weight: 700; display: flex; align-items: center; gap: 8px; flex-shrink: 0; }.oj-diff-light .oj-diff-title { color: #24292e; }.oj-diff-dark .oj-diff-title { color: #e6edf3; }.oj-diff-title-icon { font-size: 20px; }.oj-diff-ids { display: flex; align-items: center; gap: 8px; font-size: 14px; }.oj-diff-record-link {text-decoration: none; font-weight: 600;padding: 2px 8px; border-radius: 4px; transition: opacity 0.2s;}a.oj-diff-record-link:hover { opacity: 0.8; }.oj-diff-record-link.old { color: #cb2431; background: #ffeef0; }.oj-diff-dark .oj-diff-record-link.old { color: #f85149; background: #3d1a1a; }.oj-diff-record-link.new { color: #22863a; background: #e6ffed; }.oj-diff-dark .oj-diff-record-link.new { color: #3fb950; background: #1b3a1f; }.oj-diff-arrow { color: #959da5; font-weight: 700; }.oj-diff-stats { margin-left: auto; display: flex; gap: 10px; font-size: 12px; font-weight: 600; flex-wrap: wrap; }.oj-diff-stat-added { color: #22863a; }.oj-diff-stat-removed { color: #cb2431; }.oj-diff-stat-unchanged{ color: #959da5; }.oj-diff-dark .oj-diff-stat-added { color: #3fb950; }.oj-diff-dark .oj-diff-stat-removed { color: #f85149; }.oj-diff-dark .oj-diff-stat-unchanged{ color: #484f58; }/* Theme toggle button */.oj-diff-theme-btn {height: 30px; border: 1.5px solid; border-radius: 6px;cursor: pointer; font-size: 12px; font-weight: 600;display: flex; align-items: center; gap: 4px;padding: 0 10px; flex-shrink: 0; transition: all 0.2s; white-space: nowrap;}.oj-diff-theme-icon { font-size: 14px; line-height: 1; }.oj-diff-theme-label { font-size: 11px; }.oj-diff-light .oj-diff-theme-btn { background: #ffffff; color: #586069; border-color: #d1d5da; }.oj-diff-light .oj-diff-theme-btn:hover { background: #f3f4f6; border-color: #667eea; color: #667eea; }.oj-diff-light .oj-diff-theme-btn.oj-diff-theme-auto { border-color: #959da5; }.oj-diff-light .oj-diff-theme-btn.oj-diff-theme-light { border-color: #e8a317; color: #e8a317; background: #fffbe6; }.oj-diff-light .oj-diff-theme-btn.oj-diff-theme-dark { border-color: #6e7781; color: #6e7781; background: #f0f0f0; }.oj-diff-dark .oj-diff-theme-btn { background: #21262d; color: #8b949e; border-color: #30363d; }.oj-diff-dark .oj-diff-theme-btn:hover { background: #30363d; border-color: #667eea; color: #667eea; }.oj-diff-dark .oj-diff-theme-btn.oj-diff-theme-auto { border-color: #484f58; }.oj-diff-dark .oj-diff-theme-btn.oj-diff-theme-light { border-color: #e8a317; color: #e8a317; background: #2a2300; }.oj-diff-dark .oj-diff-theme-btn.oj-diff-theme-dark { border-color: #8b949e; color: #c9d1d9; background: #21262d; }/* Close button */.oj-diff-close {width: 32px; height: 32px; border: none; border-radius: 8px;cursor: pointer; font-size: 18px;display: flex; align-items: center; justify-content: center;transition: background 0.2s; flex-shrink: 0;}.oj-diff-light .oj-diff-close { background: #f0f0f0; color: #586069; }.oj-diff-light .oj-diff-close:hover { background: #d0d0d0; }.oj-diff-dark .oj-diff-close { background: #21262d; color: #8b949e; }.oj-diff-dark .oj-diff-close:hover { background: #30363d; }/* Body */.oj-diff-body { flex: 1; overflow: auto; padding: 0; }.oj-diff-code {font-family: 'Cascadia Code', 'Fira Code', 'JetBrains Mono', 'Consolas', monospace;font-size: 13px; line-height: 1.5;font-variant-ligatures: none;font-feature-settings: "liga" 0, "calt" 0;white-space: pre; tab-size: 4; -moz-tab-size: 4;}.oj-diff-line { display: flex; align-items: stretch; min-width: 100%; width: max-content; }.oj-diff-ln-old, .oj-diff-ln-new {display: inline-block; width: 3em; min-width: 3em;text-align: right; padding: 0 8px 0 0;user-select: none; font-size: 12px; flex-shrink: 0; box-sizing: border-box;}.oj-diff-marker { display: inline-block; width: 1.5em; min-width: 1.5em; text-align: center; user-select: none; font-weight: 700; flex-shrink: 0; }.oj-diff-marker-empty { display: inline-block; width: 1.5em; min-width: 1.5em; flex-shrink: 0; }.oj-diff-content { flex: 1; white-space: pre; padding-left: 4px; min-width: 0; }/* Collapsed lines */.oj-diff-collapsed { cursor: pointer; user-select: none; }.oj-diff-ln-collapsed { font-style: italic; opacity: 0.6; font-size: 10px; }.oj-diff-collapsed-btn { display: block; width: 100%; padding: 4px 16px; font-size: 11px; font-family: sans-serif; text-align: center; transition: background 0.2s; }.oj-diff-light .oj-diff-collapsed-btn { color: #586069; background: #f6f8fa; border-top: 1px dashed #d1d5da; border-bottom: 1px dashed #d1d5da; }.oj-diff-light .oj-diff-collapsed-btn:hover { background: #eaf1fb; color: #0366d6; }.oj-diff-dark .oj-diff-collapsed-btn { color: #8b949e; background: #0d1117; border-top: 1px dashed #30363d; border-bottom: 1px dashed #30363d; }.oj-diff-dark .oj-diff-collapsed-btn:hover { background: #161b22; color: #58a6ff; }/* Unchanged lines */.oj-diff-light .oj-diff-unchanged .oj-diff-ln-old, .oj-diff-light .oj-diff-unchanged .oj-diff-ln-new { color: #959da5; background: #f6f8fa; }.oj-diff-light .oj-diff-unchanged .oj-diff-content { color: #24292e; }.oj-diff-dark .oj-diff-unchanged .oj-diff-ln-old, .oj-diff-dark .oj-diff-unchanged .oj-diff-ln-new { color: #484f58; background: #161b22; }.oj-diff-dark .oj-diff-unchanged .oj-diff-content { color: #e6edf3; }/* Removed lines */.oj-diff-removed { background: #ffeef0; }.oj-diff-light .oj-diff-removed .oj-diff-ln-old { color: #cb2431; background: #f8d7da; }.oj-diff-light .oj-diff-removed .oj-diff-ln-new { background: #ffeef0; }.oj-diff-light .oj-diff-removed .oj-diff-marker { color: #cb2431; }.oj-diff-light .oj-diff-removed .oj-diff-content { color: #24292e; }.oj-diff-dark .oj-diff-removed { background: #3d1a1a; }.oj-diff-dark .oj-diff-removed .oj-diff-ln-old { color: #f85149; background: #4d2020; }.oj-diff-dark .oj-diff-removed .oj-diff-ln-new { background: #3d1a1a; }.oj-diff-dark .oj-diff-removed .oj-diff-marker { color: #f85149; }.oj-diff-dark .oj-diff-removed .oj-diff-content { color: #e6edf3; }/* Added lines */.oj-diff-added { background: #e6ffed; }.oj-diff-light .oj-diff-added .oj-diff-ln-new { color: #22863a; background: #cdffd8; }.oj-diff-light .oj-diff-added .oj-diff-ln-old { background: #e6ffed; }.oj-diff-light .oj-diff-added .oj-diff-marker { color: #22863a; }.oj-diff-light .oj-diff-added .oj-diff-content { color: #24292e; }.oj-diff-dark .oj-diff-added { background: #1b3a1f; }.oj-diff-dark .oj-diff-added .oj-diff-ln-new { color: #3fb950; background: #245028; }.oj-diff-dark .oj-diff-added .oj-diff-ln-old { background: #1b3a1f; }.oj-diff-dark .oj-diff-added .oj-diff-marker { color: #3fb950; }.oj-diff-dark .oj-diff-added .oj-diff-content { color: #e6edf3; }/* Settings bar */.oj-diff-settings-bar {display: flex; align-items: center; gap: 10px;padding: 8px 20px; border-top: 1px solid; flex-shrink: 0;overflow-x: auto; white-space: nowrap;}.oj-diff-light .oj-diff-settings-bar { border-color: #e1e4e8; background: #ffffff; }.oj-diff-dark .oj-diff-settings-bar { border-color: #30363d; background: #161b22; }.oj-diff-settings-label { font-size: 12px; font-weight: 600; user-select: none; flex-shrink: 0; }.oj-diff-light .oj-diff-settings-label { color: #586069; }.oj-diff-dark .oj-diff-settings-label { color: #8b949e; }/* Slider */.oj-diff-slider {-webkit-appearance: none; appearance: none; height: 4px; border-radius: 4px;outline: none; cursor: pointer; width: 80px; min-width: 80px; max-width: 80px; flex-shrink: 0;}.oj-diff-light .oj-diff-slider { background: #d1d5da; }.oj-diff-dark .oj-diff-slider { background: #30363d; }.oj-diff-slider::-webkit-slider-thumb {-webkit-appearance: none; width: 14px; height: 14px; border-radius: 50%;background: #667eea; cursor: pointer; box-shadow: 0 1px 4px rgba(102,126,234,0.5); transition: transform 0.15s;}.oj-diff-slider::-webkit-slider-thumb:hover { transform: scale(1.2); }.oj-diff-slider::-moz-range-thumb { width: 14px; height: 14px; border-radius: 50%; background: #667eea; cursor: pointer; border: none; }.oj-diff-settings-value { font-size: 12px; min-width: 36px; text-align: center; font-variant-numeric: tabular-nums; user-select: none; }.oj-diff-light .oj-diff-settings-value { color: #24292e; }.oj-diff-dark .oj-diff-settings-value { color: #e6edf3; }.oj-diff-settings-divider { color: #d1d5da; user-select: none; font-size: 12px; }.oj-diff-dark .oj-diff-settings-divider { color: #30363d; }/* Tab buttons */.oj-diff-tab-group { display: flex; gap: 2px; border-radius: 6px; overflow: hidden; border: 1px solid; flex-shrink: 0; }.oj-diff-light .oj-diff-tab-group { border-color: #d1d5da; }.oj-diff-dark .oj-diff-tab-group { border-color: #30363d; }.oj-diff-tab-btn { padding: 3px 9px; font-size: 12px; border: none; cursor: pointer; transition: all 0.15s; font-weight: 600; background: transparent; }.oj-diff-light .oj-diff-tab-btn { color: #586069; }.oj-diff-light .oj-diff-tab-btn:hover { background: #e8f0fe; color: #667eea; }.oj-diff-light .oj-diff-tab-btn.active { background: #667eea; color: #fff; }.oj-diff-dark .oj-diff-tab-btn { color: #8b949e; }.oj-diff-dark .oj-diff-tab-btn:hover { background: #21262d; color: #667eea; }.oj-diff-dark .oj-diff-tab-btn.active { background: #667eea; color: #fff; }/* Collapse toggle */.oj-diff-collapse-toggle {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-collapse-icon { font-size: 14px; line-height: 1; }.oj-diff-collapse-label { font-size: 11px; line-height: 1; }.oj-diff-light .oj-diff-collapse-toggle { color: #586069; border-color: #d1d5da; }.oj-diff-light .oj-diff-collapse-toggle:hover { background: #f3f4f6; border-color: #667eea; color: #667eea; }.oj-diff-light .oj-diff-collapse-toggle.active,.oj-diff-light .oj-diff-collapse-toggle.active:hover { border-color: #667eea; color: #667eea; background: #eaf1fb; }.oj-diff-light .oj-diff-collapse-toggle.partial,.oj-diff-light .oj-diff-collapse-toggle.partial:hover { border-color: #e8a317; color: #b08800; background: #fff8e1; }.oj-diff-dark .oj-diff-collapse-toggle { color: #8b949e; border-color: #30363d; }.oj-diff-dark .oj-diff-collapse-toggle:hover { background: #21262d; border-color: #667eea; color: #667eea; }.oj-diff-dark .oj-diff-collapse-toggle.active,.oj-diff-dark .oj-diff-collapse-toggle.active:hover { border-color: #667eea; color: #667eea; background: #1a2332; }.oj-diff-dark .oj-diff-collapse-toggle.partial,.oj-diff-dark .oj-diff-collapse-toggle.partial:hover { border-color: #d29922; color: #d29922; background: #261e0a; }/* Fold icon */.oj-diff-fold-icon {display: inline-block; vertical-align: middle;width: 12px; min-width: 12px; height: 1em; line-height: 1em;text-align: center; flex-shrink: 0;font-size: 8px; cursor: pointer; user-select: none;opacity: 0.3; transition: opacity 0.15s, color 0.15s, background 0.15s; border-radius: 2px;}.oj-diff-unchanged:hover .oj-diff-fold-icon, .oj-diff-unchanged-foldable .oj-diff-fold-icon { opacity: 0.5; }.oj-diff-fold-icon:hover { opacity: 1 !important; transform: scale(1.2); }.oj-diff-light .oj-diff-fold-icon { color: #586069; }.oj-diff-light .oj-diff-fold-icon:hover { color: #667eea; background: #e8eafc; }.oj-diff-dark .oj-diff-fold-icon { color: #8b949e; }.oj-diff-dark .oj-diff-fold-icon:hover { color: #79c0ff; background: #1c2d41; }.oj-diff-fold-icon-placeholder { display: inline-block; vertical-align: middle; width: 12px; min-width: 12px; flex-shrink: 0; }/* Footer */.oj-diff-footer {display: flex; align-items: center; justify-content: space-between;gap: 12px; padding: 14px 20px; border-top: 1px solid; flex-shrink: 0; flex-wrap: wrap;}.oj-diff-light .oj-diff-footer { border-color: #e1e4e8; background: #f6f8fa; }.oj-diff-dark .oj-diff-footer { border-color: #30363d; background: #0d1117; }.oj-diff-footer-left { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }.oj-diff-btn {padding: 7px 16px; border-radius: 8px; font-size: 13px;font-weight: 600; cursor: pointer; transition: all 0.2s; border: none; white-space: nowrap;}.oj-diff-btn-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: #ffffff; }.oj-diff-btn-primary:hover { opacity: 0.9; transform: translateY(-1px); }.oj-diff-btn-secondary { background: transparent; border: 1px solid; }.oj-diff-light .oj-diff-btn-secondary { border-color: #d1d5da; color: #586069; }.oj-diff-light .oj-diff-btn-secondary:hover { background: #f3f4f6; }.oj-diff-dark .oj-diff-btn-secondary { border-color: #30363d; color: #8b949e; }.oj-diff-dark .oj-diff-btn-secondary:hover { background: #21262d; }.oj-diff-btn-secondary:disabled { opacity: 0.4; cursor: not-allowed; }/* View toggle button */.oj-diff-view-toggle {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-view-icon { font-size: 14px; line-height: 1; }.oj-diff-view-label { font-size: 11px; line-height: 1; }.oj-diff-light .oj-diff-view-toggle { color: #586069; border-color: #d1d5da; }.oj-diff-light .oj-diff-view-toggle:hover { background: #f3f4f6; border-color: #667eea; color: #667eea; }.oj-diff-light .oj-diff-view-toggle.active,.oj-diff-light .oj-diff-view-toggle.active:hover { border-color: #667eea; color: #667eea; background: #eaf1fb; }.oj-diff-dark .oj-diff-view-toggle { color: #8b949e; border-color: #30363d; }.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; }/* Split view */.oj-diff-split-container { display: flex; width: 100%; }.oj-diff-split-col { display: flex; flex-direction: column; }.oj-diff-light .oj-diff-split-inner { background: #ffffff; }.oj-diff-dark .oj-diff-split-inner { background: #0d1117; }.oj-diff-split-row {display: flex; align-items: baseline; min-height: 1.5em;min-width: 100%; width: max-content;}.oj-diff-split-row .oj-diff-content { white-space: pre; padding-left: 4px; flex: 1; min-width: 0; }.oj-diff-split-row .oj-diff-ln-old,.oj-diff-split-row .oj-diff-ln-new { width: 3em; min-width: 3em; text-align: right; padding: 0 8px 0 0; user-select: none; font-size: 12px; flex-shrink: 0; box-sizing: border-box; }.oj-diff-split-row .oj-diff-marker,.oj-diff-split-row .oj-diff-marker-empty { width: 1.5em; min-width: 1.5em; text-align: center; user-select: none; font-weight: 700; flex-shrink: 0; }.oj-diff-split-divider { width: 2px; flex-shrink: 0; }.oj-diff-light .oj-diff-split-divider { background: #e1e4e8; }.oj-diff-dark .oj-diff-split-divider { background: #30363d; }/* Split: unchanged */.oj-diff-light .oj-diff-split-unchanged { background: #ffffff; }.oj-diff-dark .oj-diff-split-unchanged { background: #0d1117; }.oj-diff-light .oj-diff-split-unchanged .oj-diff-ln-old,.oj-diff-light .oj-diff-split-unchanged .oj-diff-ln-new { color: #959da5; background: #f6f8fa; }.oj-diff-light .oj-diff-split-unchanged .oj-diff-content { color: #24292e; }.oj-diff-dark .oj-diff-split-unchanged .oj-diff-ln-old,.oj-diff-dark .oj-diff-split-unchanged .oj-diff-ln-new { color: #484f58; background: #161b22; }.oj-diff-dark .oj-diff-split-unchanged .oj-diff-content { color: #e6edf3; }/* Split: removed (left) */.oj-diff-light .oj-diff-split-removed { background: #ffeef0; }.oj-diff-light .oj-diff-split-removed .oj-diff-ln-old { color: #cb2431; background: #f8d7da; }.oj-diff-light .oj-diff-split-removed .oj-diff-marker { color: #cb2431; }.oj-diff-light .oj-diff-split-removed .oj-diff-content { color: #24292e; }.oj-diff-dark .oj-diff-split-removed { background: #3d1a1a; }.oj-diff-dark .oj-diff-split-removed .oj-diff-ln-old { color: #f85149; background: #4d2020; }.oj-diff-dark .oj-diff-split-removed .oj-diff-marker { color: #f85149; }.oj-diff-dark .oj-diff-split-removed .oj-diff-content { color: #e6edf3; }/* Split: added (right) */.oj-diff-light .oj-diff-split-added { background: #e6ffed; }.oj-diff-light .oj-diff-split-added .oj-diff-ln-new { color: #22863a; background: #cdffd8; }.oj-diff-light .oj-diff-split-added .oj-diff-marker { color: #22863a; }.oj-diff-light .oj-diff-split-added .oj-diff-content { color: #24292e; }.oj-diff-dark .oj-diff-split-added { background: #1b3a1f; }.oj-diff-dark .oj-diff-split-added .oj-diff-ln-new { color: #3fb950; background: #245028; }.oj-diff-dark .oj-diff-split-added .oj-diff-marker { color: #3fb950; }.oj-diff-dark .oj-diff-split-added .oj-diff-content { color: #e6edf3; }/* Split: empty side (placeholder) */.oj-diff-light .oj-diff-split-empty { background: #f6f8fa; }.oj-diff-dark .oj-diff-split-empty { background: #161b22; }.oj-diff-split-empty .oj-diff-content { opacity: 0; pointer-events: none; }/* Split: collapsed */.oj-diff-split-collapsed { align-items: center; cursor: pointer; user-select: none; }.oj-diff-split-collapsed-inner { display: block; width: 100%; padding: 4px 8px; font-size: 11px; font-family: sans-serif; }.oj-diff-light .oj-diff-split-collapsed { background: #f6f8fa; border-top: 1px dashed #d1d5da; border-bottom: 1px dashed #d1d5da; }.oj-diff-light .oj-diff-split-collapsed .oj-diff-split-collapsed-inner { color: #586069; }.oj-diff-light .oj-diff-split-collapsed:hover { background: #eaf1fb; }.oj-diff-light .oj-diff-split-collapsed:hover .oj-diff-split-collapsed-inner { color: #0366d6; }.oj-diff-dark .oj-diff-split-collapsed { background: #0d1117; border-top: 1px dashed #30363d; border-bottom: 1px dashed #30363d; }.oj-diff-dark .oj-diff-split-collapsed .oj-diff-split-collapsed-inner { color: #8b949e; }.oj-diff-dark .oj-diff-split-collapsed:hover { background: #161b22; }.oj-diff-dark .oj-diff-split-collapsed:hover .oj-diff-split-collapsed-inner { color: #58a6ff; }`);}// ======================== 初始化 ========================function init() {injectStyles();if (!CURRENT_PLATFORM) return;const recordId = ADAPTER.getRecordIdFromUrl();const onRecordPage = ADAPTER.isRecordPage();if (onRecordPage && recordId) {// 记录详情页——完整功能(各平台已根据自身能力裁剪按钮)let debounceTimer = null;function scheduleInject() {if (debounceTimer) clearTimeout(debounceTimer);debounceTimer = setTimeout(() => {injectCompareButton();injectInlineButton(recordId);}, 300);}const observer = new MutationObserver((mutations) => {let needReinject = false;for (const m of mutations) {for (const node of m.removedNodes) {if (node.nodeType === 1) {if (node.id === 'oj-diff-compare-btn' ||node.hasAttribute?.('data-oj-diff-injected') ||node.querySelector?.('[data-oj-diff-injected]')) {needReinject = true;break;}}}if (needReinject) break;}if (needReinject) { scheduleInject(); return; }const hasContent =document.querySelector('pre') ||document.querySelector('code') ||document.querySelector('.markdown-renderer') ||document.querySelector('#main-container');if (hasContent) scheduleInject();});observer.observe(document.body, { childList: true, subtree: true });setTimeout(() => {injectCompareButton();injectInlineButton(recordId);}, 800);// 监听主题变化(重新渲染浮动按钮颜色)new MutationObserver(() => {const btn = document.getElementById('oj-diff-compare-btn');if (btn) { btn.remove(); injectCompareButton(); }}).observe(document.documentElement, {attributes: true,attributeFilter: ['data-theme'],});} else {// 非 record 页面——通用浮动按钮setTimeout(() => injectUniversalButton(), 800);new MutationObserver(() => {const btn = document.getElementById('oj-diff-universal-btn');if (btn) { btn.remove(); injectUniversalButton(); }}).observe(document.documentElement, {attributes: true,attributeFilter: ['data-theme'],});}}if (document.body) {init();} else {document.addEventListener('DOMContentLoaded', init);}})();```:::