正文
增加 2053 行删除 1 行
123用 AI 做的,用于实现类似于 CF 的代码对比功能,不一定没有问题。请先[安装篡改猴](https://www.tampermonkey.net)再使用。(由于代码 $100\%$ 由 AI 生成,没敢放在公开推荐的“休闲·娱乐”或“科技·工程”区。)[剪切板链接](https://www.luogu.com.cn/paste/6r2bjn33)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055用 AI 做的,用于实现类似于 CF 的代码对比功能,不一定没有问题。请先[安装篡改猴](https://www.tampermonkey.net)再使用。(由于代码 $100\%$ 由 AI 生成,没敢放在公开推荐的“休闲·娱乐”或“科技·工程”区。):::info[代码(提示:目前 $2000$ 多行,约 $80$ KB)]```js// ==UserScript==// @name 洛谷代码对比// @namespace luogu-code-diff// @version 1.3.4// @description 洛谷代码对比工具,支持手动输入对比、提交记录 ID 对比、字体/行距/缩进调节、亮暗模式(全站可用)// @match https://www.luogu.com.cn/record/*// @match https://www.luogu.com.cn/recordlist*// @match https://www.luogu.com.cn/problem/*// @match https://www.luogu.com.cn/problemset*// @match https://www.luogu.com.cn/user/*// @match https://www.luogu.com.cn/discuss/*// @match https://www.luogu.com.cn/// @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)',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);}/** 弹出并显示上一个模态框,返回 true 表示有恢复 */function popAndRestore() {if (modalStack.length === 0) return false;const prev = modalStack.pop();prev.style.display = '';// 恢复焦点到代码区域(确保键盘可操作)const codeArea = prev.querySelector('.lg-diff-code');if (codeArea) codeArea.focus();return true;}/** 清空整个堆栈(最终关闭时用) */function clearModalStack() {modalStack.length = 0;}// ======================== 用户设置 ========================const SETTINGS_KEY = 'lg-diff-settings';const DEFAULT_SETTINGS = {fontSize: 13, // 字体大小 px(8~28)lineHeight: 1.5, // 行间距倍数(1.0~3.0,步进 0.1)tabSize: 4, // Tab 宽度(2 / 4 / 8)themeMode: 'auto', // 'auto' | 'light' | 'dark'collapseUnchanged: true, // 折叠连续未变更行};function loadSettings() {try {const raw = localStorage.getItem(SETTINGS_KEY);if (raw) return { ...DEFAULT_SETTINGS, ...JSON.parse(raw) };} catch (e) {console.warn('[洛谷代码对比] 读取设置失败:', e);}return { ...DEFAULT_SETTINGS };}function saveSettings(settings) {try {localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));} catch (e) {console.warn('[洛谷代码对比] 保存设置失败:', e);}}/*** 应用代码显示设置* 行高用绝对 px 值确保字号联动;tab-size 控制缩进宽度*/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('.lg-diff-ln-old, .lg-diff-ln-new').forEach(el => {el.style.fontSize = lnFs;el.style.lineHeight = lhPx;});}// ======================== 主题 ========================/** 根据 themeMode 判断当前是否暗色 */function isDarkMode(themeMode) {const mode = themeMode || loadSettings().themeMode;if (mode === 'dark') return true;if (mode === 'light') return false;// auto:跟随洛谷或系统return (document.documentElement.getAttribute('data-theme') === 'dark' ||document.body?.getAttribute('data-theme') === 'dark' ||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, '"');}function getRecordIdFromUrl() {const match = window.location.pathname.match(/\/record\/(\d+)/);return match ? match[1] : null;}/** 判断当前页面是否为记录详情页(有完整对比功能) */function isRecordPage() {return /^\/record\/\d+/.test(window.location.pathname);}function fetchLuogu(url) {const 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}`); });}function extractData(response) {if (response.code !== undefined && response.code !== 200)throw new Error(`洛谷返回错误码: ${response.code}`);if (response.currentData) return response.currentData;if (response.data) return response.data;if (response.record) return response;if (response.records) return response;throw new Error('无法从响应中提取数据');}// ======================== Diff 算法 ========================/*** 行级 LCS diff,返回 [{type, content}]* 性能保护:超过 3000 行时降级为逐行对比*/function lineDiff(oldLines, newLines) {const m = oldLines.length;const n = newLines.length;// 大文件保护:超过限制时直接标记全删全加if (m * n > 9000000) {console.warn('[洛谷代码对比] 文件过大,使用简化 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;}/*** 对 diff 结果应用"折叠连续未变更行"* 变更行附近 context 行保留,其余归为 collapsed 块* collapsed 块记录行号范围以便显示*/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; }}// 所有连续 unchanged 行全部折叠,不保留 contextconst 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 构建 ========================/*** 构建 diff 代码 HTML* @param {Array} diffs - diff 结果数组* @param {boolean} showFoldIcons - 是否在 unchanged 行左侧显示折叠图标*/function buildCodeHtml(diffs, showFoldIcons) {// 第一遍:计算每个 unchanged 行所属块的起始索引和总行数// blockInfo[i] = { blockStart: 块第一行索引, blockCount: 块总行数 }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;}}}// 第二遍:渲染 HTMLlet 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="lg-diff-line lg-diff-collapsed" data-count="' + diff.count + '">' +'<span class="lg-diff-fold-icon-placeholder"></span>' +'<span class="lg-diff-ln-old' + (hasLineInfo ? ' lg-diff-ln-collapsed' : '') + '">' + oldRange + '</span>' +'<span class="lg-diff-ln-new' + (hasLineInfo ? ' lg-diff-ln-collapsed' : '') + '">' + newRange + '</span>' +'<span class="lg-diff-marker lg-diff-marker-empty"></span>' +'<span class="lg-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 {// 无行号信息时,推进行号(假设都是 unchanged)oldLineNum += diff.count;newLineNum += diff.count;}continue;}if (diff.type === 'unchanged') {oldLineNum++; newLineNum++;const info = blockInfo.get(di);const foldIcon = info? '<span class="lg-diff-fold-icon" data-fold-start="' + info.blockStart + '" data-fold-count="' + info.blockCount + '" title="折叠 ' + info.blockCount + ' 行相同代码">⌃</span>': '<span class="lg-diff-fold-icon-placeholder"></span>';html +='<div class="lg-diff-line lg-diff-unchanged' + (info ? ' lg-diff-unchanged-foldable' : '') + '">' +foldIcon +'<span class="lg-diff-ln-old">' + oldLineNum + '</span>' +'<span class="lg-diff-ln-new">' + newLineNum + '</span>' +'<span class="lg-diff-marker lg-diff-marker-empty"></span>' +'<span class="lg-diff-content">' + escapeHtml(diff.content) + '</span>' +'</div>';} else if (diff.type === 'removed') {oldLineNum++;html +='<div class="lg-diff-line lg-diff-removed">' +'<span class="lg-diff-fold-icon-placeholder"></span>' +'<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++;html +='<div class="lg-diff-line lg-diff-added">' +'<span class="lg-diff-fold-icon-placeholder"></span>' +'<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>';}}return html;}// ======================== 加载遮罩 ========================function createLoadingOverlay(message) {const dark = isDarkMode();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;';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="lg-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:lg-diff-spin 0.8s linear infinite;' +'"></div>' +'<div id="lg-diff-loading-msg">' + escapeHtml(message) + '</div>' +'</div>';document.body.appendChild(overlay);return overlay;}function removeLoadingOverlay() {const el = document.getElementById('lg-diff-loading');if (el) el.remove();}function updateLoadingMessage(overlay, message) {const el = overlay.querySelector('#lg-diff-loading-msg');if (el) el.textContent = message;}// ======================== 主对比模态框 ========================/*** 渲染 Diff 模态框* @param {string} oldCode* @param {string} newCode* @param {string} oldLabel 左侧标签(记录 ID 或 "旧版本")* @param {string} newLabel 右侧标签(记录 ID 或 "新版本")* @param {string|null} oldUrl 旧侧链接(null = 无链接)* @param {string|null} newUrl 新侧链接* @param {string|null} currentRecordId 当前页面的提交记录 ID(用于"与上次提交对比"按钮)* @param {boolean} isPrevCompare 是否为"与上次提交对比"(为 true 时禁用该按钮)*/function showDiffModal(oldCode, newCode, oldLabel, newLabel, oldUrl, newUrl, currentRecordId, isPrevCompare) {const settings = loadSettings();const dark = isDarkMode(settings.themeMode);const C = getColors(dark);// 判断是否有有效的记录 ID(用于决定是否显示"与上次提交对比"等按钮)const hasRecordId = currentRecordId && String(currentRecordId).trim();// Diff 计算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 codeHtml = buildCodeHtml(displayDiffs, true);// 存储原始 diff 用于展开操作let expandedDiffs = rawDiffs;// ---- 构建 DOM ----const overlay = document.createElement('div');overlay.id = 'lg-diff-modal-overlay';const modal = document.createElement('div');modal.className = 'lg-diff-modal ' + (dark ? 'lg-diff-dark' : 'lg-diff-light');// ---- Header ----const header = document.createElement('div');header.className = 'lg-diff-header';// 标题const titleDiv = document.createElement('div');titleDiv.className = 'lg-diff-title';titleDiv.innerHTML = '<span class="lg-diff-title-icon">📋</span>代码对比';// ID 对比链接区const idsDiv = document.createElement('div');idsDiv.className = 'lg-diff-ids';const oldLinkHtml = oldUrl? '<a href="' + escapeHtml(oldUrl) + '" target="_blank" class="lg-diff-record-link old">#' + escapeHtml(oldLabel) + '</a>': '<span class="lg-diff-record-link old">' + escapeHtml(oldLabel) + '</span>';const newLinkHtml = newUrl? '<a href="' + escapeHtml(newUrl) + '" target="_blank" class="lg-diff-record-link new">#' + escapeHtml(newLabel) + '</a>': '<span class="lg-diff-record-link new">' + escapeHtml(newLabel) + '</span>';idsDiv.innerHTML = oldLinkHtml + '<span class="lg-diff-arrow">→</span>' + newLinkHtml;// 统计const statsDiv = document.createElement('div');statsDiv.className = 'lg-diff-stats';statsDiv.innerHTML ='<span class="lg-diff-stat-added">+' + addedCount + ' 行</span>' +'<span class="lg-diff-stat-removed">-' + removedCount + ' 行</span>' +'<span class="lg-diff-stat-unchanged">' + unchangedCount + ' 行未变更</span>';// 亮暗模式切换按钮——带文字标签,更易辨识const themeBtn = document.createElement('button');themeBtn.className = 'lg-diff-theme-btn';themeBtn.title = '切换亮/暗模式(当前:自动)';themeBtn.setAttribute('data-theme-mode', settings.themeMode);// 根据当前模式设置初始内容function updateThemeBtnContent(mode) {const LABELS = { auto: '🖥 自动', light: '☀️ 亮色', dark: '🌙 暗色' };themeBtn.innerHTML = '<span class="lg-diff-theme-icon"></span><span class="lg-diff-theme-label">' + LABELS[mode] + '</span>';themeBtn.title = '切换亮/暗模式(当前:' + LABELS[mode] + ')';// 更新按钮样式:当前模式的强调色themeBtn.classList.remove('lg-diff-theme-auto', 'lg-diff-theme-light', 'lg-diff-theme-dark');themeBtn.classList.add('lg-diff-theme-' + mode);}updateThemeBtnContent(settings.themeMode);// 关闭按钮const closeBtn = document.createElement('button');closeBtn.className = 'lg-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 = 'lg-diff-body';const codeArea = document.createElement('div');codeArea.className = 'lg-diff-code';codeArea.id = 'lg-diff-code-area';codeArea.innerHTML = codeHtml;body.appendChild(codeArea);// ---- Settings bar ----const settingsBar = document.createElement('div');settingsBar.className = 'lg-diff-settings-bar';settingsBar.innerHTML =// 字号'<span class="lg-diff-settings-label">字号</span>' +'<input type="range" class="lg-diff-slider" id="lg-diff-font-slider"' +' min="8" max="28" step="1" value="' + settings.fontSize + '" title="字体大小">' +'<span class="lg-diff-settings-value" id="lg-diff-font-value">' + settings.fontSize + 'px</span>' +'<span class="lg-diff-settings-divider">|</span>' +// 行距'<span class="lg-diff-settings-label">行距</span>' +'<input type="range" class="lg-diff-slider" id="lg-diff-lh-slider"' +' min="1.0" max="3.0" step="0.1" value="' + settings.lineHeight + '" title="行间距">' +'<span class="lg-diff-settings-value" id="lg-diff-lh-value">' + settings.lineHeight.toFixed(1) + 'x</span>' +'<span class="lg-diff-settings-divider">|</span>' +// 缩进(Tab 宽度)'<span class="lg-diff-settings-label">缩进</span>' +'<div class="lg-diff-tab-group" id="lg-diff-tab-group">' +[2, 4, 8].map(n =>'<button class="lg-diff-tab-btn' + (settings.tabSize === n ? ' active' : '') + '" data-tab="' + n + '">' + n + '</button>').join('') +'</div>' +'<span class="lg-diff-settings-divider">|</span>' +// 折叠未变更行——图标+文字按钮'<button class="lg-diff-collapse-toggle" id="lg-diff-collapse-btn" title="折叠/展开未变更行">' +'<span class="lg-diff-collapse-icon">📄</span>' +'<span class="lg-diff-collapse-label">未折叠</span>' +'</button>';// ---- Footer ----const footer = document.createElement('div');footer.className = 'lg-diff-footer';// 左侧工具按钮组const footerLeft = document.createElement('div');footerLeft.className = 'lg-diff-footer-left';// 根据是否有 currentRecordId 决定显示哪些按钮if (hasRecordId) {footerLeft.innerHTML ='<button class="lg-diff-btn lg-diff-btn-secondary" id="lg-diff-prev-compare"' + (isPrevCompare ? ' disabled title="当前已在与上次提交对比"' : ' title="与上一次提交记录对比"') + '>⇄ 与上次提交对比</button>' +'<button class="lg-diff-btn lg-diff-btn-secondary" id="lg-diff-manual-compare">✏️ 两份代码对比</button>' +'<button class="lg-diff-btn lg-diff-btn-secondary" id="lg-diff-custom-compare">🔢 与指定提交对比</button>' +'<button class="lg-diff-btn lg-diff-btn-secondary" id="lg-diff-record-compare">📋 两次提交记录对比</button>';} else {// 没有记录 ID 时,只显示通用按钮footerLeft.innerHTML ='<button class="lg-diff-btn lg-diff-btn-secondary" id="lg-diff-manual-compare">✏️ 两份代码对比</button>' +'<button class="lg-diff-btn lg-diff-btn-secondary" id="lg-diff-record-compare">📋 两次提交记录对比</button>';}// 右侧关闭const footerRight = document.createElement('div');footerRight.innerHTML ='<button class="lg-diff-btn lg-diff-btn-primary" id="lg-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('#lg-diff-font-slider');const fontValueEl = overlay.querySelector('#lg-diff-font-value');const lhSlider = overlay.querySelector('#lg-diff-lh-slider');const lhValueEl = overlay.querySelector('#lg-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);});// Tab 宽度按钮组overlay.querySelector('#lg-diff-tab-group').addEventListener('click', (e) => {const btn = e.target.closest('.lg-diff-tab-btn');if (!btn) return;const tab = parseInt(btn.dataset.tab, 10);currentSettings.tabSize = tab;overlay.querySelectorAll('.lg-diff-tab-btn').forEach(b => {b.classList.toggle('active', parseInt(b.dataset.tab, 10) === tab);});applyCodeSettings(codeArea, currentSettings);saveSettings(currentSettings);});// 折叠/展开切换——三态:完全不折叠 / 部分折叠 / 完全折叠const collapseBtn = overlay.querySelector('#lg-diff-collapse-btn');const collapseIcon = collapseBtn.querySelector('.lg-diff-collapse-icon');const collapseLabel = collapseBtn.querySelector('.lg-diff-collapse-label');// 判断当前折叠状态(纯内容判断,不依赖外部 flag)// 'none' = 没有 collapsed 块// 'full' = 有 collapsed 块,且没有任何 unchanged 行(全部折叠)// 'partial' = 有 collapsed 块,且还有 unchanged 行(部分折叠)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 = '点击:展开所有行';}}// 当前 diffs 引用,供各处更新图标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 = buildCodeHtml(newDiffs, true);applyCodeSettings(codeArea, currentSettings);bindCollapseButtons(codeArea, newDiffs, expandedDiffs, currentSettings);refreshCollapseIcon();});// 绑定展开按钮事件——点击某折叠块时,只展开该块对应的行function bindCollapseButtons(area, collapsedDiffs, allDiffs, s) {area.querySelectorAll('.lg-diff-collapsed-btn').forEach(btn => {btn.addEventListener('click', () => {const collapsedLine = btn.closest('.lg-diff-collapsed');const count = parseInt(collapsedLine.getAttribute('data-count'), 10);// 在 collapsedDiffs 中找到该折叠块的位置let collapsedIndex = -1;const allCollapsedLines = area.querySelectorAll('.lg-diff-collapsed');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);// 找到该折叠块在 allDiffs 中对应的原始行// 计算该折叠块之前的所有项覆盖了多少原始行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 = buildCodeHtml(newCollapsedDiffs, true);applyCodeSettings(area, s);bindCollapseButtons(area, newCollapsedDiffs, allDiffs, s);refreshCollapseIcon();});});// 绑定行内折叠图标——点击后将整块连续未变更行全部折叠area.querySelectorAll('.lg-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();// 验证这些位置确实都是 unchangedlet 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;const cNewStart = newNum + 1;const cOldEnd = cOldStart + foldCount - 1;const cNewEnd = cNewStart + foldCount - 1;// 整块全部折叠newDiffs.splice(foldStart, foldCount, {type: 'collapsed',count: foldCount,oldStart: cOldStart,oldEnd: cOldEnd,newStart: cNewStart,newEnd: cNewEnd,});currentDiffs = newDiffs;area.innerHTML = buildCodeHtml(newDiffs, true);applyCodeSettings(area, s);bindCollapseButtons(area, newDiffs, allDiffs, s);refreshCollapseIcon();});});}bindCollapseButtons(codeArea, displayDiffs, expandedDiffs, currentSettings);// 亮暗模式切换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);// 切换 modal 的亮/暗 classconst newDark = isDarkMode(next);modal.classList.toggle('lg-diff-dark', newDark);modal.classList.toggle('lg-diff-light', !newDark);});// 关闭——区分"最终关闭"和"返回上级对话框"const closeFinal = () => { clearModalStack(); overlay.remove(); };const closeBack = () => {overlay.remove();popAndRestore(); // 尝试恢复上一级};// 如果有上级模态框,✕ 按钮和 ESC 执行"返回上级"而非"彻底关闭"const hasParent = modalStack.length > 0;closeBtn.addEventListener('click', closeBack);overlay.querySelector('#lg-diff-close-btn').addEventListener('click', closeBack);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('#lg-diff-close-btn').textContent = '返回';}// 根据是否有 currentRecordId 决定绑定哪些按钮的事件if (hasRecordId) {// 与上次提交对比——先隐藏当前模态框(压栈)if (!isPrevCompare) {overlay.querySelector('#lg-diff-prev-compare').addEventListener('click', () => {pushAndHide(overlay);runCompare(currentRecordId, null);});}// 对比其他提交——先隐藏当前模态框(压栈)overlay.querySelector('#lg-diff-custom-compare').addEventListener('click', () => {pushAndHide(overlay);promptCustomCompare(currentRecordId);});}// 手动输入对比——先隐藏当前模态框(压栈)overlay.querySelector('#lg-diff-manual-compare').addEventListener('click', () => {pushAndHide(overlay);showManualInputDialog();});// 对比两份提交记录——先隐藏当前模态框(压栈)overlay.querySelector('#lg-diff-record-compare').addEventListener('click', () => {pushAndHide(overlay);showRecordCompareDialog();});}// ======================== 手动输入对比对话框 ========================function showManualInputDialog() {const existing = document.getElementById('lg-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 = 'lg-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="lg-diff-modal ' + (dark ? 'lg-diff-dark' : 'lg-diff-light') + '" style="max-width:860px;width:92vw;">' +'<div class="lg-diff-header">' +'<div class="lg-diff-title"><span class="lg-diff-title-icon">✏️</span>手动输入代码对比</div>' +'<button class="lg-diff-close" title="关闭">✕</button>' +'</div>' +'<div class="lg-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="lg-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="lg-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="lg-diff-footer">' +'<div class="lg-diff-footer-left">' +'<button class="lg-diff-btn lg-diff-btn-secondary" id="lg-diff-manual-cancel">取消</button>' +'<button class="lg-diff-btn lg-diff-btn-secondary" id="lg-diff-manual-clear" title="清空两个输入框">🗑 清空</button>' +'</div>' +'<button class="lg-diff-btn lg-diff-btn-primary" id="lg-diff-manual-ok">开始对比</button>' +'</div>' +'</div>';document.body.appendChild(dialog);const close = () => { dialog.remove(); popAndRestore(); };dialog.querySelector('.lg-diff-close').addEventListener('click', close);dialog.querySelector('#lg-diff-manual-cancel').addEventListener('click', close);dialog.addEventListener('click', (e) => { if (e.target === dialog) close(); });dialog.querySelector('#lg-diff-manual-clear').addEventListener('click', () => {dialog.querySelector('#lg-diff-manual-old').value = '';dialog.querySelector('#lg-diff-manual-new').value = '';dialog.querySelector('#lg-diff-manual-old').focus();});const doCompare = () => {const oldCode = dialog.querySelector('#lg-diff-manual-old').value;const newCode = dialog.querySelector('#lg-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('#lg-diff-manual-ok').addEventListener('click', doCompare);// Ctrl+Enter 快捷键触发对比dialog.addEventListener('keydown', (e) => {if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) doCompare();if (e.key === 'Escape') close();});// ✕ 按钮改为"返回"(如果有上级模态框)const xBtn = dialog.querySelector('.lg-diff-close');if (modalStack.length > 0) {xBtn.title = '返回上级';xBtn.textContent = '←';}// Tab 在 textarea 中插入空格而不是跳出[dialog.querySelector('#lg-diff-manual-old'), dialog.querySelector('#lg-diff-manual-new')].forEach(ta => {ta.addEventListener('keydown', (e) => {if (e.key === 'Tab') {e.preventDefault();const start = ta.selectionStart;const end = ta.selectionEnd;ta.value = ta.value.slice(0, start) + ' ' + ta.value.slice(end);ta.selectionStart = ta.selectionEnd = start + 4;}});});// 自动聚焦到旧版本输入框setTimeout(() => dialog.querySelector('#lg-diff-manual-old').focus(), 50);}// ======================== 自定义 ID 对比对话框 ========================function promptCustomCompare(currentRecordId) {const existing = document.getElementById('lg-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 = 'lg-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="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:' + C.textSecondary + ';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 ' + C.inputBorder + ';' +'background:' + C.inputBg + ';color:' + C.textPrimary + ';' +'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">' +'<div class="lg-diff-footer-left">' +'<button class="lg-diff-btn lg-diff-btn-secondary" id="lg-diff-custom-cancel">取消</button>' +'</div>' +'<button class="lg-diff-btn lg-diff-btn-primary" id="lg-diff-custom-ok">开始对比</button>' +'</div>' +'</div>';document.body.appendChild(dialog);const close = () => { dialog.remove(); popAndRestore(); };dialog.querySelector('.lg-diff-close').addEventListener('click', close);dialog.querySelector('#lg-diff-custom-cancel').addEventListener('click', close);dialog.addEventListener('click', (e) => { if (e.target === dialog) close(); });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;}dialog.remove();// 关闭父级对比模态框(如果有的话),开始新的对比const parent = modalStack.length > 0 ? modalStack[modalStack.length - 1] : null;if (parent) { parent.remove(); modalStack.pop(); }await runCompare(currentRecordId, targetId);};dialog.querySelector('#lg-diff-custom-ok').addEventListener('click', doCompare);input.addEventListener('keydown', (e) => { if (e.key === 'Enter') doCompare(); });// ✕ 按钮改为"返回"(如果有上级模态框)const xBtn = dialog.querySelector('.lg-diff-close');if (modalStack.length > 0) {xBtn.title = '返回上级';xBtn.textContent = '←';}}// ======================== 对比两份提交记录对话框 ========================function showRecordCompareDialog() {const existing = document.getElementById('lg-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 = 'lg-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="lg-diff-modal ' + (dark ? 'lg-diff-dark' : 'lg-diff-light') + '" style="max-width:560px;">' +'<div class="lg-diff-header">' +'<div class="lg-diff-title"><span class="lg-diff-title-icon">🔢</span>对比两份提交记录</div>' +'<button class="lg-diff-close" title="关闭">✕</button>' +'</div>' +'<div class="lg-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="lg-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="lg-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="lg-diff-rcmp-error" style="color:#cb2431;font-size:13px;display:none;"></div>' +'</div>' +'<div class="lg-diff-footer">' +'<div class="lg-diff-footer-left">' +'<button class="lg-diff-btn lg-diff-btn-secondary" id="lg-diff-rcmp-cancel">取消</button>' +'</div>' +'<button class="lg-diff-btn lg-diff-btn-primary" id="lg-diff-rcmp-ok">开始对比</button>' +'</div>' +'</div>';document.body.appendChild(dialog);const close = () => { dialog.remove(); popAndRestore(); };dialog.querySelector('.lg-diff-close').addEventListener('click', close);dialog.querySelector('#lg-diff-rcmp-cancel').addEventListener('click', close);dialog.addEventListener('click', (e) => { if (e.target === dialog) close(); });const oldInput = dialog.querySelector('#lg-diff-rcmp-old-id');const newInput = dialog.querySelector('#lg-diff-rcmp-new-id');// ✕ 按钮改为"返回"(如果有上级模态框)const xBtn = dialog.querySelector('.lg-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('#lg-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('#lg-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);}/** 根据两份提交记录 ID 获取代码并对比 */async function runRecordCompare(oldId, newId) {const loading = createLoadingOverlay('正在获取代码,请稍候...');try {updateLoadingMessage(loading, '正在获取旧版本提交 #' + oldId + ' ...');const oldRecord = await fetchRecordDetail(oldId);updateLoadingMessage(loading, '正在获取新版本提交 #' + newId + ' ...');const newRecord = await fetchRecordDetail(newId);if (!oldRecord.sourceCode && oldRecord.sourceCode !== '')throw new Error('旧版本提交 #' + oldId + ' 的代码不可访问');if (!newRecord.sourceCode && newRecord.sourceCode !== '')throw new Error('新版本提交 #' + newId + ' 的代码不可访问');removeLoadingOverlay();showDiffModal(String(oldRecord.sourceCode ?? ''),String(newRecord.sourceCode ?? ''),String(oldId),String(newId),LUOGU_BASE + '/record/' + oldId,LUOGU_BASE + '/record/' + newId,getRecordIdFromUrl(),false);} catch (err) {removeLoadingOverlay();showToast(err.message, 'error');}}// ======================== 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);}// ======================== 核心逻辑 ========================async function fetchRecordDetail(recordId) {const url = `${LUOGU_BASE}/record/${recordId}`;const response = await fetchLuogu(url);const data = extractData(response);if (!data.record) throw new Error('无法获取记录信息(response 中缺少 record 字段)');return data.record;}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);const data = extractData(response);let records = data.records;if (Array.isArray(records)) return records;if (records && typeof records === 'object') {if (Array.isArray(records.result)) return records.result;if (Array.isArray(records.records)) return records.records;if (Array.isArray(records.values)) return records.values;if (Array.isArray(records.data)) return records.data;}return [];}async function findPrevRecord(currentRecordId, pid, uid) {for (let page = 1; page <= 2; page++) {const records = await fetchRecordList({ pid, user: String(uid), page });const idx = records.findIndex(r => String(r.id) === String(currentRecordId));if (idx !== -1) {if (idx + 1 < records.length) return records[idx + 1];continue;}for (const r of records) {if (String(r.id) !== String(currentRecordId)) return r;}}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;if (targetRecordId) {if (!currentRecord) {updateLoadingMessage(loading, '正在获取当前提交代码...');currentRecord = await fetchRecordDetail(currentRecordId);}updateLoadingMessage(loading, '正在获取对比提交代码...');targetRecord = await fetchRecordDetail(targetRecordId);} else {if (!currentRecord) {updateLoadingMessage(loading, '正在获取当前提交信息...');currentRecord = await fetchRecordDetail(currentRecordId);}const problem = currentRecord.problem;const pid =problem?.pid || problem?.id || problem?.problemId ||(typeof problem === 'string' ? problem : null);const uid = currentRecord.user?.uid || currentRecord.uid;if (!pid) throw new Error('无法获取题目 ID(problem 字段缺失)');if (!uid) throw new Error('无法获取用户信息(可能需要登录)');updateLoadingMessage(loading, '正在查找上一次提交记录...');const prevBase = await findPrevRecord(currentRecordId, pid, uid);updateLoadingMessage(loading, '正在获取上一次提交代码...');targetRecord = await fetchRecordDetail(prevBase.id);}if (!currentRecord.sourceCode && currentRecord.sourceCode !== '')throw new Error('当前提交的代码不可访问(可能是隐私设置)');if (!targetRecord.sourceCode && targetRecord.sourceCode !== '')throw new Error('对比提交的代码不可访问(可能是隐私设置)');removeLoadingOverlay();showDiffModal(String(targetRecord.sourceCode ?? ''),String(currentRecord.sourceCode ?? ''),String(targetRecord.id),String(currentRecord.id),LUOGU_BASE + '/record/' + targetRecord.id,LUOGU_BASE + '/record/' + currentRecord.id,String(currentRecordId),!targetRecordId // isPrevCompare:targetRecordId 为 null 时即为"与上次提交对比");} catch (err) {removeLoadingOverlay();showToast(err.message, 'error');}}// ======================== 按钮注入 ========================function injectCompareButton() {if (document.getElementById('lg-diff-compare-btn')) return;const recordId = getRecordIdFromUrl();if (!recordId) return;const btn = document.createElement('button');btn.id = 'lg-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', () => {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', () => showFloatingMenu(recordId));document.body.appendChild(btn);}/** 点击浮动按钮后显示快捷菜单 */function showFloatingMenu(recordId) {const existing = document.getElementById('lg-diff-float-menu');if (existing) { existing.remove(); return; }const dark = isDarkMode();const C = getColors(dark);const menu = document.createElement('div');menu.id = 'lg-diff-float-menu';menu.style.cssText ='position:fixed;z-index:100001;' +'bottom:72px;right:24px;' +'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:220px;';const items = [{ text: '⇄ 与上次提交记录对比', action: () => runCompare(recordId, null) },{ text: '🔢 与指定提交记录对比', action: () => promptCustomCompare(recordId) },{ text: '✏️ 两份代码对比', action: () => showManualInputDialog() },{ text: '📋 两次提交记录对比', action: () => showRecordCompareDialog() },];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 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-lg-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-lg-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 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());container.appendChild(b1);container.appendChild(b2);container.appendChild(b3);container.appendChild(b4);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,#lg-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);}.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; color: #24292e; }.lg-diff-modal.lg-diff-dark { background: #161b22; color: #e6edf3; }/* Header */.lg-diff-header {display: flex;align-items: center;gap: 12px;padding: 14px 20px;border-bottom: 1px solid;flex-shrink: 0;flex-wrap: wrap;}.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: 17px; font-weight: 700;display: flex; align-items: center; gap: 8px;flex-shrink: 0;}.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;}a.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: 10px;font-size: 12px; font-weight: 600; flex-wrap: wrap;}.lg-diff-stat-added { color: #22863a; }.lg-diff-stat-removed { color: #cb2431; }.lg-diff-stat-unchanged{ color: #959da5; }.lg-diff-dark .lg-diff-stat-added { color: #3fb950; }.lg-diff-dark .lg-diff-stat-removed { color: #f85149; }.lg-diff-dark .lg-diff-stat-unchanged{ color: #484f58; }/* 亮/暗主题切换按钮——带标签,更易辨识 */.lg-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;}.lg-diff-theme-icon { font-size: 14px; line-height: 1; }.lg-diff-theme-label { font-size: 11px; }/* 亮色模式下主题按钮样式 */.lg-diff-light .lg-diff-theme-btn {background: #ffffff; color: #586069; border-color: #d1d5da;}.lg-diff-light .lg-diff-theme-btn:hover { background: #f3f4f6; border-color: #667eea; color: #667eea; }.lg-diff-light .lg-diff-theme-btn.lg-diff-theme-auto { border-color: #959da5; }.lg-diff-light .lg-diff-theme-btn.lg-diff-theme-light { border-color: #e8a317; color: #e8a317; background: #fffbe6; }.lg-diff-light .lg-diff-theme-btn.lg-diff-theme-dark { border-color: #6e7781; color: #6e7781; background: #f0f0f0; }/* 暗色模式下主题按钮样式 */.lg-diff-dark .lg-diff-theme-btn {background: #21262d; color: #8b949e; border-color: #30363d;}.lg-diff-dark .lg-diff-theme-btn:hover { background: #30363d; border-color: #667eea; color: #667eea; }.lg-diff-dark .lg-diff-theme-btn.lg-diff-theme-auto { border-color: #484f58; }.lg-diff-dark .lg-diff-theme-btn.lg-diff-theme-light { border-color: #e8a317; color: #e8a317; background: #2a2300; }.lg-diff-dark .lg-diff-theme-btn.lg-diff-theme-dark { border-color: #8b949e; color: #c9d1d9; background: #21262d; }.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; flex-shrink: 0;}.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;font-variant-ligatures: none;font-feature-settings: "liga" 0, "calt" 0;white-space: pre;tab-size: 4;-moz-tab-size: 4;}.lg-diff-line {display: flex;align-items: stretch;}.lg-diff-ln-old,.lg-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;}.lg-diff-marker {display: inline-block;width: 1.5em; min-width: 1.5em;text-align: center;user-select: none;font-weight: 700;flex-shrink: 0;}.lg-diff-marker-empty {display: inline-block;width: 1.5em; min-width: 1.5em;flex-shrink: 0;}.lg-diff-content {flex: 1;white-space: pre;padding-left: 4px;min-width: 0;}/* 折叠行 */.lg-diff-collapsed {cursor: pointer;user-select: none;}.lg-diff-ln-collapsed {font-style: italic; opacity: 0.6; font-size: 10px;}.lg-diff-collapsed-btn {display: block;width: 100%;padding: 4px 16px;font-size: 11px;font-family: sans-serif;text-align: center;transition: background 0.2s;}.lg-diff-light .lg-diff-collapsed-btn {color: #586069; background: #f6f8fa;border-top: 1px dashed #d1d5da;border-bottom: 1px dashed #d1d5da;}.lg-diff-light .lg-diff-collapsed-btn:hover { background: #eaf1fb; color: #0366d6; }.lg-diff-dark .lg-diff-collapsed-btn {color: #8b949e; background: #0d1117;border-top: 1px dashed #30363d;border-bottom: 1px dashed #30363d;}.lg-diff-dark .lg-diff-collapsed-btn:hover { background: #161b22; color: #58a6ff; }/* 未变更行 */.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: 10px;padding: 8px 20px; border-top: 1px solid; flex-shrink: 0;flex-wrap: wrap;}.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; flex-shrink: 0;}.lg-diff-light .lg-diff-settings-label { color: #586069; }.lg-diff-dark .lg-diff-settings-label { color: #8b949e; }/* 滑块样式 */.lg-diff-slider {-webkit-appearance: none;appearance: none;height: 4px;border-radius: 4px;outline: none;cursor: pointer;width: 90px;flex-shrink: 0;}.lg-diff-light .lg-diff-slider { background: #d1d5da; }.lg-diff-dark .lg-diff-slider { background: #30363d; }.lg-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;}.lg-diff-slider::-webkit-slider-thumb:hover { transform: scale(1.2); }.lg-diff-slider::-moz-range-thumb {width: 14px; height: 14px;border-radius: 50%;background: #667eea;cursor: pointer;border: none;}.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; }/* Tab 宽度按钮组 */.lg-diff-tab-group {display: flex; gap: 2px; border-radius: 6px; overflow: hidden;border: 1px solid; flex-shrink: 0;}.lg-diff-light .lg-diff-tab-group { border-color: #d1d5da; }.lg-diff-dark .lg-diff-tab-group { border-color: #30363d; }.lg-diff-tab-btn {padding: 3px 9px; font-size: 12px; border: none;cursor: pointer; transition: all 0.15s; font-weight: 600;background: transparent;}.lg-diff-light .lg-diff-tab-btn { color: #586069; }.lg-diff-light .lg-diff-tab-btn:hover { background: #e8f0fe; color: #667eea; }.lg-diff-light .lg-diff-tab-btn.active { background: #667eea; color: #fff; }.lg-diff-dark .lg-diff-tab-btn { color: #8b949e; }.lg-diff-dark .lg-diff-tab-btn:hover { background: #21262d; color: #667eea; }.lg-diff-dark .lg-diff-tab-btn.active { background: #667eea; color: #fff; }/* 折叠切换按钮(设置栏图标——三态) */.lg-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;}.lg-diff-collapse-icon { font-size: 14px; line-height: 1; }.lg-diff-collapse-label { font-size: 11px; line-height: 1; }.lg-diff-light .lg-diff-collapse-toggle { color: #586069; border-color: #d1d5da; }.lg-diff-light .lg-diff-collapse-toggle:hover { background: #f3f4f6; border-color: #667eea; color: #667eea; }.lg-diff-light .lg-diff-collapse-toggle.active { border-color: #667eea; color: #667eea; background: #eaf1fb; }.lg-diff-light .lg-diff-collapse-toggle.partial { border-color: #e8a317; color: #b08800; background: #fff8e1; }.lg-diff-dark .lg-diff-collapse-toggle { color: #8b949e; border-color: #30363d; }.lg-diff-dark .lg-diff-collapse-toggle:hover { background: #21262d; border-color: #667eea; color: #667eea; }.lg-diff-dark .lg-diff-collapse-toggle.active { border-color: #667eea; color: #667eea; background: #1a2332; }.lg-diff-dark .lg-diff-collapse-toggle.partial { border-color: #d29922; color: #d29922; background: #261e0a; }/* 行内折叠图标(代码左侧) */.lg-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;}.lg-diff-unchanged:hover .lg-diff-fold-icon,.lg-diff-unchanged-foldable .lg-diff-fold-icon {opacity: 0.5;}.lg-diff-fold-icon:hover {opacity: 1 !important;transform: scale(1.2);}.lg-diff-light .lg-diff-fold-icon { color: #586069; }.lg-diff-light .lg-diff-fold-icon:hover { color: #667eea; background: #e8eafc; }.lg-diff-dark .lg-diff-fold-icon { color: #8b949e; }.lg-diff-dark .lg-diff-fold-icon:hover { color: #79c0ff; background: #1c2d41; }.lg-diff-fold-icon-placeholder {display: inline-block; vertical-align: middle;width: 12px; min-width: 12px; flex-shrink: 0;}/* 折叠复选框(已废弃,保留以防回退) */.lg-diff-toggle-label {display: flex; align-items: center; gap: 5px;font-size: 12px; cursor: pointer; user-select: none;flex-shrink: 0;}.lg-diff-light .lg-diff-toggle-label { color: #586069; }.lg-diff-dark .lg-diff-toggle-label { color: #8b949e; }.lg-diff-toggle-label input[type=checkbox] { cursor: pointer; accent-color: #667eea; }/* 底部 */.lg-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;}.lg-diff-light .lg-diff-footer { border-color: #e1e4e8; background: #f6f8fa; }.lg-diff-dark .lg-diff-footer { border-color: #30363d; background: #0d1117; }.lg-diff-footer-left { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }.lg-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;}.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; }.lg-diff-btn-secondary:disabled { opacity: 0.4; cursor: not-allowed; }`);}// ======================== 初始化 ========================/*** 在非 record 页面注入通用浮动按钮(只提供手动输入对比和记录 ID 对比)*/function injectUniversalButton() {if (document.getElementById('lg-diff-universal-btn')) return;const dark = isDarkMode();const C = getColors(dark);const btn = document.createElement('button');btn.id = 'lg-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', () => {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', () => showUniversalMenu(btn));document.body.appendChild(btn);}/** 通用浮动按钮点击后弹出快捷菜单 */function showUniversalMenu(anchor) {const existing = document.getElementById('lg-diff-universal-menu');if (existing) { existing.remove(); return; }const dark = isDarkMode();const C = getColors(dark);const menu = document.createElement('div');menu.id = 'lg-diff-universal-menu';menu.style.cssText ='position:fixed;z-index:100001;' +'bottom:72px;right:24px;' +'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:200px;';const items = [{ text: '✏️ 两份代码对比', action: () => showManualInputDialog() },{ text: '📋 两次提交记录对比', action: () => showRecordCompareDialog() },];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 outsideClick = (e) => {if (!menu.contains(e.target)) { menu.remove(); document.removeEventListener('click', outsideClick); }};setTimeout(() => document.addEventListener('click', outsideClick), 0);}function init() {injectStyles();const recordId = getRecordIdFromUrl();const onRecordPage = isRecordPage();if (onRecordPage && recordId) {// record 详情页——完整功能(浮动按钮 + 行内按钮)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 === 'lg-diff-compare-btn' ||node.hasAttribute?.('data-lg-diff-injected') ||node.querySelector?.('[data-lg-diff-injected]')) {needReinject = true;break;}}}if (needReinject) break;}if (needReinject) { scheduleInject(); return; }const hasContent =document.querySelector('pre') ||document.querySelector('code') ||document.querySelector('.markdown-renderer');if (hasContent) scheduleInject();});observer.observe(document.body, { childList: true, subtree: true });setTimeout(() => {injectCompareButton();injectInlineButton(recordId);}, 800);new MutationObserver(() => {const btn = document.getElementById('lg-diff-compare-btn');if (btn) { btn.remove(); injectCompareButton(); }}).observe(document.documentElement, {attributes: true,attributeFilter: ['data-theme'],});} else {// 非 record 页面——通用浮动按钮(手动输入对比 + 记录 ID 对比)setTimeout(() => injectUniversalButton(), 800);new MutationObserver(() => {const btn = document.getElementById('lg-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);}})();```:::