版本比较
OJ 代码对比器 2.2.1(插件)
标题
增加 1 行删除 1 行
11洛谷代码对比器 1.0OJ 代码对比器 2.2.1(插件)正文
增加 2171 行删除 1076 行
12312345678910111256789101314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575822596025262728293031323334353637616263646566676869707140414243444546474849505152727374757677787980818283568485868788899091929394959697989910010110210358104105606110610710810911011111211364114115116686970711171187311912012112212378124125126127831281291301318713213390919293949596134135136137138139140141142143144145146100147148149150151152102103104105106107108153154155156157158159160161162163111112113164165166167116168169170171172173174175176177178126127128129179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249132133250251252253254135136137138139255256257258259260261262263264265141142143144145146147148149150151152153154155266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299159160161300301302163164165166167303304305306307169170308309172173310311312313175176314315316317318319178179320321322323181182324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681187188189190682683684685195196197198686687688689690691692693694695696203204205206207697698699700701702211212213214215216703704705706219220221707708709223710711712226713714715716717718231232233719720721236722723238239240724725726727242243244245246247248249250251252253254728729730731732733734257258259260261262263735736737265266738739740269741742743273744745746275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304747748749750751752753754755306307308309756757758759760761762763764765766767768769770771772773774775776777778312313314315779780317318319320781782783784785786787788789790791792793794795796797798799800322323801802803804327805806807808809810811812813814815816817818819820821822823824825826827828829830831832329330331332333334833834835836837838839840841842843844845846847848849338339340341342850851852853854855856857346347348349350858859860861862863864865866867868869870355356357871872359873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910103621011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610373643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014021038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118940640711901191410119211934134144154164174181194119511961197119811994204211200120112021203120412051206427428429120712081209121012111212121343443543612141215121612171218121912201221122212231224122544144244344412261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612774484494504514524531278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140245645745845914031404140514061407140814091410141114121413141414151416462141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814394644654664671440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147747247347414781479148014811482148347747814841485148614871488481482483484485486487488489490491492493494495496497498499500501502503504505506148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533510511512513514153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626517162716281629163016311632523163316341635163616375281638163916401641164216435325335345351644164516461647164816491650538165116525405415425435445455465475481653165416551656550551552553554165716581659166055655716611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707559560561562563564565566567568170817095705715725731710171117121713171457517151716171757757857958058117181719172058358458558617211722172317241725588589590591592172617271728172917305945955965971731173217331734173559960060160260360460560617361737173817391740174117426086096101743174417451746174717481749613614615616617618175017516201752175317541755175617571758175917601761176217631764176517661767176817691770177162262362462562662762862917721773631632633634635636637638639640641177417751776177717781779178017811782643178317841785178617871788178917901791179217931794179517961797179817991800180164618021803180464918051806180718086546556566576586596601809662663664665181018111812666667181366918141815671672181618171818181918201821182267418231824676677678679680681682683684685686687688689690691182569369418261827696182818291830699700701702703704705183118321833183418351836708709183771171271371418381839184018411842184318441845184618477181848184918501851722723724725726727728729730731732733734735736737738739740741742743744745746747748185218537511854753754755756185518561857185875976076176276376476576676776876977077177277377477577677777877978078178278318597857867877887897907917927937947957967977987998008018028038048058068078081860186118621863186418651866186718681869187018718108111872187318741875187681481518771878187981781881982082182282382482582682782818801881188218831884831832188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194883519498371950195119521953195419551956842843844195719581959846847848849850851852853854855856857858859860861862863864865866867868869196019611962196319641965196619671968196919701971197287187287387487587687787887988088188288388488588688788888919731974891892197519761977197819791980198119821983198419851986198719881989894199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091905906907908209220939109119129139149159169179182094209520962097209820992100210192292392492592692792892993021022103210421052106210721082109211093493521112112211321142115211621172118211993893994021202121212221232124942943944945946947948949212521269519529532127212821292130213121322133213421352136956957958959213721389619629639649659669672139214021412142214321442145214696997097197297321472148214921502151215221532154215521569769779789799809812157215821592160216121622163216421652166216798398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210332168216921702171217210362173217421752176217721782179103910401041218021812182104310441045104610471048104910501051105210531054105510561057105810591060106110622183218410641065106621852186218721882189219010691070107110721073219121921075107610771078107910801081108210831084219321942195219621972198108710881089109010911092109310942199220022011096109710981099110022022203110211031104110522042205220622072208220922102211221211071108110911101111221322142215221622172218111311141115221922202221222222232224222522262227222822292230111711181119112011212231223222332234223522362237223822392240224122421123112422432244224522462247224822492250225111271128112911302252225322542255113211331134225622572258225922601136113711382261226222632264226522662267226822691141114211432270227122722273114511461147227422752276114911501151227722782279228022812282228322842285228622872288115311541155228922902291229222932294229522962297229822992300230123022303230423052306230723082309231011581159231123122313231423152316231723182319232023212322232323242325116211631164232623271166116723282329233023312332233323342335233611701171117223372338233923402341234223432344234523462347234823491175117611772350235123522353235423552356235723582359236023612362236323642365236623671180118111822368236923701184118511862371237223732374118811892375237623772378237923802381238223832384119211931194238523862387238811961197119811992389239023912392239323942395239623972398120112021203239924002401240224032404240524062407240812051206120724092410241124122413241424152416241724181209121012112419242024212422242312131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367242424252426242724282429243024312432243324342435243624372438243924402441244213761377137813792443244413811382138313841385244524462447244824492450245124522453245424552456245713872458138913901391139213931394139513961397245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248313991400140124841403140414051406140714082485248624872488141014112489249024912492249324942495141314141415141624962497249824992500250125022503250425052506250725082509251025112512251314192514251525162517251825191426252025212522用 AI 做的,用于实现类似于 CF 的代码对比功能,不一定没有问题。请先安装篡改猴再使用。~~链接自己去搜。~~:::info[提示:请不要随意展开,这玩意 $41$ KB,$1.4$k 行]``````本插件是用 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 洛谷代码对比// @namespace luogu-code-diff// @version 1.3.0// @description 在洛谷记录详情页添加代码对比功能// @match https://www.luogu.com.cn/record/*// @match https://www.luogu.com.cn/recordlist*// @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 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)', 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)', 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 = 'lg-diff-settings'; const SETTINGS_KEY = 'oj-diff-settings'; const DEFAULT_SETTINGS = { fontSize: 13, // 字体大小 px lineHeight: 1.5, // 行间距倍数(1.5 = 1行代码 + 0.5行空行) 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) { const parsed = JSON.parse(raw); return { ...DEFAULT_SETTINGS, ...parsed }; } if (raw) return { ...DEFAULT_SETTINGS, ...JSON.parse(raw) }; } catch (e) { console.warn('[洛谷代码对比] 读取设置失败:', e); console.warn('[OJ代码对比] 读取设置失败:', e); } return { ...DEFAULT_SETTINGS }; }
/** 保存用户设置 */ function saveSettings(settings) { try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings)); } catch (e) { console.warn('[洛谷代码对比] 保存设置失败:', e); console.warn('[OJ代码对比] 保存设置失败:', 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); 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; /** 判断当前是否为暗色模式 */ function isDarkMode() { return ( document.documentElement.getAttribute('data-theme') === 'dark' || document.body?.getAttribute('data-theme') === 'dark' || window.matchMedia('(prefers-color-scheme: dark)').matches ); // 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() { return isDarkMode() ? COLORS.dark : COLORS.light; function getColors(dark) { return dark ? 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; /** 让浮动按钮可拖动(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); }); }
/** 发起洛谷 API 请求(同源 fetch,自动携带 Cookie) * 使用 _contentOnly 参数让洛谷返回 JSON 数据而非 HTML
/** * GM_xmlhttpRequest 封装(用于跨域请求) * 同源请求优先用 fetch(支持 cookies),跨域回退到 GM_xmlhttpRequest */ function fetchLuogu(url) { // 构建带 _contentOnly 参数的 URL const fullUrl = url.startsWith('http') ? url : LUOGU_BASE + url; const separator = fullUrl.includes('?') ? '&' : '?'; const jsonUrl = `${fullUrl}${separator}_contentOnly=1`; 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; }
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}`); 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_xmlhttpRequest return 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 请求超时')); }, }); }); }
/** 从洛谷页面响应中提取数据 * 洛谷 _contentOnly 返回格式: * { code: 200, currentData: {...}, currentTemplate: "...", currentUser: {...} } /** * 解析 HTML 字符串为 DOM Document(用于从页面中提取数据) */ function extractData(response) { // 检查返回码 if (response.code !== undefined && response.code !== 200) { throw new Error(`洛谷返回错误码: ${response.code}`); } function parseHtml(htmlStr) { const parser = new DOMParser(); return parser.parseFromString(htmlStr, 'text/html'); }
// _contentOnly 格式:数据在 currentData 中 if (response.currentData) return response.currentData; // ======================== 各平台 Adapter ========================
// Lentille 格式:数据在 data 中 if (response.data) return response.data; // ---------- Luogu Adapter ---------- const LuoguAdapter = { platform: PLATFORMS.LUOGU,
// 记录详情可能直接在顶层 if (response.record) return response; /** 从 URL 中提取记录 ID */ getRecordIdFromUrl() { const match = window.location.pathname.match(/\/record\/(\d+)/); return match ? match[1] : null; },
// 记录列表的 records 字段 if (response.records) return response; isRecordPage() { return /^\/record\/\d+/.test(window.location.pathname); },
console.log('[洛谷代码对比] 未识别的响应格式:', response); throw new Error('无法从响应中提取数据'); 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 和用户 ID const 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/67890 const 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 的 contestId const 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 里的 contestId if (!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 构建精确 URL const 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 选择 adapter function 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 算法 ========================
/** * 基于行级的 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); 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++) { 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]); } 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]); } }
// 回溯 diff 结果 const result = []; let i = m, j = n; const rawDiffs = [];
let i = m, j = n; const raw = []; 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--; raw.push({ type: 'unchanged', 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] }); raw.push({ type: 'added', content: newLines[j - 1] }); j--; } else { rawDiffs.push({ type: 'removed', oldIdx: i - 1, content: oldLines[i - 1] }); raw.push({ type: 'removed', content: oldLines[i - 1] }); i--; } } raw.reverse();
rawDiffs.reverse();
// 合并相邻的删除和新增为"修改" // 合并连续 removed+added 对 const merged = []; let k = 0; while (k < rawDiffs.length) { while (k < raw.length) { if ( rawDiffs[k].type === 'removed' && k + 1 < rawDiffs.length && rawDiffs[k + 1].type === 'added' raw[k].type === 'removed' && k + 1 < raw.length && raw[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]); } 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 item of removedGroup) { merged.push({ ...item, pairedWithAdd: true }); } for (const item of addedGroup) { merged.push({ ...item, pairedWithRemove: true }); } for (const x of rg) merged.push({ ...x, pairedWithAdd: true }); for (const x of ag) merged.push({ ...x, pairedWithRemove: true }); } else { merged.push(rawDiffs[k]); k++; merged.push(raw[k++]); } }
return merged; }
// ======================== UI 组件 ======================== function collapseUnchanged(diffs) { const n = diffs.length;
/** 创建加载遮罩 */ 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; } 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; } }
/** 移除加载遮罩 */ function removeLoadingOverlay() { const overlay = document.getElementById('lg-diff-loading'); if (overlay) overlay.remove(); 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; }
/** 渲染 Diff 结果到模态框 */ function showDiffModal(oldCode, newCode, oldRecordId, newRecordId) { const colors = getColors(); const dark = isDarkMode(); // ======================== 代码 HTML 构建 ========================
// 执行 diff(确保 sourceCode 是字符串) const oldLines = String(oldCode || '').split('\n'); const newLines = String(newCode || '').split('\n'); const diffs = lineDiff(oldLines, newLines); 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; } } }
// 构建代码行 HTML let codeHtml = ''; let html = ''; let oldLineNum = 0; let newLineNum = 0;
for (const diff of diffs) { 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++; 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>' + 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">' + 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>' + '<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++; 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>' + 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; }
// 统计变更 const addedCount = diffs.filter((d) => d.type === 'added').length; const removedCount = diffs.filter((d) => d.type === 'removed').length; // ======================== 并列视图 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 = '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> `; 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);
// 应用用户设置 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'); // ---- 设置交互 ---- 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');
fontDecBtn.addEventListener('click', () => { currentSettings.fontSize = Math.max(currentSettings.fontSize - 1, 8); fontSlider.addEventListener('input', () => { currentSettings.fontSize = parseInt(fontSlider.value, 10); 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'; lhSlider.addEventListener('input', () => { currentSettings.lineHeight = parseFloat(parseFloat(lhSlider.value).toFixed(1)); lhValueEl.textContent = currentSettings.lineHeight.toFixed(1) + 'x'; 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'; 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); });
lhIncBtn.addEventListener('click', () => { currentSettings.lineHeight = Math.min(+(currentSettings.lineHeight + 0.1).toFixed(1), 3.0); lhValueEl.textContent = currentSettings.lineHeight + 'x'; applyCodeSettings(codeArea, 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(); });
// 事件绑定 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(); // 绑定展开按钮和折叠图标事件 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';
// 自定义对比 overlay.querySelector('#lg-diff-custom-compare').addEventListener('click', () => { close(); promptCustomCompare(newRecordId); // 亮暗模式切换 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); });
// ESC 关闭 // 关闭逻辑 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') { close(); document.removeEventListener('keydown', escHandler); } 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(); }); } }
/** 提示用户输入自定义提交 ID */ function promptCustomCompare(currentRecordId) { const existing = document.getElementById('lg-diff-custom-dialog'); // ======================== 手动输入对比对话框 ========================
function showManualInputDialog() { const existing = document.getElementById('oj-diff-manual-dialog'); if (existing) existing.remove();
const dark = isDarkMode(); const colors = getColors(); const settings = loadSettings(); const dark = isDarkMode(settings.themeMode); const C = getColors(dark);
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> `; 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 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 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('#lg-diff-custom-id'); 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('#lg-diff-custom-error'); const errEl = dialog.querySelector('#oj-diff-custom-error'); errEl.textContent = '请输入有效的数字 ID'; errEl.style.display = 'block'; return; } closeDialog(); 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(); }); 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 = '←'; } }
// ======================== 核心逻辑 ======================== // ======================== 对比两份提交记录对话框 ========================
/** 获取记录详情(包含源代码) * 请求 /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); function showRecordCompareDialog() { const existing = document.getElementById('oj-diff-record-cmp-dialog'); if (existing) existing.remove();
// _contentOnly 返回的数据在 currentData 中,record 直接在 data 下 if (!data.record) { console.error('[洛谷代码对比] 响应中没有 record 字段,响应数据:', JSON.stringify(data).slice(0, 500)); throw new Error('无法获取记录信息(response 中缺少 record 字段)'); } const settings = loadSettings(); const dark = isDarkMode(settings.themeMode); const C = getColors(dark);
return data.record; } 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>';
/** 获取提交记录列表 * 请求 /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)); document.body.appendChild(dialog);
const url = `${LUOGU_BASE}/record/list?${query.toString()}`; const response = await fetchLuogu(url); console.log('[洛谷代码对比] 记录列表响应:', response); const data = extractData(response); 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(); });
console.log('[洛谷代码对比] 记录列表 data.records 类型:', typeof data.records, Array.isArray(data.records), JSON.stringify(data.records).slice(0, 300)); const oldInput = dialog.querySelector('#oj-diff-rcmp-old-id'); const newInput = dialog.querySelector('#oj-diff-rcmp-new-id');
//洛谷 records 字段可能是: // 1. 直接数组: [record1, record2, ...] // 2. 分页对象: { result: [...], count: N, perPage: M } // 3. 其他嵌套结构: { records: [...] }(较少见但防御性处理) let records = data.records; const xBtn = dialog.querySelector('.oj-diff-close'); if (modalStack.length > 0) { xBtn.title = '返回上级'; xBtn.textContent = '←'; }
if (Array.isArray(records)) { // 直接数组,无需处理 return records; } const doCompare = async () => { const oldId = oldInput.value.trim(); const newId = newInput.value.trim(); const errEl = dialog.querySelector('#oj-diff-rcmp-error');
if (records && typeof records === 'object') { // 分页对象:result 字段包含实际数组 if (Array.isArray(records.result)) { console.log('[洛谷代码对比] records 是分页对象,使用 result 字段'); return records.result; if (!oldId || !/^\d+$/.test(oldId) || !newId || !/^\d+$/.test(newId)) { errEl.textContent = '请输入有效的数字 ID(两个 ID 均为必填)'; errEl.style.display = 'block'; return; } // 嵌套 records 字段 if (Array.isArray(records.records)) { console.log('[洛谷代码对比] records 是嵌套对象,使用 records.records 字段'); return records.records; if (oldId === newId) { errEl.textContent = '两个 ID 不能相同'; errEl.style.display = 'block'; return; } // records 对象的 values 或 data 字段 if (Array.isArray(records.values)) { return records.values; } if (Array.isArray(records.data)) { return records.data; } } 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); };
// records 为 null/undefined 或无法识别的结构 console.error('[洛谷代码对比] 无法识别 records 格式:', records); return []; 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); }
/** 查找同一用户同一题目的上一次提交 */ async function findPrevRecord(currentRecordId, pid, uid) { // 洛谷记录列表默认按时间倒序排列(最新的在前) // 遍历前两页查找 for (let page = 1; page <= 2; page++) { const records = await fetchRecordList({ pid, user: String(uid), page }); // ======================== Toast 提示 ========================
const currentIdx = records.findIndex((r) => String(r.id) === String(currentRecordId)); 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); }
if (currentIdx !== -1) { // 当前提交在本页找到,返回列表中它之后的第一个(即时间上更早的) if (currentIdx + 1 < records.length) { return records[currentIdx + 1]; } // 当前提交在列表末尾,需要看下一页 continue; } // ======================== 核心逻辑(通用,通过 ADAPTER 多态调用) ========================
// 当前提交不在本页,如果当前页的记录提交时间都早于当前提交, // 则返回本页第一条(最新的早于当前的) if (records.length > 0) { // 检查本页是否有不是当前提交的记录 for (const record of records) { if (String(record.id) !== String(currentRecordId)) { return record; } } } } /** 根据两份提交记录 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);
throw new Error('未找到该题目的上一次提交记录'); 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;
// 优先从页面内嵌数据获取当前提交信息(零延迟) const pageData = _unsafeWindow._feInjection?.currentData; if (pageData?.record) { currentRecord = pageData.record; console.log('[洛谷代码对比] 从页面内嵌数据获取当前记录成功'); }
if (targetRecordId) { // 有指定的对比 ID if (!currentRecord) { updateLoadingMessage(loading, '正在获取当前提交代码...'); currentRecord = await fetchRecordDetail(currentRecordId); // 指定提交 ID 对比——总是从 API 重新获取,避免 getPageData 可能缺少 sourceCode updateLoadingMessage(loading, '正在获取当前提交代码...'); currentRecord = await ADAPTER.fetchRecordDetail(currentRecordId); }
updateLoadingMessage(loading, '正在获取对比提交代码...'); targetRecord = await fetchRecordDetail(targetRecordId); targetRecord = await ADAPTER.fetchRecordDetail(targetRecordId); } else { // 自动查找上一次提交 if (!currentRecord) { // 与上次提交对比 // 尝试从页面缓存获取(仅洛谷有效,快速获取当前记录信息) const pageData = ADAPTER.getPageData(); if (pageData) { currentRecord = pageData; } else { updateLoadingMessage(loading, '正在获取当前提交信息...'); currentRecord = await fetchRecordDetail(currentRecordId); currentRecord = await ADAPTER.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);
const prevBase = await ADAPTER.findPrevRecord(currentRecordId, currentRecord); updateLoadingMessage(loading, '正在获取上一次提交代码...'); targetRecord = await fetchRecordDetail(prevRecordBase.id); targetRecord = await ADAPTER.fetchRecordDetail(prevBase.id, prevBase); }
// 检查源代码是否可访问 if (!currentRecord.sourceCode && currentRecord.sourceCode !== '') { throw new Error('当前提交的代码不可访问(可能是隐私设置)'); } if (!targetRecord.sourceCode && targetRecord.sourceCode !== '') { throw new Error('对比提交的代码不可访问(可能是隐私设置)'); } const curCode = ADAPTER.getSourceCode(currentRecord); const tgtCode = ADAPTER.getSourceCode(targetRecord); if (!curCode) throw new Error('当前提交的代码不可访问或为空(可能是隐私设置或权限不足)'); if (!tgtCode) throw new Error('对比提交的代码不可访问或为空(可能是隐私设置或权限不足)');
removeLoadingOverlay();
// 展示 diff 结果(targetRecord 是旧代码,currentRecord 是新代码) showDiffModal( String(targetRecord.sourceCode ?? ''), String(currentRecord.sourceCode ?? ''), String(targetRecord.id), String(currentRecord.id) 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(); showError(err.message); showToast(err.message, 'error'); } }
/** 更新加载提示文字 */ 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 (document.getElementById('oj-diff-compare-btn')) return; const recordId = ADAPTER.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.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 = 'scale(1.05)'; btn.style.boxShadow = '0 6px 24px rgba(102, 126, 234, 0.6)'; 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 = 'scale(1)'; btn.style.boxShadow = '0 4px 16px rgba(102, 126, 234, 0.4)'; 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', async () => { btn.style.pointerEvents = 'none'; btn.style.opacity = '0.6'; try { await runCompare(recordId, null); } finally { btn.style.pointerEvents = 'auto'; btn.style.opacity = '1'; } });
btn.addEventListener('click', () => showFloatingMenu(recordId)); document.body.appendChild(btn); makeDraggable(btn); }
// 同时尝试在页面内注入一个次要按钮 injectInlineButton(recordId); 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.style.cssText = ` display: flex; gap: 8px; margin: 8px 0; align-items: center; `; container.setAttribute('data-oj-diff-injected', '1'); container.style.cssText = 'display:flex;gap:8px;margin:8px 0;align-items:center;flex-wrap:wrap;';
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'; } }); 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 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); }); const isAtCoder = CURRENT_PLATFORM?.id === 'atcoder';
container.appendChild(inlineBtn); container.appendChild(customBtn); 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 lg-diff-spin { to { transform: rotate(360deg); } } @keyframes oj-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; #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); }
/* 模态框 */ .lg-diff-modal { width: 90vw; max-width: 960px; max-height: 85vh; border-radius: 16px; overflow: hidden; display: flex; flex-direction: column; .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; }
.lg-diff-modal.lg-diff-light { background: #ffffff; /* 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; }
.lg-diff-modal.lg-diff-dark { background: #161b22; } .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; }
/* 头部 */ .lg-diff-header { display: flex; align-items: center; gap: 16px; padding: 16px 24px; border-bottom: 1px solid; } .oj-diff-ids { display: flex; align-items: center; gap: 8px; font-size: 14px; }
.lg-diff-light .lg-diff-header { border-color: #e1e4e8; background: #f6f8fa; .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; }
.lg-diff-dark .lg-diff-header { border-color: #30363d; background: #0d1117; } .oj-diff-arrow { color: #959da5; font-weight: 700; }
.lg-diff-title { font-size: 18px; font-weight: 700; display: flex; align-items: center; gap: 8px; } .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; }
.lg-diff-light .lg-diff-title { color: #24292e; } .lg-diff-dark .lg-diff-title { color: #e6edf3; }
.lg-diff-title-icon { font-size: 20px; /* 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; }
.lg-diff-ids { display: flex; align-items: center; gap: 8px; font-size: 14px; } .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; }
.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; /* 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; 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; }
.lg-diff-light .lg-diff-close { background: #f0f0f0; color: #586069; } /* Body */ .oj-diff-body { flex: 1; overflow: auto; padding: 0; }
.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 { .oj-diff-code { font-family: 'Cascadia Code', 'Fira Code', 'JetBrains Mono', 'Consolas', monospace; font-size: 13px; line-height: 1.5; white-space: pre; 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; min-height: 0; } .oj-diff-line { display: flex; align-items: stretch; min-width: 100%; width: max-content; }
.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; .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; }
.lg-diff-marker { display: inline-block; width: 20px; min-width: 20px; text-align: center; user-select: none; font-weight: 700; } .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; }
.lg-diff-content { flex: 1; white-space: pre; padding-left: 8px; } .oj-diff-content { flex: 1; white-space: pre; padding-left: 4px; min-width: 0; }
/* 未变更行 */ .lg-diff-unchanged { background: transparent; } /* 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; }
.lg-diff-light .lg-diff-unchanged .lg-diff-ln-old, .lg-diff-light .lg-diff-unchanged .lg-diff-ln-new { color: #959da5; background: #f6f8fa; } /* 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; }
.lg-diff-light .lg-diff-unchanged .lg-diff-content { color: #24292e; } /* 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; }
.lg-diff-dark .lg-diff-unchanged .lg-diff-ln-old, .lg-diff-dark .lg-diff-unchanged .lg-diff-ln-new { color: #484f58; background: #161b22; } /* 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; }
.lg-diff-dark .lg-diff-unchanged .lg-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; }
/* 删除行 */ .lg-diff-removed { background: #ffeef0; } .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; }
.lg-diff-light .lg-diff-removed .lg-diff-ln-old { color: #cb2431; background: #f8d7da; /* 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; }
.lg-diff-light .lg-diff-removed .lg-diff-ln-new { background: #ffeef0; .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; }
.lg-diff-light .lg-diff-removed .lg-diff-marker { color: #cb2431; } .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; }
.lg-diff-light .lg-diff-removed .lg-diff-content { color: #24292e; } .oj-diff-settings-divider { color: #d1d5da; user-select: none; font-size: 12px; } .oj-diff-dark .oj-diff-settings-divider { color: #30363d; }
.lg-diff-dark .lg-diff-removed { background: #3d1a1a; } /* 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; }
.lg-diff-dark .lg-diff-removed .lg-diff-ln-old { color: #f85149; background: #4d2020; /* 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; }
.lg-diff-dark .lg-diff-removed .lg-diff-ln-new { background: #3d1a1a; /* 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; }
.lg-diff-dark .lg-diff-removed .lg-diff-marker { color: #f85149; } .oj-diff-fold-icon-placeholder { display: inline-block; vertical-align: middle; width: 12px; min-width: 12px; flex-shrink: 0; }
.lg-diff-dark .lg-diff-removed .lg-diff-content { color: #e6edf3; /* 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; }
/* 新增行 */ .lg-diff-added { background: #e6ffed; .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; }
.lg-diff-light .lg-diff-added .lg-diff-ln-new { color: #22863a; background: #cdffd8; /* 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; }
.lg-diff-light .lg-diff-added .lg-diff-ln-old { background: #e6ffed; } /* Split view */ .oj-diff-split-container { display: flex; width: 100%; }
.lg-diff-light .lg-diff-added .lg-diff-marker { color: #22863a; } .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; }
.lg-diff-light .lg-diff-added .lg-diff-content { color: #24292e; .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; }
.lg-diff-dark .lg-diff-added { background: #1b3a1f; } .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; }
.lg-diff-dark .lg-diff-added .lg-diff-ln-new { color: #3fb950; background: #245028; } /* 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; }
.lg-diff-dark .lg-diff-added .lg-diff-ln-old { background: #1b3a1f; } /* 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; }
.lg-diff-dark .lg-diff-added .lg-diff-marker { color: #3fb950; } /* 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; }
.lg-diff-dark .lg-diff-added .lg-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; }
/* 设置工具栏 */ .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; } /* 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();
// 使用 MutationObserver 监听页面加载 const observer = new MutationObserver((mutations, obs) => { const recordId = getRecordIdFromUrl(); if (!recordId) return; if (!CURRENT_PLATFORM) return;
// 检查页面是否已充分加载 const hasContent = document.querySelector('pre') || document.querySelector('code') || document.querySelector('.markdown-renderer'); if (hasContent || document.readyState === 'complete') { injectCompareButton(); // 不停止观察,因为页面可能会动态更新 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); } });
observer.observe(document.body, { childList: true, subtree: true, });
// 也在 DOMContentLoaded 时尝试注入 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { setTimeout(injectCompareButton, 1000); 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(); }); } else { setTimeout(injectCompareButton, 1000); }
// 监听主题切换 const themeObserver = new MutationObserver(() => { // 主题切换时移除旧按钮并重新注入 const btn = document.getElementById('lg-diff-compare-btn'); if (btn) { btn.remove(); 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(); } themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'], }); }).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); }})();``````
```:::