跳到正文

个人记录

洛谷提交历史版本对比

formu1约 223 分钟
原文
文章信息与版本

文章信息

发布
2026年11月5日
收录
2026年11月5日
更新
2026年11月15日
篇幅
约 223 分钟

版本

  1. v2当前
  2. v1

注意:未完工版本,任何东西都有待修缮,欢迎提出

洛谷 · 提交版本对比

一个 Tampermonkey 油猴脚本:在洛谷网页里直接比较同一道题、任意两次提交的代码。

不用把代码复制出来,也不用打开本地 diff 工具——在题目页或记录页点一下,就能看到两次提交之间改了什么。

并排对比(浅色)

功能

  • 两种视图:并排(side-by-side)和统一(unified),随时切换。
  • 行内高亮:成对修改的行会把真正变化的 token 标出来,而不是整行红绿一片。
  • 智能配对:一段删除和一段插入会按行相似度对齐,修改前后的 cin / cout 不会错位成两行。
  • 仅显示差异:默认折叠长段相同代码,只保留修改处前后 3 行上下文;可一键展开全部。
  • 忽略空白:忽略缩进、行尾空格和空白 run 的差异,适合只改了格式的版本。
  • 统计信息:+新增 −删除、修改块数量、两次提交的语言/状态/时间。
  • 快捷对比:
    • 题目页:默认比较最近两次提交;
    • 记录页:默认比较当前提交与上一次提交;
    • 「最近两次 AC」「当前 ↔ 上次 AC」。
  • 可拖动分割线:按住 side/main 之间的竖线左右拖动即可调整提交列表宽度;宽度会记住,聚焦分割线后也可用左右方向键微调。
  • 提交编号直达:点列表里的 #提交号(以及顶部 A/B 摘要里的编号)会在新标签页打开对应的 /record/{id},不会打断当前对比。
  • 导出 patch:复制或下载标准 unified diff(.diff)。
  • 暗色模式:自动跟随洛谷页面背景,也可在系统深色模式下正常工作。
  • 不打断浏览:Shadow DOM 隔离样式,Esc 关闭,Alt + D 打开;刷新页面/切换题目后自动更新入口。

暗色模式

真实页面验证

在 2026-11 的线上页面实测:当前洛谷已不再暴露 _feInstance,脚本通过页面里的 #lentille-context 读取用户与题目数据,并保留接口兜底。未登录时会在面板里明确提示:

真实页面(未登录)

安装

  1. 给浏览器安装 Tampermonkey(Chrome / Edge / Firefox 均可)。
  2. 打开 Tampermonkey 管理面板 → 「添加新脚本」,把 luogu-version-diff.user.js 的全部内容粘贴进去,Ctrl + S 保存。
    • 也可以直接在文件管理器里把 .user.js 拖进浏览器窗口,按 Tampermonkey 的提示安装。
  3. 打开任意洛谷题目页,右下角出现「版本对比」按钮即安装成功。

更新到 v1.3.0:包含 v1.1.0 的面板点击修复、v1.2.0 的提交编号 #xxx 跳转,以及新增的 side/main 可拖动分割线。请用最新 luogu-version-diff.user.js 覆盖 Tampermonkey 里的旧脚本,然后刷新洛谷页面;面板右上角版本号应显示 v1.3.0。

脚本只在 www.luogu.com.cn / www.luogu.com 下运行,不向任何第三方发送数据。

使用

题目页

打开 https://www.luogu.com.cn/problem/P1001,点右下角「版本对比」(或按 Alt + D):

  • 自动读取当前账号在这道题下的提交记录(默认最近 100 条,可继续加载);
  • 自动选中最近两次提交并展示 diff;
  • 在左侧列表点选任意两条记录即可换一组比较。

记录页

打开 https://www.luogu.com.cn/record/123456,点「版本对比」:

  • 自动以当前记录和上一次提交为一组开始比较;
  • 顶部「当前 ↔ 上次 AC」可以直接对比当前提交与此前最近一次 AC;
  • 如果当前记录不是你的提交,脚本只会列出并比较你自己的提交。

选择与视图

  • 左侧点选记录:第一次点为 A(左/旧),第二次点为 B(右/新);点第三次会替换最早选中的一条。
  • 点「⇄」交换 A/B。
  • 工具栏可切换「并排 / 统一」、「忽略空白」、「仅显示差异」。
  • 「复制 patch」「下载」生成标准 unified diff。

记录页对比

实现要点

数据来源

全部走洛谷自身的同源接口,携带当前登录 Cookie:

用途请求
提交列表GET /record/list?pid=...&user=...&page=...
单条提交(含代码)GET /record/{id}
状态/语言名称GET /_lfe/config
  • 当前洛谷的 Record 页面使用 Lentille 内容协商:请求头 x-lentille-request: content-only,返回顶层 data(旧版为 currentData,脚本两者都兼容)。
  • 不再依赖已经失效的 _contentOnly 参数;这也避免接口返回整页 HTML 的情况。
  • 所有请求都发生在点击「版本对比」之后:页面加载、滚动、路由切换都不会请求接口;面板打开期间也不会轮询提交记录。
  • 洛谷的 user 参数在不同版本中可能接受 uid 或用户名:脚本先试 uid,列表为空或返回的用户不符时自动回退到用户名(测试账号使用 uid 正常)。
  • 当前用户优先读当前页面的 #lentille-context(当前洛谷版本),其次 _feInstance / _feInjection(旧版),最后才请求接口兜底。
  • 记录页会优先复用 #lentille-context 里的记录数据,减少一次网络请求;字段不全时自动回退到接口。
  • 配置(/_lfe/config)只在第一次成功打开面板时请求一次;代码、提交详情、用户和列表都在当前页面会话内缓存。

网络重试与缓存

  • 失败重试:第一次 400ms,随后按指数退避 2s、4s(最多 3 次重试,延迟上限 8s);429 至少从 2s 起步。
  • 401 / 403 / 「代码不可见」等确定性错误不重试,直接给出提示。
  • 关闭面板会取消列表、用户与代码请求,以及正在等待的退避,不会在后台继续重试。
  • 提交列表缓存 60 秒:关闭后重新打开或重复点击不会重新拉取分页;点「刷新」会强制重新请求。
  • 同一份代码/配置/详情只请求一次(命中缓存直接复用),避免反复切换 A/B 时重复下载。
  • 所有缓存都在页面内存中,刷新页面即清空;脚本不会实时监测新提交,需要最新列表时请点「刷新」。

diff 引擎

  • 行级 Myers diff(线性空间 middle-snake 分割)+ 小区间 LCS 动态规划兜底;
  • 先裁剪公共前后缀,常见「只改几行」的提交几乎瞬间完成;
  • 对 2000 行完全不同的代码约 220 ms,5000 行仅少量修改约 13 ms(Node 基准);
  • 两阶段处理:先算行级 diff,再在变更块内用 token 相似度做二次对齐与行内高亮;
  • unified diff 导出复用同一套 hunk 计算,保证界面与 patch 一致。

界面

  • Shadow DOM + 独立 CSS 变量,避免被洛谷主题样式污染;
  • 自动检测页面背景亮度/主题 class,切换浅色/暗色;
  • Esc 关闭、Alt + D 开关、焦点陷阱、aria-live 提示;
  • 代码全部经过 HTML 转义,不执行提交内容。

本地开发与测试

无需安装依赖(Node.js ≥ 18):

Bash
# 单元测试:diff 正确性、最小性、hunk、unified diff、路由解析
node tests/diff.test.js

# 启动本地演示(带 mock 数据,不会访问洛谷)
node demo/server.js
# 浏览器打开 http://127.0.0.1:8787/problem/P1001

演示页面模拟了洛谷题目页和 6 条提交记录,用来检查面板、暗色模式和记录页流程。带 ?screenshot=1 会自动打开面板,方便截图:

代码
http://127.0.0.1:8787/problem/P1001?screenshot=1
http://127.0.0.1:8787/problem/P1001?screenshot=1&theme=dark
http://127.0.0.1:8787/problem/P1001?screenshot=1&view=unified
http://127.0.0.1:8787/record/124?screenshot=1

演示页还带了两个网络探针:?probe=1 会在页面加载后打印接口请求数(应为 0,证明未点击不请求);?probe=2 会先打开面板、关闭再重开,然后打印请求数(应保持不变,证明列表/代码缓存生效)。?fail=1 会让第一次列表请求返回 503,用来验证 400ms 后的自动重试。

测试结果:27 项全部通过,包括 1500 组随机小规模用例与 200 组中等规模用例的最小编辑距离校验。

目录结构

代码
luogu-version-diff/
├── luogu-version-diff.user.js   # 单文件油猴脚本(安装这个)
├── tests/diff.test.js           # diff/路由/格式化单元测试
├── demo/
│   ├── page.html                # 洛谷风格 mock 页面(内置提交与代码)
│   └── server.js                # 本地静态/路由服务器
├── screenshots/                 # 界面截图
├── package.json                 # npm test / npm run demo
└── README.md

限制与注意事项

  • 必须登录洛谷,且只能比较你自己的提交;洛谷不会向他人开放未公开的代码。
  • 脚本只在点击「版本对比」时查询一次,不会轮询或实时监听新的提交记录;需要更新时点面板里的刷新按钮。
  • 洛谷接口属于非公开接口,若官方调整字段(如 sourceCode、records.result)或更换内容协商方式,脚本可能需要同步更新。
  • 记录页默认取「列表中的下一条」作为上一次提交;如果当前记录太旧、不在已加载的 100 条内,脚本会把它单独加入列表,由你手动选择另一条。
  • 比较在浏览器主线程同步计算;极大的文件(数万行)可能造成短暂卡顿。脚本对单次代码总量有 80 万字符的保护上限。
  • 「忽略空白」会把连续空格/制表符合并为一个空格并去掉首尾空白;不会改变展示的原始代码。
  • 仅做文本 diff,不理解语法/AST,不会做语义等价判断。
  • 脚本使用 @grant none 运行在页面上下文,读取 #lentille-context(当前洛谷版本)/ _feInstance(旧版)获取当前用户;若取不到会走接口兜底,仍失败则明确提示登录或无法读取,不会静默出错。
  • 演示页面中的用户 demo_oier、提交记录和代码都是虚构数据,仅用于本地预览。

License

MIT(脚本本身)。提交代码的版权归各自作者所有,本工具只做本地展示与比较。

JavaScript
// ==UserScript==
// @name         洛谷 · 提交版本对比
// @name:en      Luogu Submission Diff
// @namespace    https://www.luogu.com.cn/
// @version      1.1.2
// @description  在同一道题的历史提交之间比较代码:并排/统一 diff、行内高亮、仅看差异、复制或下载 patch。
// @author       DSH
// @match        https://www.luogu.com.cn/*
// @match        https://www.luogu.com/*
// @run-at       document-idle
// @grant        none
// @noframes
// ==/UserScript==

(function () {
  'use strict';

  const VERSION = '1.1.2';
  const LS = 'lgvd:';
  const MAX_RECORDS = 300;
  const INITIAL_LIMIT = 100;
  const FETCH_GAP = 110;
  const CONTEXT = 3;
  const MAX_CODE_CHARS = 400000;
  const LIST_TTL = 60000;
  const RETRY_BASE = 300;

  /* ------------------------------------------------------------------ *
   *  小工具
   * ------------------------------------------------------------------ */

  const $ = (sel, root) => (root || shadow || document).querySelector(sel);
  const $$ = (sel, root) => Array.from((root || shadow || document).querySelectorAll(sel));

  function esc(s) {
    return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({
      '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
    }[c]));
  }

  function pad2(n) { return n < 10 ? '0' + n : '' + n; }

  function sleep(ms) { return new Promise((r) => setTimeout(r, ms)); }

  function clamp(n, a, b) { return Math.max(a, Math.min(b, n)); }

  function fmtDateTime(sec) {
    if (!sec) return '—';
    const d = new Date(sec * 1000);
    return `${d.getMonth() + 1}-${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
  }

  function fmtFullTime(sec) {
    if (!sec) return '';
    try { return new Date(sec * 1000).toLocaleString('zh-CN', { hour12: false }); }
    catch { return fmtDateTime(sec); }
  }

  function fmtRunTime(ms) {
    if (ms == null) return '—';
    if (ms < 1000) return ms + 'ms';
    return (ms / 1000).toFixed(ms < 10000 ? 2 : 1) + 's';
  }

  function fmtMemory(kb) {
    if (kb == null) return '—';
    if (kb < 1024) return kb + 'KB';
    return (kb / 1024).toFixed(1) + 'MB';
  }

  const storage = {
    get(key, fallback) {
      try {
        const raw = localStorage.getItem(LS + key);
        return raw == null ? fallback : JSON.parse(raw);
      } catch { return fallback; }
    },
    set(key, value) {
      try { localStorage.setItem(LS + key, JSON.stringify(value)); } catch { /* ignore */ }
    }
  };

  /* ------------------------------------------------------------------ *
   *  状态与语言
   * ------------------------------------------------------------------ */

  const STATUS_FALLBACK = {
    '-1': { short: 'N/A', name: 'Unshown', cls: 'grey' },
    0: { short: '等待', name: 'Waiting', cls: 'blue' },
    1: { short: '评测中', name: 'Judging', cls: 'blue' },
    2: { short: 'CE', name: 'Compile Error', cls: 'yellow' },
    3: { short: 'OLE', name: 'Output Limit Exceeded', cls: 'blue' },
    4: { short: 'MLE', name: 'Memory Limit Exceeded', cls: 'blue' },
    5: { short: 'TLE', name: 'Time Limit Exceeded', cls: 'blue' },
    6: { short: 'WA', name: 'Wrong Answer', cls: 'red' },
    7: { short: 'RE', name: 'Runtime Error', cls: 'purple' },
    11: { short: 'UKE', name: 'Unknown Error', cls: 'lapis' },
    12: { short: 'AC', name: 'Accepted', cls: 'green' },
    14: { short: 'NAC', name: 'Unaccepted', cls: 'red' },
    21: { short: 'Hack+', name: 'Hack Success', cls: 'green' },
    22: { short: 'Hack-', name: 'Hack Failure', cls: 'red' },
    23: { short: 'Hack', name: 'Hack Skipped', cls: 'blue' }
  };

  const STATUS_CLASS = {
    '-1': 'grey', 0: 'blue', 1: 'blue', 2: 'yellow', 3: 'blue', 4: 'blue',
    5: 'blue', 6: 'red', 7: 'purple', 11: 'lapis', 12: 'green', 14: 'red',
    21: 'green', 22: 'red', 23: 'blue'
  };

  const LANG_FALLBACK = {
    1: 'Pascal', 2: 'C', 3: 'C++98', 4: 'C++11', 5: '提交答案', 6: 'Python 2',
    7: 'Python 3', 8: 'Java 8', 9: 'Node.js', 10: 'Shell', 11: 'C++14',
    12: 'C++17', 13: 'Ruby', 14: 'Go', 15: 'Rust', 16: 'PHP', 17: 'C#',
    18: 'Visual Basic', 19: 'Haskell', 20: 'Kotlin/Native', 21: 'Kotlin/JVM',
    22: 'Scala', 23: 'Perl', 24: 'PyPy 2', 25: 'PyPy 3', 26: '文言',
    27: 'C++20', 28: 'C++14 (GCC 9)', 29: 'F#', 30: 'OCaml', 31: 'Julia',
    32: 'Lua', 33: 'Java 21', 34: 'C++23'
  };

  const CONFIG = { status: {}, langs: {} };
  let configPromise = null;

  function applyConfig(cfg) {
    if (!cfg) return;
    const status = cfg.RecordStatus || cfg.recordStatus;
    if (status && typeof status === 'object') {
      for (const key of Object.keys(status)) {
        const v = status[key] || {};
        CONFIG.status[key] = {
          short: v.shortName || (STATUS_FALLBACK[key] && STATUS_FALLBACK[key].short) || '?',
          name: v.name || '',
          cls: STATUS_CLASS[key] || (STATUS_FALLBACK[key] && STATUS_FALLBACK[key].cls) || 'grey'
        };
      }
    }
    const langs = cfg.CodeLanguage || cfg.codeLanguages;
    if (langs && typeof langs === 'object') {
      for (const key of Object.keys(langs)) {
        const v = langs[key] || {};
        if (v.name) CONFIG.langs[key] = v.name;
      }
    }
  }

  function statusInfo(id) {
    return CONFIG.status[id] || STATUS_FALLBACK[id] || { short: '?', name: 'Unknown', cls: 'grey' };
  }

  function languageName(id) {
    return CONFIG.langs[id] || LANG_FALLBACK[id] || ('语言 #' + id);
  }

  /* ------------------------------------------------------------------ *
   *  洛谷接口
   * ------------------------------------------------------------------ */

  class LgError extends Error {
    constructor(kind, message, extra) {
      super(message);
      this.name = 'LgError';
      this.kind = kind;
      this.extra = extra || {};
    }
  }

  function pageGlobal(name) {
    try { if (window[name]) return window[name]; } catch { /* ignore */ }
    try {
      if (typeof unsafeWindow !== 'undefined' && unsafeWindow && unsafeWindow[name]) return unsafeWindow[name];
    } catch { /* ignore */ }
    return null;
  }

  // 当前洛谷把页面数据序列化在 #lentille-context 里;旧版则挂 _feInstance。
  let contextCache = { href: '', value: null };
  function readLentilleContext() {
    if (contextCache.href === location.href) return contextCache.value;
    let value = null;
    const el = document.getElementById('lentille-context');
    if (el) {
      try { value = JSON.parse(el.textContent || ''); } catch { value = null; }
    }
    contextCache = { href: location.href, value: value };
    return value;
  }

  async function apiFetch(path, params, opts) {
    opts = opts || {};
    const url = new URL(path, location.origin);
    if (params) {
      for (const key of Object.keys(params)) {
        const v = params[key];
        if (v !== undefined && v !== null && v !== '') url.searchParams.set(key, String(v));
      }
    }

    const ctrl = new AbortController();
    const timer = setTimeout(() => ctrl.abort(), 20000);
    if (opts.signal) {
      if (opts.signal.aborted) ctrl.abort();
      else opts.signal.addEventListener('abort', () => ctrl.abort(), { once: true });
    }

    const headers = {
      'accept': 'application/json, text/plain, */*',
      'x-requested-with': 'XMLHttpRequest'
    };
    // 当前洛谷的 record 页面数据走 Lentille,必须用这个头才会返回 JSON。
    if (opts.lentille) headers['x-lentille-request'] = 'content-only';

    let res;
    try {
      res = await fetch(url.href, {
        credentials: 'same-origin',
        headers: headers,
        signal: ctrl.signal
      });
    } catch (e) {
      clearTimeout(timer);
      if (opts.signal && opts.signal.aborted) throw new LgError('abort', '已取消');
      if (e && e.name === 'AbortError') throw new LgError('timeout', '请求超时,请稍后重试');
      throw new LgError('network', '网络请求失败,请检查网络连接');
    }
    clearTimeout(timer);

    if (res.status === 401) throw new LgError('login', '请先登录洛谷');
    if (res.status === 403) throw new LgError('forbidden', '没有访问权限');
    if (res.status === 429) throw new LgError('rate', '请求过于频繁,请稍后再试');

    const text = await res.text();
    let json = null;
    try { json = JSON.parse(text); } catch { /* not json */ }

    if (!res.ok) throw new LgError('http', '接口请求失败(HTTP ' + res.status + ')', { status: res.status });
    if (!json) {
      const type = res.headers.get('content-type') || '';
      if (type.includes('text/html')) {
        throw new LgError('content', '洛谷返回了网页而不是接口数据(接口格式可能已变化)');
      }
      throw new LgError('parse', '接口返回内容无法解析');
    }
    if (json.needLogin || json.status === 401 || json.code === 401) {
      throw new LgError('login', '请先登录洛谷');
    }
    if (json.status === 403 || json.code === 403) {
      throw new LgError('forbidden', '没有访问权限');
    }
    if (json.status != null && json.status !== 200) {
      throw new LgError('api', '接口返回错误(' + json.status + ')');
    }
    if (json.code != null && json.code !== 200) {
      throw new LgError('api', json.message || json.errorMessage || ('接口返回错误(' + json.code + ')'));
    }
    return json;
  }

  const inflight = new Map();

  function requestKey(path, params) {
    const parts = [];
    if (params) {
      for (const key of Object.keys(params).sort()) {
        const v = params[key];
        if (v !== undefined && v !== null && v !== '') {
          parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(String(v)));
        }
      }
    }
    return path + '?' + parts.join('&');
  }

  function sleepAbortable(ms, signal) {
    return new Promise((resolve, reject) => {
      if (signal && signal.aborted) {
        reject(new LgError('abort', '已取消'));
        return;
      }
      const timer = setTimeout(() => {
        cleanup();
        resolve();
      }, ms);
      function cleanup() {
        if (signal) signal.removeEventListener('abort', onAbort);
      }
      function onAbort() {
        clearTimeout(timer);
        cleanup();
        reject(new LgError('abort', '已取消'));
      }
      if (signal) signal.addEventListener('abort', onAbort, { once: true });
    });
  }

  function isRetryable(error) {
    if (!(error instanceof LgError)) return true;
    if (error.kind === 'login' || error.kind === 'forbidden' || error.kind === 'abort'
      || error.kind === 'code' || error.kind === 'content' || error.kind === 'huge') {
      return false;
    }
    if (error.kind === 'http' && error.extra && error.extra.status != null) {
      const status = Number(error.extra.status);
      if (status < 500 && status !== 408 && status !== 425 && status !== 429) return false;
    }
    return true;
  }

  // 第一次 300ms,之后按 2^(n-2) 秒退避:300ms → 1s → 2s → 4s。
  function retryDelay(failures, error) {
    const delay = failures <= 1
      ? RETRY_BASE
      : Math.min(4000, Math.pow(2, failures - 2) * 1000);
    if (error && error.kind === 'rate') return Math.max(2000, delay);
    return delay;
  }

  function notifyRetry(failures, delay, opts) {
    if (opts && opts.silent) return;
    try { if (!state.open) return; } catch { return; }
    const label = delay < 1000 ? delay + 'ms' : (delay / 1000) + 's';
    toast('网络异常,' + label + ' 后重试(第 ' + failures + ' 次)');
  }

  async function apiGetInner(path, params, opts) {
    opts = opts || {};
    const retries = opts.retries == null ? 3 : opts.retries;
    let last = null;
    for (let attempt = 0; attempt <= retries; attempt++) {
      if (opts.signal && opts.signal.aborted) throw new LgError('abort', '已取消');
      try {
        return await apiFetch(path, params, opts);
      } catch (e) {
        last = e;
        if (!isRetryable(e)) throw e;
        if (attempt >= retries) break;
        const failures = attempt + 1;
        const delay = retryDelay(failures, e);
        notifyRetry(failures, delay, opts);
        await sleepAbortable(delay, opts.signal);
      }
    }
    throw last;
  }

  async function apiGet(path, params, opts) {
    opts = opts || {};
    const key = requestKey(path, params);
    // 带 signal 的请求属于某一次面板会话,关闭时会被取消,因此不做跨会话复用。
    const existing = inflight.get(key);
    if (existing && !opts.signal) return existing;
    const task = apiGetInner(path, params, opts);
    if (!opts.signal) inflight.set(key, task);
    try {
      return await task;
    } finally {
      if (!opts.signal && inflight.get(key) === task) inflight.delete(key);
    }
  }

  function loadConfig() {
    if (!configPromise) {
      configPromise = apiGet('/_lfe/config', {}, { retries: 1, silent: true })
        .then((cfg) => { applyConfig(cfg); return cfg; })
        .catch(() => null);
    }
    return configPromise;
  }

  let userCache;
  function saveUser(u) { storage.set('user', u); }

  async function getCurrentUser(signal) {
    if (userCache !== undefined) return userCache;

    const ctx = readLentilleContext();
    const ctxUser = ctx && ctx.user;
    if (ctxUser && ctxUser.name) {
      userCache = { uid: ctxUser.uid, name: ctxUser.name };
      saveUser(userCache);
      return userCache;
    }

    const inst = pageGlobal('_feInstance');
    const inj = pageGlobal('_feInjection');
    const cand = (inst && inst.currentUser) || (inj && inj.currentUser) || null;
    if (cand && cand.name) {
      userCache = { uid: cand.uid, name: cand.name };
      saveUser(userCache);
      return userCache;
    }

    const cached = storage.get('user', null);
    if (cached && cached.name) {
      userCache = { uid: cached.uid, name: cached.name };
      return userCache;
    }

    try {
      const res = await apiGet('/record/list', { page: 1 }, { signal: signal, lentille: true });
      const data = res.data || res.currentData || {};
      const u = res.user || res.currentUser;
      if (u && u.name) {
        userCache = { uid: u.uid, name: u.name };
        saveUser(userCache);
        return userCache;
      }
    } catch (e) {
      if (e instanceof LgError && e.kind === 'login') {
        userCache = null;
        throw e;
      }
    }
    userCache = null;
    return null;
  }

  function normalizeRecord(r) {
    return {
      id: Number(r.id),
      status: Number(r.status),
      score: r.score == null ? null : Number(r.score),
      time: r.time == null ? null : Number(r.time),
      memory: r.memory == null ? null : Number(r.memory),
      language: Number(r.language),
      submitTime: Number(r.submitTime),
      o2: !!r.enableO2,
      pid: r.problem ? r.problem.pid : null,
      title: r.problem ? (r.problem.title || r.problem.name || null) : null,
      user: r.user && r.user.uid != null ? { uid: Number(r.user.uid), name: r.user.name } : null,
      length: r.sourceCodeLength == null ? null : Number(r.sourceCodeLength)
    };
  }

  async function fetchRecordPage(pid, userParam, page, signal) {
    const res = await apiGet('/record/list', { pid: pid, user: userParam, page: page }, { signal: signal, lentille: true });
    const data = res.data || res.currentData || {};
    const list = data.records;
    if (!list) throw new LgError('api', '无法读取提交记录列表');
    const result = list.result;
    const arr = Array.isArray(result) ? result : Object.values(result || {});
    return {
      items: arr.map(normalizeRecord),
      count: Number(list.count) || 0,
      perPage: Number(list.perPage) || arr.length || 20
    };
  }

  const listCache = new Map();

  function listCacheKey(pid, user) {
    return pid + '|' + (user.uid != null ? 'u:' + user.uid : 'n:' + user.name);
  }

  function getCachedList(pid, user, limit) {
    const hit = listCache.get(listCacheKey(pid, user));
    if (!hit) return null;
    if (Date.now() - hit.at > LIST_TTL) {
      listCache.delete(listCacheKey(pid, user));
      return null;
    }
    if (!user.param) user.param = hit.param || (user.uid != null ? String(user.uid) : user.name);
    return {
      items: hit.items.slice(0, limit),
      total: hit.total,
      perPage: hit.perPage,
      pages: hit.pages,
      hasMore: hit.items.length < hit.total
    };
  }

  function saveListCache(pid, user, data) {
    listCache.set(listCacheKey(pid, user), {
      items: data.items.slice(),
      total: data.total,
      perPage: data.perPage,
      pages: data.pages,
      param: data.param || user.param,
      at: Date.now()
    });
  }

  async function loadRecords(pid, user, options) {
    options = options || {};
    const limit = options.limit || INITIAL_LIMIT;
    const signal = options.signal;

    // 同一道题 60s 内复用列表,避免每次打开面板都重复请求分页。
    if (!options.force) {
      const cached = getCachedList(pid, user, limit);
      if (cached) return cached;
    }

    let param = user.param || (user.uid != null ? String(user.uid) : user.name);

    let first = await fetchRecordPage(pid, param, 1, signal);
    const wrongUser = !!(first.items.length && user.uid != null
      && first.items[0].user && first.items[0].user.uid != null
      && Number(first.items[0].user.uid) !== Number(user.uid));
    // 洛谷的 user 参数在不同版本里可能是 uid 也可能是用户名,空结果/用户不符时换一种再试。
    if ((first.count === 0 || wrongUser) && user.name && String(param) !== user.name) {
      const alt = await fetchRecordPage(pid, user.name, 1, signal);
      if (alt.count > 0 || wrongUser) { param = user.name; first = alt; }
    }
    user.param = param;

    const perPage = first.perPage || 20;
    const total = Math.max(first.count, first.items.length);
    const pagesWanted = Math.max(1, Math.min(Math.ceil(limit / perPage), Math.ceil(total / perPage)));
    const items = first.items.slice();

    for (let page = 2; page <= pagesWanted; page++) {
      if (signal && signal.aborted) throw new LgError('abort', '已取消');
      await sleepAbortable(FETCH_GAP, signal);
      const res = await fetchRecordPage(pid, param, page, signal);
      items.push.apply(items, res.items);
      if (options.onProgress) options.onProgress(items.length, total);
    }

    const deduped = dedupeRecords(items);
    const result = {
      items: deduped.slice(0, limit),
      total: Math.max(total, deduped.length),
      perPage: perPage,
      pages: pagesWanted,
      hasMore: deduped.length < total,
      param: param
    };
    saveListCache(pid, user, result);
    return result;
  }

  async function loadMoreRecords(pid, user, fromPage, limit, signal) {
    const items = [];
    let page = fromPage;
    let total = 0;
    let perPage = 20;
    const param = user.param || (user.uid != null ? String(user.uid) : user.name);
    while (items.length < limit) {
      if (signal && signal.aborted) throw new LgError('abort', '已取消');
      await sleepAbortable(FETCH_GAP, signal);
      const res = await fetchRecordPage(pid, param, page, signal);
      total = Math.max(total, res.count);
      perPage = res.perPage || perPage;
      items.push.apply(items, res.items);
      page++;
      if (page > Math.ceil(total / perPage) || res.items.length === 0) break;
    }
    return { items: dedupeRecords(items), total: total, page: page - 1, perPage: perPage };
  }

  function dedupeRecords(items) {
    const seen = new Set();
    const out = [];
    for (const r of items) {
      if (seen.has(r.id)) continue;
      seen.add(r.id);
      out.push(r);
    }
    out.sort((a, b) => (b.submitTime - a.submitTime) || (b.id - a.id));
    return out;
  }

  const detailCache = new Map();
  const detailTasks = new Map();
  const codeCache = new Map();
  function getRecordDetail(id, signal) {
    const key = Number(id);
    if (detailCache.has(key)) return Promise.resolve(detailCache.get(key));
    if (detailTasks.has(key)) return detailTasks.get(key);

    const task = (async () => {
      const ctx = readLentilleContext();
      const ctxRecord = ctx && ctx.data && ctx.data.record;
      if (ctxRecord && Number(ctxRecord.id) === key && ctxRecord.problem && ctxRecord.submitTime) {
        detailCache.set(key, ctxRecord);
        if (typeof ctxRecord.sourceCode === 'string' && ctxRecord.sourceCode.length) {
          codeCache.set(key, ctxRecord.sourceCode);
        }
        return ctxRecord;
      }

      const res = await apiGet('/record/' + key, {}, { signal: signal, lentille: true });
      const data = res.data || res.currentData || {};
      const rec = data.record;
      if (!rec) throw new LgError('api', '无法读取该提交记录');
      detailCache.set(key, rec);
      if (typeof rec.sourceCode === 'string' && rec.sourceCode.length) {
        codeCache.set(key, rec.sourceCode);
      }
      return rec;
    })();

    detailTasks.set(key, task);
    const cleanup = () => {
      if (detailTasks.get(key) === task) detailTasks.delete(key);
    };
    task.then(cleanup, cleanup);
    return task;
  }

  async function getCode(id, signal) {
    if (codeCache.has(id)) return codeCache.get(id);

    const rec = await getRecordDetail(id, signal);
    if (typeof rec.sourceCode === 'string' && rec.sourceCode.length) {
      codeCache.set(id, rec.sourceCode);
      return rec.sourceCode;
    }

    // 少数页面会把代码直接注入 _feInjection,作为兜底。
    const inj = pageGlobal('_feInjection');
    const cur = inj && inj.currentData && inj.currentData.record;
    if (cur && Number(cur.id) === Number(id) && typeof cur.sourceCode === 'string' && cur.sourceCode.length) {
      codeCache.set(id, cur.sourceCode);
      return cur.sourceCode;
    }

    throw new LgError('code', '这条提交的代码不可见(可能未公开,或不是你的提交)');
  }

  /* ------------------------------------------------------------------ *
   *  行级 diff(Myers + 小区间 LCS DP)
   * ------------------------------------------------------------------ */

  function splitLines(text) {
    if (text == null) return [];
    const s = String(text).replace(/\r\n?/g, '\n');
    if (s === '') return [];
    const lines = s.split('\n');
    if (lines.length && lines[lines.length - 1] === '') lines.pop();
    return lines;
  }

  function canonLine(line) {
    return line.replace(/[ \t]+/g, ' ').trim();
  }

  function diffSmall(a, b, aLo, aHi, bLo, bHi, eq, ops) {
    const n = aHi - aLo;
    const m = bHi - bLo;
    const w = m + 1;
    const dp = new Uint32Array((n + 1) * w);
    for (let i = n - 1; i >= 0; i--) {
      for (let j = m - 1; j >= 0; j--) {
        const idx = i * w + j;
        if (eq(aLo + i, bLo + j)) dp[idx] = dp[(i + 1) * w + j + 1] + 1;
        else dp[idx] = Math.max(dp[(i + 1) * w + j], dp[i * w + j + 1]);
      }
    }
    let i = 0;
    let j = 0;
    while (i < n && j < m) {
      if (eq(aLo + i, bLo + j)) {
        ops.push({ t: '=', ai: aLo + i, bi: bLo + j });
        i++; j++;
      } else if (dp[(i + 1) * w + j] >= dp[i * w + j + 1]) {
        ops.push({ t: '-', ai: aLo + i, bi: bLo + j });
        i++;
      } else {
        ops.push({ t: '+', ai: aLo + i, bi: bLo + j });
        j++;
      }
    }
    while (i < n) { ops.push({ t: '-', ai: aLo + i, bi: bLo + j }); i++; }
    while (j < m) { ops.push({ t: '+', ai: aLo + i, bi: bLo + j }); j++; }
  }

  // Myers 的线性空间 middle-snake 分割,返回把两个区间切成两半的坐标。
  function bisect(a, b, aLo, aHi, bLo, bHi, eq) {
    const n = aHi - aLo;
    const m = bHi - bLo;
    const maxD = Math.ceil((n + m) / 2);
    const vOffset = maxD;
    const vLength = 2 * maxD + 2;
    const v1 = new Int32Array(vLength).fill(-1);
    const v2 = new Int32Array(vLength).fill(-1);
    v1[vOffset + 1] = 0;
    v2[vOffset + 1] = 0;

    const delta = n - m;
    const front = (delta & 1) !== 0;
    let k1start = 0, k1end = 0, k2start = 0, k2end = 0;

    for (let d = 0; d < maxD; d++) {
      for (let k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
        const k1off = vOffset + k1;
        let x1;
        if (k1 === -d || (k1 !== d && v1[k1off - 1] < v1[k1off + 1])) x1 = v1[k1off + 1];
        else x1 = v1[k1off - 1] + 1;
        let y1 = x1 - k1;
        while (x1 < n && y1 < m && eq(aLo + x1, bLo + y1)) { x1++; y1++; }
        v1[k1off] = x1;

        if (x1 > n) k1end += 2;
        else if (y1 > m) k1start += 2;
        else if (front) {
          const k2off = vOffset + delta - k1;
          if (k2off >= 0 && k2off < vLength && v2[k2off] !== -1) {
            const x2 = n - v2[k2off];
            if (x1 >= x2) return [aLo + x1, bLo + y1];
          }
        }
      }

      for (let k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
        const k2off = vOffset + k2;
        let x2;
        if (k2 === -d || (k2 !== d && v2[k2off - 1] < v2[k2off + 1])) x2 = v2[k2off + 1];
        else x2 = v2[k2off - 1] + 1;
        let y2 = x2 - k2;
        while (x2 < n && y2 < m && eq(aHi - 1 - x2, bHi - 1 - y2)) { x2++; y2++; }
        v2[k2off] = x2;

        if (x2 > n) k2end += 2;
        else if (y2 > m) k2start += 2;
        else if (!front) {
          const k1off = vOffset + delta - k2;
          if (k1off >= 0 && k1off < vLength && v1[k1off] !== -1) {
            const x1 = v1[k1off];
            const y1 = x1 - (delta - k2);
            if (x1 >= n - x2) return [aLo + x1, bLo + y1];
          }
        }
      }
    }
    return null;
  }

  function diffRange(a, b, aLo, aHi, bLo, bHi, eq, ops) {
    while (aLo < aHi && bLo < bHi && eq(aLo, bLo)) {
      ops.push({ t: '=', ai: aLo, bi: bLo });
      aLo++; bLo++;
    }

    let suf = 0;
    while (aLo < aHi - suf && bLo < bHi - suf && eq(aHi - 1 - suf, bHi - 1 - suf)) suf++;
    const aEnd = aHi - suf;
    const bEnd = bHi - suf;

    if (aLo >= aEnd) {
      for (let j = bLo; j < bEnd; j++) ops.push({ t: '+', ai: aLo, bi: j });
    } else if (bLo >= bEnd) {
      for (let i = aLo; i < aEnd; i++) ops.push({ t: '-', ai: i, bi: bLo });
    } else {
      const n = aEnd - aLo;
      const m = bEnd - bLo;
      if (n * m <= 16000) {
        diffSmall(a, b, aLo, aEnd, bLo, bEnd, eq, ops);
      } else {
        const split = bisect(a, b, aLo, aEnd, bLo, bEnd, eq);
        const useless = !split || (split[0] === aLo && split[1] === bLo) || (split[0] === aEnd && split[1] === bEnd);
        if (useless) {
          for (let i = aLo; i < aEnd; i++) ops.push({ t: '-', ai: i, bi: bLo });
          for (let j = bLo; j < bEnd; j++) ops.push({ t: '+', ai: aEnd, bi: j });
        } else {
          diffRange(a, b, aLo, split[0], bLo, split[1], eq, ops);
          diffRange(a, b, split[0], aEnd, split[1], bEnd, eq, ops);
        }
      }
    }

    for (let k = 0; k < suf; k++) ops.push({ t: '=', ai: aEnd + k, bi: bEnd + k });
  }

  function diffLines(aLines, bLines, ignoreWhitespace) {
    const a = ignoreWhitespace ? aLines.map(canonLine) : aLines;
    const b = ignoreWhitespace ? bLines.map(canonLine) : bLines;
    const eq = (i, j) => a[i] === b[j];
    const ops = [];
    diffRange(a, b, 0, a.length, 0, b.length, eq, ops);
    return ops;
  }

  function buildRuns(ops) {
    const runs = [];
    for (const op of ops) {
      const last = runs[runs.length - 1];
      if (op.t === '=') {
        if (last && last.type === '=' && last.aEnd === op.ai && last.bEnd === op.bi) {
          last.aEnd++; last.bEnd++;
        } else {
          runs.push({ type: '=', aStart: op.ai, aEnd: op.ai + 1, bStart: op.bi, bEnd: op.bi + 1 });
        }
      } else if (op.t === '-') {
        if (last && last.type === '-' && last.aEnd === op.ai) {
          last.aEnd++;
        } else {
          runs.push({ type: '-', aStart: op.ai, aEnd: op.ai + 1, bStart: op.bi, bEnd: op.bi });
        }
      } else {
        if (last && last.type === '+' && last.bEnd === op.bi) {
          last.bEnd++;
        } else {
          runs.push({ type: '+', aStart: op.ai, aEnd: op.ai, bStart: op.bi, bEnd: op.bi + 1 });
        }
      }
    }
    return runs;
  }

  function buildHunks(runs, context, totalA, totalB) {
    const changed = [];
    for (let i = 0; i < runs.length; i++) {
      if (runs[i].type !== '=') changed.push(i);
    }
    if (!changed.length) return [];

    const groups = [];
    let start = changed[0];
    let end = changed[0];
    for (let k = 1; k < changed.length; k++) {
      const idx = changed[k];
      let gap = 0;
      for (let r = end + 1; r < idx; r++) {
        if (runs[r].type === '=') gap += runs[r].aEnd - runs[r].aStart;
      }
      if (gap <= context * 2) {
        end = idx;
      } else {
        groups.push([start, end]);
        start = idx; end = idx;
      }
    }
    groups.push([start, end]);

    return groups.map(([s, e]) => {
      const first = runs[s];
      const last = runs[e];
      return {
        aStart: Math.max(0, first.aStart - context),
        bStart: Math.max(0, first.bStart - context),
        aEnd: Math.min(totalA, last.aEnd + context),
        bEnd: Math.min(totalB, last.bEnd + context)
      };
    });
  }

  function hunkRows(runs, hunk, aLines, bLines) {
    const rows = [];
    for (const run of runs) {
      if (run.type === '=') {
        if (run.aEnd <= hunk.aStart || run.aStart >= hunk.aEnd) continue;
        const from = Math.max(run.aStart, hunk.aStart);
        const to = Math.min(run.aEnd, hunk.aEnd);
        for (let i = from; i < to; i++) {
          rows.push({
            type: '=',
            aNo: i + 1,
            bNo: run.bStart + (i - run.aStart) + 1,
            text: aLines[i]
          });
        }
      } else if (run.type === '-') {
        if (run.aEnd <= hunk.aStart || run.aStart >= hunk.aEnd) continue;
        const from = Math.max(run.aStart, hunk.aStart);
        const to = Math.min(run.aEnd, hunk.aEnd);
        for (let i = from; i < to; i++) rows.push({ type: '-', aNo: i + 1, bNo: 0, text: aLines[i] });
      } else {
        if (run.bEnd <= hunk.bStart || run.bStart >= hunk.bEnd) continue;
        const from = Math.max(run.bStart, hunk.bStart);
        const to = Math.min(run.bEnd, hunk.bEnd);
        for (let j = from; j < to; j++) rows.push({ type: '+', aNo: 0, bNo: j + 1, text: bLines[j] });
      }
    }
    return rows;
  }

  function buildRows(runs, aLines, bLines, fold, context) {
    const totalA = aLines.length;
    const totalB = bLines.length;
    const hunks = fold ? buildHunks(runs, context, totalA, totalB) : [{ aStart: 0, aEnd: totalA, bStart: 0, bEnd: totalB }];
    const rows = [];

    if (!hunks.length) return { rows: rows, hunks: hunks };

    let lastA = 0;
    for (const hunk of hunks) {
      if (fold && hunk.aStart > lastA) {
        rows.push({ type: 'gap', count: hunk.aStart - lastA, text: '' });
      }
      rows.push.apply(rows, hunkRows(runs, hunk, aLines, bLines));
      lastA = hunk.aEnd;
    }
    if (fold && lastA < totalA) {
      rows.push({ type: 'gap', count: totalA - lastA, text: '' });
    }
    return { rows: rows, hunks: hunks };
  }

  function lineSimilarity(a, b) {
    const ta = tokenize(a).filter((t) => t.trim() !== '');
    const tb = tokenize(b).filter((t) => t.trim() !== '');
    if (!ta.length || !tb.length) return 0;
    const counts = new Map();
    for (const t of ta) counts.set(t, (counts.get(t) || 0) + 1);
    let inter = 0;
    for (const t of tb) {
      const c = counts.get(t) || 0;
      if (c > 0) { inter++; counts.set(t, c - 1); }
    }
    return (2 * inter) / (ta.length + tb.length);
  }

  function alignChangeBlock(dels, inss, out) {
    const n = dels.length;
    const m = inss.length;
    if (n === 1 && m === 1) {
      out.push({ type: 'chg', l: dels[0], r: inss[0] });
      return;
    }
    if (!n || !m || n * m > 25000) {
      for (const d of dels) out.push({ type: 'del', l: d, r: null });
      for (const s of inss) out.push({ type: 'ins', l: null, r: s });
      return;
    }

    const score = [];
    const choice = [];
    for (let i = 0; i <= n; i++) {
      score.push(new Float64Array(m + 1));
      choice.push(new Uint8Array(m + 1));
    }
    for (let i = n - 1; i >= 0; i--) {
      for (let j = m - 1; j >= 0; j--) {
        let best = score[i + 1][j];
        let pick = 0; // skip a deletion
        if (score[i][j + 1] > best + 1e-9) {
          best = score[i][j + 1];
          pick = 1; // skip an insertion
        }
        const sim = lineSimilarity(dels[i].text, inss[j].text);
        if (sim >= 0.3) {
          const v = score[i + 1][j + 1] + sim;
          if (v >= best - 1e-9) {
            best = v;
            pick = 2; // pair them
          }
        }
        score[i][j] = best;
        choice[i][j] = pick;
      }
    }

    let i = 0;
    let j = 0;
    while (i < n || j < m) {
      let pick;
      if (i >= n) pick = 1;
      else if (j >= m) pick = 0;
      else pick = choice[i][j];

      if (pick === 2) {
        out.push({ type: 'chg', l: dels[i], r: inss[j] });
        i++; j++;
      } else if (pick === 0) {
        out.push({ type: 'del', l: dels[i], r: null });
        i++;
      } else {
        out.push({ type: 'ins', l: null, r: inss[j] });
        j++;
      }
    }
  }

  function buildSplitRows(rows) {
    const out = [];
    for (let i = 0; i < rows.length; i++) {
      const row = rows[i];
      if (row.type === '=') {
        out.push({
          type: 'eq',
          l: { no: row.aNo, text: row.text },
          r: { no: row.bNo, text: row.text }
        });
        continue;
      }
      if (row.type === 'gap') { out.push(row); continue; }

      const dels = [];
      const inss = [];
      while (i < rows.length && (rows[i].type === '-' || rows[i].type === '+')) {
        if (rows[i].type === '-') dels.push({ no: rows[i].aNo, text: rows[i].text });
        else inss.push({ no: rows[i].bNo, text: rows[i].text });
        i++;
      }
      i--;
      alignChangeBlock(dels, inss, out);
    }
    return out;
  }

  function diffStats(rows) {
    let add = 0, del = 0;
    for (const row of rows) {
      if (row.type === '+') add++;
      else if (row.type === '-') del++;
    }
    return { add: add, del: del };
  }

  function runStats(runs) {
    let add = 0, del = 0;
    for (const run of runs) {
      if (run.type === '-') del += run.aEnd - run.aStart;
      else if (run.type === '+') add += run.bEnd - run.bStart;
    }
    return { add: add, del: del };
  }

  function tokenize(line) {
    return line.match(/\s+|[A-Za-z_$][\w$]*|\d+|[^\sA-Za-z0-9_$]/g) || [];
  }

  function inlinePair(aText, bText) {
    if (aText.length > 600 || bText.length > 600) return null;
    const a = tokenize(aText);
    const b = tokenize(bText);
    if (!a.length || !b.length || a.length > 220 || b.length > 220) return null;

    const ops = [];
    diffRange(a, b, 0, a.length, 0, b.length, (i, j) => a[i] === b[j], ops);

    let matched = 0;
    for (const op of ops) if (op.t === '=') matched++;
    if (matched / Math.max(a.length, b.length) < 0.3) return null;

    const aSeg = [];
    const bSeg = [];

    function push(seg, text, changed) {
      const last = seg[seg.length - 1];
      if (last && last.changed === changed) last.text += text;
      else seg.push({ text: text, changed: changed });
    }

    for (const op of ops) {
      if (op.t === '=') {
        push(aSeg, a[op.ai], false);
        push(bSeg, b[op.bi], false);
      } else if (op.t === '-') {
        push(aSeg, a[op.ai], true);
      } else {
        push(bSeg, b[op.bi], true);
      }
    }

    const toHtml = (seg) => seg.map((s) => (s.changed ? '<mark>' + esc(s.text) + '</mark>' : esc(s.text))).join('');
    return { a: toHtml(aSeg), b: toHtml(bSeg) };
  }

  function toUnifiedDiff(runs, aLines, bLines, oldName, newName, context) {
    const hunks = buildHunks(runs, context == null ? CONTEXT : context, aLines.length, bLines.length);
    let out = '--- ' + oldName + '\n+++ ' + newName + '\n';
    for (const hunk of hunks) {
      const aLen = hunk.aEnd - hunk.aStart;
      const bLen = hunk.bEnd - hunk.bStart;
      const aHead = aLen === 0 ? hunk.aStart + ',0' : (hunk.aStart + 1) + ',' + aLen;
      const bHead = bLen === 0 ? hunk.bStart + ',0' : (hunk.bStart + 1) + ',' + bLen;
      out += '@@ -' + aHead + ' +' + bHead + ' @@\n';
      for (const row of hunkRows(runs, hunk, aLines, bLines)) {
        if (row.type === '=') out += ' ' + row.text + '\n';
        else if (row.type === '-') out += '-' + row.text + '\n';
        else out += '+' + row.text + '\n';
      }
    }
    return out;
  }

  function computeDiff(oldText, newText, ignoreWhitespace) {
    const aLines = splitLines(oldText);
    const bLines = splitLines(newText);
    const ops = diffLines(aLines, bLines, ignoreWhitespace);
    const runs = buildRuns(ops);
    return { aLines: aLines, bLines: bLines, ops: ops, runs: runs };
  }

  /* ------------------------------------------------------------------ *
   *  路由
   * ------------------------------------------------------------------ */

  function parseRoute(loc) {
    loc = loc || location;
    const path = loc.pathname.replace(/\/+$/, '') || '/';
    let m = path.match(/^\/problem\/([^/]+)$/);
    if (m) {
      const pid = decodeURIComponent(m[1]);
      if (pid === 'list' || pid === 'new' || pid === 'random') return null;
      return { kind: 'problem', pid: pid };
    }
    m = path.match(/^\/record\/(\d+)$/);
    if (m) return { kind: 'record', rid: Number(m[1]) };
    if (path === '/record/list') {
      const pid = new URLSearchParams(loc.search).get('pid');
      if (pid) return { kind: 'list', pid: pid };
    }
    return null;
  }

  function pageProblemTitle(pid) {
    let raw = (document.title || '').replace(/\s*[-–—]\s*洛谷.*$/, '').trim();
    if (pid) {
      const head = String(pid).toLowerCase();
      if (raw.toLowerCase().startsWith(head)) {
        raw = raw.slice(String(pid).length).replace(/^[\s·::\-–—]+/, '').trim();
      } else if (!raw.toLowerCase().includes(head)) {
        return pid;
      }
    }
    return raw || pid;
  }

  /* ------------------------------------------------------------------ *
   *  图标
   * ------------------------------------------------------------------ */

  const SVG_ATTR = 'class="lgvd-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"';

  const ICON = {
    compare: '<svg ' + SVG_ATTR + '><circle cx="18" cy="18" r="3"/><circle cx="6" cy="6" r="3"/><path d="M13 6h3a2 2 0 0 1 2 2v7"/><path d="M11 18H8a2 2 0 0 1-2-2V9"/></svg>',
    close: '<svg ' + SVG_ATTR + '><path d="M18 6 6 18"/><path d="M6 6l12 12"/></svg>',
    refresh: '<svg ' + SVG_ATTR + '><path d="M21 12a9 9 0 1 1-2.64-6.36"/><path d="M21 3v6h-6"/></svg>',
    swap: '<svg ' + SVG_ATTR + '><path d="m8 3-4 4 4 4"/><path d="M4 7h16"/><path d="m16 21 4-4-4-4"/><path d="M20 17H4"/></svg>',
    copy: '<svg ' + SVG_ATTR + '><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>',
    download: '<svg ' + SVG_ATTR + '><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m7 10 5 5 5-5"/><path d="M12 15V3"/></svg>',
    check: '<svg ' + SVG_ATTR + '><path d="M20 6 9 17l-5-5"/></svg>'
  };

  /* ------------------------------------------------------------------ *
   *  CSS
   * ------------------------------------------------------------------ */

  const CSS = `
    :host {
      all: initial;
    }
    .lgvd-root {
      --bg: #ffffff;      --bg-soft: #f7f8fa;
      --bg-code: #ffffff;
      --text: #1f2328;
      --muted: #6b7280;
      --border: #e5e7eb;
      --border-strong: #d1d5db;
      --hover: #eef1f5;
      --accent: #2563eb;
      --accent-soft: #eff6ff;
      --accent-soft-border: #bfdbfe;
      --danger: #dc2626;
      --ok: #15803d;
      --add-bg: #e9fbef;
      --add-border: #b7efc5;
      --add-ln: #d8f8e2;
      --del-bg: #fff0ef;
      --del-border: #ffc9c4;
      --del-ln: #ffe0dd;
      --mark-add: #9ef0b4;
      --mark-del: #ffb3ad;
      --empty: #fafafa;
      --shadow: 0 30px 90px rgba(15, 23, 42, .45), 0 0 0 1px rgba(15, 23, 42, .08);
      --st-grey-bg: #eceff3; --st-grey-fg: #4b5563;
      --st-blue-bg: #e3efff; --st-blue-fg: #1d4ed8;
      --st-yellow-bg: #fff4d6; --st-yellow-fg: #a16207;
      --st-red-bg: #ffe6e4; --st-red-fg: #c2410c;
      --st-purple-bg: #f0e9ff; --st-purple-fg: #7c3aed;
      --st-green-bg: #dcf7e3; --st-green-fg: #15803d;
      --st-lapis-bg: #e4e9ff; --st-lapis-fg: #4338ca;
      --mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", "Courier New", monospace;
      --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
      position: fixed;
      inset: 0;
      z-index: 2147483647;
      pointer-events: none;
      font-family: var(--sans);
      color: var(--text);
      font-size: 14px;
      line-height: 1.45;
      -webkit-font-smoothing: antialiased;
    }
    .lgvd-root.dark {
      --bg: #0d1117;
      --bg-soft: #151b23;
      --bg-code: #0d1117;
      --text: #e6edf3;
      --muted: #8b949e;
      --border: #30363d;
      --border-strong: #484f58;
      --hover: #1b2230;
      --accent: #58a6ff;
      --accent-soft: rgba(56, 139, 253, .14);
      --accent-soft-border: rgba(56, 139, 253, .4);
      --danger: #f85149;
      --ok: #3fb950;
      --add-bg: rgba(46, 160, 67, .16);
      --add-border: rgba(46, 160, 67, .45);
      --add-ln: rgba(46, 160, 67, .24);
      --del-bg: rgba(248, 81, 73, .16);
      --del-border: rgba(248, 81, 73, .45);
      --del-ln: rgba(248, 81, 73, .24);
      --mark-add: rgba(46, 160, 67, .5);
      --mark-del: rgba(248, 81, 73, .5);
      --empty: #11161d;
      --shadow: 0 30px 90px rgba(0, 0, 0, .6), 0 0 0 1px rgba(255, 255, 255, .06);
      --st-grey-bg: #21262d; --st-grey-fg: #9ca3af;
      --st-blue-bg: rgba(56, 139, 253, .2); --st-blue-fg: #79c0ff;
      --st-yellow-bg: rgba(187, 128, 9, .25); --st-yellow-fg: #e3b341;
      --st-red-bg: rgba(248, 81, 73, .2); --st-red-fg: #ff7b72;
      --st-purple-bg: rgba(163, 113, 247, .22); --st-purple-fg: #d2a8ff;
      --st-green-bg: rgba(46, 160, 67, .22); --st-green-fg: #7ee787;
      --st-lapis-bg: rgba(99, 102, 241, .25); --st-lapis-fg: #a5b4fc;
    }
    * { box-sizing: border-box; }
    button { font: inherit; }

    .lgvd-launch {
      position: fixed;
      right: 24px;
      bottom: 92px;
      z-index: 2147483647;
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 10px 15px;
      border: 0;
      border-radius: 999px;
      background: linear-gradient(135deg, #2563eb, #6d28d9);
      color: #fff;
      font-size: 13px;
      font-weight: 600;
      letter-spacing: .2px;
      cursor: pointer;
      pointer-events: auto;
      box-shadow: 0 8px 24px rgba(37, 99, 235, .38), 0 2px 6px rgba(15, 23, 42, .2);
      transition: transform .16s ease, box-shadow .16s ease, opacity .16s ease;
    }
    .lgvd-launch:hover {
      transform: translateY(-2px);
      box-shadow: 0 12px 30px rgba(37, 99, 235, .46), 0 3px 8px rgba(15, 23, 42, .22);
    }
    .lgvd-launch:active { transform: translateY(0); }
    .lgvd-launch[hidden] { display: none; }
    .lgvd-launch .lgvd-ico { width: 18px; height: 18px; }

    .lgvd-modal { position: fixed; inset: 0; pointer-events: auto; }
    .lgvd-modal[hidden] { display: none; }
    .lgvd-backdrop {
      position: absolute;
      inset: 0;
      z-index: 0;
      background: rgba(9, 14, 24, .52);
      animation: lgvd-fade .18s ease both;
    }
    .lgvd-panel {
      position: absolute;
      left: 50%;
      top: 50%;
      z-index: 1;
      transform: translate(-50%, -50%);
      width: min(1440px, calc(100vw - 44px));
      height: min(860px, calc(100vh - 52px));
      display: flex;
      flex-direction: column;
      overflow: hidden;
      background: var(--bg);
      border: 1px solid var(--border);
      border-radius: 4px;
      box-shadow: var(--shadow);
      animation: lgvd-pop .2s cubic-bezier(.2, .8, .2, 1) both;
    }
    .lgvd-head {
      flex: none;
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 16px;
      padding: 13px 20px;
      border-bottom: 1px solid var(--border);
      background: var(--bg-soft);
    }
    .lgvd-brand { display: flex; align-items: center; gap: 12px; min-width: 0; }
    .lgvd-mark {
      flex: none;
      width: 38px; height: 38px;
      display: grid; place-items: center;
      border-radius: 11px;
      background: linear-gradient(135deg, #2563eb, #7c3aed);
      color: #fff;
      /* box-shadow: 0 4px 12px rgba(37, 99, 235, .32); */
    }
    .lgvd-mark .lgvd-ico { width: 20px; height: 20px; }
    .lgvd-brand-text { min-width: 0; }
    .lgvd-brand-text h2 { margin: 0; font-size: 16px; font-weight: 650; letter-spacing: .2px; }
    .lgvd-sub {
      display: flex; align-items: center; gap: 6px;
      margin-top: 2px; font-size: 12px; color: var(--muted);
      max-width: 760px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
    }
    .lgvd-pid { color: var(--accent); font-weight: 650; text-decoration: none; }
    .lgvd-pid:hover { text-decoration: underline; }
    .lgvd-sep { opacity: .5; }
    .lgvd-head-actions { display: flex; align-items: center; gap: 6px; }
    .lgvd-ver { font-size: 10.5px; color: var(--muted); margin-right: 4px; }
    .lgvd-icon {
      width: 30px; height: 30px; display: grid; place-items: center;
      border: 1px solid transparent; border-radius: 8px;
      background: transparent; color: var(--muted); cursor: pointer;
    }
    .lgvd-icon:hover { background: var(--hover); color: var(--text); }
    .lgvd-icon .lgvd-ico { width: 17px; height: 17px; }

    .lgvd-body { flex: 1; min-height: 0; display: flex; }

    .lgvd-side {
      flex: none;
      width: var(--side-w, 344px);
      min-width: 220px;
      max-width: 760px;
      min-height: 0;
      display: flex;
      flex-direction: column;
      border-right: 0;
      background: var(--bg-soft);
      color: var(--text);
    }
    .lgvd-resizer {
      flex: 0 0 7px;
      position: relative;
      cursor: col-resize;
      background: var(--bg-soft);
      touch-action: none;
      user-select: none;
    }
    .lgvd-resizer::before {
      content: "";
      position: absolute;
      top: 0;
      bottom: 0;
      left: 3px;
      width: 1px;
      background: var(--border);
      transition: left .12s ease, width .12s ease, background .12s ease;
    }
    .lgvd-resizer:hover::before,
    .lgvd-resizer.dragging::before {
      left: 1px;
      width: 5px;
      background: var(--accent);
      border-radius: 3px;
    }
    .lgvd-resizer:focus-visible { outline: 2px solid var(--accent); outline-offset: -3px; }
    .lgvd-side-head {
      flex: none;
      display: flex; align-items: center; justify-content: space-between; gap: 8px;
      padding: 11px 14px;
      border-bottom: 1px solid var(--border);
    }
    .lgvd-user { display: flex; align-items: center; gap: 8px; min-width: 0; font-size: 12px; font-weight: 600; }
    .lgvd-avatar {
      flex: none; width: 22px; height: 22px; border-radius: 50%;
      display: grid; place-items: center;
      background: var(--accent); color: #fff; font-size: 11px; font-weight: 700;
    }
    .lgvd-user-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .lgvd-switch { display: inline-flex; align-items: center; gap: 5px; font-size: 11.5px; color: var(--muted); cursor: pointer; user-select: none; white-space: nowrap; }
    .lgvd-switch input { width: 13px; height: 13px; accent-color: var(--accent); margin: 0; }

    .lgvd-quick { flex: none; display: flex; gap: 6px; padding: 8px 12px 6px; }
    .lgvd-quick button {
      flex: 1;
      padding: 5px 6px;
      border: 1px solid var(--border);
      border-radius: 7px;
      background: var(--bg);
      color: var(--muted);
      font-size: 11.5px;
      cursor: pointer;
      white-space: nowrap;
    }
    .lgvd-quick button:hover { border-color: var(--border-strong); color: var(--text); background: var(--hover); }

    .lgvd-selbar {
      flex: none;
      display: flex; align-items: center; gap: 6px; flex-wrap: wrap;
      min-height: 38px;
      padding: 4px 14px 8px;
      font-size: 11.5px;
      color: var(--muted);
    }
    .lgvd-chip {
      display: inline-flex; align-items: center; gap: 5px;
      padding: 3px 8px 3px 5px;
      border: 1px solid var(--border);
      border-radius: 999px;
      background: var(--bg);
      color: var(--text);
      font-family: var(--mono);
      font-size: 11px;
    }
    .lgvd-chip .tag {
      width: 16px; height: 16px; display: grid; place-items: center;
      border-radius: 50%; color: #fff; font-family: var(--sans); font-size: 9.5px; font-weight: 800;
    }
    .lgvd-chip.a .tag { background: #d97706; }
    .lgvd-chip.b .tag { background: #2563eb; }
    .lgvd-chip em { font-style: normal; font-family: var(--sans); font-size: 10px; padding: 1px 4px; border-radius: 4px; }
    .lgvd-chip-rid { color: inherit; text-decoration: none; font-family: var(--mono); }
    .lgvd-chip-rid:hover { color: var(--accent); text-decoration: underline; }
    .lgvd-chip em.grey { background: var(--st-grey-bg); color: var(--st-grey-fg); }
    .lgvd-chip em.blue { background: var(--st-blue-bg); color: var(--st-blue-fg); }
    .lgvd-chip em.yellow { background: var(--st-yellow-bg); color: var(--st-yellow-fg); }
    .lgvd-chip em.red { background: var(--st-red-bg); color: var(--st-red-fg); }
    .lgvd-chip em.purple { background: var(--st-purple-bg); color: var(--st-purple-fg); }
    .lgvd-chip em.green { background: var(--st-green-bg); color: var(--st-green-fg); }
    .lgvd-chip em.lapis { background: var(--st-lapis-bg); color: var(--st-lapis-fg); }
    .lgvd-chip-arrow { color: var(--muted); font-family: var(--mono); }
    .lgvd-mini {
      width: 22px; height: 22px; display: grid; place-items: center;
      border: 1px solid var(--border); border-radius: 6px;
      background: var(--bg); color: var(--muted); cursor: pointer;
    }
    .lgvd-mini:hover { color: var(--text); background: var(--hover); }
    .lgvd-mini .lgvd-ico { width: 13px; height: 13px; }
    .lgvd-selbar .hint { color: var(--muted); }

    .lgvd-list { flex: 1; min-height: 0; overflow: auto; padding: 2px 10px 10px; scrollbar-width: thin; }
    .lgvd-list::-webkit-scrollbar { width: 9px; height: 9px; }
    .lgvd-list::-webkit-scrollbar-thumb { background: var(--border-strong); border-radius: 8px; border: 2px solid var(--bg-soft); }
    .lgvd-rec {
      width: 100%;
      display: grid;
      grid-template-columns: 43px minmax(0, 1fr) 22px;
      gap: 8px;
      align-items: center;
      margin: 3px 0;
      padding: 6px 7px;
      border: 1px solid transparent;
      border-radius: 9px;
      background: transparent;
      color: inherit;
      text-align: left;
      cursor: pointer;
      font: inherit;
      transition: background .12s ease, border-color .12s ease;
    }
    .lgvd-rec:hover { background: var(--hover); }
    .lgvd-rec.on { background: var(--accent-soft); border-color: var(--accent-soft-border); }
    .lgvd-rec:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
    .lgvd-badge {
      display: inline-flex; align-items: center; justify-content: center;
      height: 21px; padding: 0 3px;
      border-radius: 5px;
      font-size: 10px; font-weight: 800; letter-spacing: .2px;
      overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
    }
    .lgvd-badge.grey { background: var(--st-grey-bg); color: var(--st-grey-fg); }
    .lgvd-badge.blue { background: var(--st-blue-bg); color: var(--st-blue-fg); }
    .lgvd-badge.yellow { background: var(--st-yellow-bg); color: var(--st-yellow-fg); }
    .lgvd-badge.red { background: var(--st-red-bg); color: var(--st-red-fg); }
    .lgvd-badge.purple { background: var(--st-purple-bg); color: var(--st-purple-fg); }
    .lgvd-badge.green { background: var(--st-green-bg); color: var(--st-green-fg); }
    .lgvd-badge.lapis { background: var(--st-lapis-bg); color: var(--st-lapis-fg); }
    .lgvd-rec-body { min-width: 0; display: flex; flex-direction: column; gap: 1px; }
    .lgvd-rec-line1 { display: flex; align-items: center; gap: 6px; min-width: 0; font-size: 12px; }
    .lgvd-rec-line1 b { font-weight: 650; font-family: var(--mono); font-size: 11.5px; color: var(--text); }
    .lgvd-rid {
      font-family: var(--mono);
      font-size: 11.5px;
      font-weight: 650;
      color: var(--text);
      text-decoration: none;
      border-bottom: 1px dashed transparent;
      border-radius: 3px;
    }
    .lgvd-rid:hover {
      color: var(--accent);
      border-bottom-color: var(--accent);
    }
    .lgvd-rid:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
    .lgvd-lang {
      overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
      font-size: 10px; color: var(--muted);
      padding: 0 4px; border: 1px solid var(--border); border-radius: 4px;
      line-height: 15px;
    }
    .lgvd-o2 { font-size: 9px; font-weight: 700; color: var(--accent); border: 1px solid var(--accent-soft-border); border-radius: 4px; padding: 0 3px; line-height: 14px; }
    .lgvd-rec-line2 { font-size: 10.5px; color: var(--muted); font-family: var(--mono); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
    .lgvd-slot {
      width: 20px; height: 20px; border-radius: 50%;
      display: grid; place-items: center;
      border: 1.5px dashed var(--border-strong);
      color: transparent;
      font-size: 9.5px; font-weight: 800;
      transition: all .12s ease;
    }
    .lgvd-rec.on .lgvd-slot { border-style: solid; border-color: transparent; color: #fff; }
    .lgvd-rec.on.a .lgvd-slot { background: #d97706; }
    .lgvd-rec.on.b .lgvd-slot { background: #2563eb; }

    .lgvd-side-foot {
      flex: none;
      display: flex; align-items: center; justify-content: space-between; gap: 8px;
      padding: 9px 14px;
      border-top: 1px solid var(--border);
      font-size: 11px;
      color: var(--muted);
    }
    .lgvd-side-foot a { color: var(--accent); text-decoration: none; }
    .lgvd-side-foot a:hover { text-decoration: underline; }
    .lgvd-more {
      border: 1px solid var(--border); background: var(--bg); color: var(--text);
      padding: 3px 8px; border-radius: 6px; font-size: 11px; cursor: pointer;
    }
    .lgvd-more:hover { background: var(--hover); }
    .lgvd-skel {
      height: 44px; margin: 6px 4px; border-radius: 8px;
      background: linear-gradient(100deg, var(--bg-soft) 20%, var(--hover) 40%, var(--bg-soft) 60%);
      background-size: 200% 100%;
      animation: lgvd-shimmer 1.3s linear infinite;
    }

    .lgvd-main { flex: 1; min-width: 0; min-height: 0; display: flex; flex-direction: column; }
    .lgvd-toolbar {
      flex: none;
      display: flex; align-items: center; gap: 10px; flex-wrap: wrap;
      padding: 9px 16px;
      border-bottom: 1px solid var(--border);
      background: var(--bg);
    }
    .lgvd-seg { display: inline-flex; padding: 2px; border: 1px solid var(--border); border-radius: 8px; background: var(--bg-soft); }
    .lgvd-seg button {
      border: 0; background: transparent; color: var(--muted);
      padding: 4px 11px; border-radius: 6px; font-size: 12px; cursor: pointer;
    }
    .lgvd-seg button.on { background: var(--bg); color: var(--text); font-weight: 600; box-shadow: 0 1px 2px rgba(15, 23, 42, .12); }
    .lgvd-check { display: inline-flex; align-items: center; gap: 5px; font-size: 11.5px; color: var(--muted); cursor: pointer; user-select: none; }
    .lgvd-check input { width: 13px; height: 13px; margin: 0; accent-color: var(--accent); }
    .lgvd-spacer { flex: 1; }
    .lgvd-btn {
      display: inline-flex; align-items: center; gap: 5px;
      padding: 5px 10px;
      border: 1px solid var(--border);
      border-radius: 7px;
      background: var(--bg);
      color: var(--text);
      font-size: 11.5px;
      cursor: pointer;
      white-space: nowrap;
    }
    .lgvd-btn:hover:not(:disabled) { background: var(--hover); }
    .lgvd-btn:disabled { opacity: .42; cursor: not-allowed; }
    .lgvd-btn.ghost { border-color: transparent; background: transparent; color: var(--muted); }
    .lgvd-btn.ghost:hover:not(:disabled) { color: var(--text); background: var(--hover); }
    .lgvd-btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
    .lgvd-btn.primary:hover:not(:disabled) { filter: brightness(1.06); }
    .lgvd-btn .lgvd-ico { width: 13px; height: 13px; }

    .lgvd-cmp { flex: none; padding: 9px 16px; border-bottom: 1px solid var(--border); background: var(--bg-soft); font-size: 12px; color: var(--text); }
    .lgvd-cmp:empty { display: none; }
    .lgvd-cmpbar { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
    .lgvd-sidecard { display: inline-flex; align-items: center; gap: 6px; min-width: 0; }
    .lgvd-sidecard .tag {
      width: 18px; height: 18px; border-radius: 50%;
      display: grid; place-items: center;
      color: #fff; font-size: 10px; font-weight: 800;
    }
    .lgvd-sidecard.a .tag { background: #d97706; }
    .lgvd-sidecard.b .tag { background: #2563eb; }
    .lgvd-sidecard .rid { font-family: var(--mono); font-weight: 650; color: var(--text); text-decoration: none; }
    .lgvd-sidecard .rid:hover { color: var(--accent); text-decoration: underline; }
    .lgvd-sidecard .badge { font-size: 10px; padding: 1px 4px; border-radius: 4px; font-weight: 700; }
    .lgvd-sidecard .badge.grey { background: var(--st-grey-bg); color: var(--st-grey-fg); }
    .lgvd-sidecard .badge.blue { background: var(--st-blue-bg); color: var(--st-blue-fg); }
    .lgvd-sidecard .badge.yellow { background: var(--st-yellow-bg); color: var(--st-yellow-fg); }
    .lgvd-sidecard .badge.red { background: var(--st-red-bg); color: var(--st-red-fg); }
    .lgvd-sidecard .badge.purple { background: var(--st-purple-bg); color: var(--st-purple-fg); }
    .lgvd-sidecard .badge.green { background: var(--st-green-bg); color: var(--st-green-fg); }
    .lgvd-sidecard .badge.lapis { background: var(--st-lapis-bg); color: var(--st-lapis-fg); }
    .lgvd-sidecard .meta { color: var(--muted); font-size: 10.5px; }
    .lgvd-arrow { color: var(--muted); font-family: var(--mono); }
    .lgvd-cmpstat { margin-left: auto; display: flex; align-items: center; gap: 8px; font-family: var(--mono); font-size: 12px; }
    .lgvd-cmpstat .plus { color: var(--ok); }
    .lgvd-cmpstat .minus { color: var(--danger); }
    .lgvd-cmpstat .blocks { font-family: var(--sans); color: var(--muted); font-size: 11px; }
    .lgvd-lang-note { margin-top: 6px; font-size: 11px; color: var(--muted); }
    .lgvd-lang-note b { color: #b45309; font-weight: 600; }

    .lgvd-diff { flex: 1; min-height: 0; overflow: auto; background: var(--bg-code); position: relative; overscroll-behavior: contain; }
    .lgvd-diff::-webkit-scrollbar { width: 11px; height: 11px; }
    .lgvd-diff::-webkit-scrollbar-thumb { background: var(--border-strong); border-radius: 8px; border: 2px solid var(--bg-code); }
    .lgvd-rows {
      width: 100%;
      min-width: 100%;
      padding: 6px 0 24px;
      font-family: var(--mono);
      font-size: 12.5px;
      line-height: 22px;
      font-variant-ligatures: none;
      tab-size: 4;
    }
    .lgvd-rows.split { display: grid; grid-template-columns: 46px minmax(max-content, 1fr) 46px minmax(max-content, 1fr); }
    .lgvd-rows.unified { display: grid; grid-template-columns: 46px 46px 16px minmax(max-content, 1fr); }
    .lgvd-srow, .lgvd-urow { display: contents; }
    .lgvd-ln {
      padding: 0 8px 0 4px;
      text-align: right;
      color: var(--muted);
      font-size: 11px;
      background: var(--bg-soft);
      border-right: 1px solid var(--border);
      user-select: none;
      white-space: nowrap;
    }
    .lgvd-ln.right { border-left: 1px solid var(--border); border-right: 0; }
    .lgvd-code { padding: 0 16px 0 10px; white-space: pre; min-width: 0; }
    .lgvd-code.empty { background: var(--empty); }
    .lgvd-ln.del, .lgvd-code.del { background: var(--del-bg); }
    .lgvd-ln.ins, .lgvd-code.ins { background: var(--add-bg); }
    .lgvd-code.del { box-shadow: inset 2px 0 0 var(--del-border); }
    .lgvd-code.ins { box-shadow: inset 2px 0 0 var(--add-border); }
    .lgvd-code mark { background: var(--mark-del); color: inherit; border-radius: 2px; padding: 0; }
    .lgvd-code.ins mark { background: var(--mark-add); }
    .lgvd-gap {
      grid-column: 1 / -1;
      display: flex; align-items: center; justify-content: center;
      padding: 1px 12px;
      color: var(--muted);
      font-family: var(--sans);
      font-size: 10.5px;
      background: var(--bg-soft);
      border-top: 1px dashed var(--border);
      border-bottom: 1px dashed var(--border);
      user-select: none;
    }
    .lgvd-sign { color: var(--muted); text-align: center; user-select: none; }
    .lgvd-urow.add .lgvd-code, .lgvd-urow.add .lgvd-ln { background: var(--add-bg); }
    .lgvd-urow.del .lgvd-code, .lgvd-urow.del .lgvd-ln { background: var(--del-bg); }
    .lgvd-urow.add .lgvd-sign { color: var(--ok); font-weight: 700; }
    .lgvd-urow.del .lgvd-sign { color: var(--danger); font-weight: 700; }

    .lgvd-state { padding: 54px 30px; text-align: center; color: var(--muted); }
    .lgvd-state .glyph { width: 44px; height: 44px; margin: 0 auto 12px; display: grid; place-items: center; border-radius: 12px; background: var(--bg-soft); border: 1px solid var(--border); }
    .lgvd-state .glyph .lgvd-ico { width: 21px; height: 21px; }
    .lgvd-state h3 { margin: 0 0 6px; font-size: 14px; font-weight: 600; color: var(--text); }
    .lgvd-state p { margin: 0 auto 14px; max-width: 420px; font-size: 12px; line-height: 1.7; }
    .lgvd-state .actions { display: flex; justify-content: center; gap: 8px; }
    .lgvd-state a.lgvd-btn { text-decoration: none; }
    .lgvd-spinner {
      width: 26px; height: 26px; margin: 0 auto 12px;
      border: 2.5px solid var(--border);
      border-top-color: var(--accent);
      border-radius: 50%;
      animation: lgvd-spin .8s linear infinite;
    }
    .lgvd-note {
      display: flex; align-items: center; gap: 8px;
      margin: 14px 16px; padding: 9px 12px;
      border-radius: 9px;
      font-size: 12px;
      background: var(--bg-soft);
      border: 1px solid var(--border);
      color: var(--muted);
    }
    .lgvd-note.ok { color: var(--ok); border-color: var(--add-border); background: var(--add-bg); }
    .lgvd-note .lgvd-ico { width: 15px; height: 15px; flex: none; }

    .lgvd-toast {
      position: absolute; left: 50%; bottom: 22px;
      transform: translate(-50%, 8px);
      max-width: 70%;
      padding: 8px 14px;
      border-radius: 9px;
      background: #111827;
      color: #fff;
      font-size: 12px;
      box-shadow: 0 8px 24px rgba(0, 0, 0, .28);
      opacity: 0;
      pointer-events: none;
      transition: opacity .18s ease, transform .18s ease;
      z-index: 3;
    }
    .lgvd-toast.show { opacity: 1; transform: translate(-50%, 0); }
    .lgvd-root.dark .lgvd-toast { background: #30363d; border: 1px solid var(--border-strong); }

    .lgvd-root.dark .lgvd-code mark { color: var(--text); }

    @keyframes lgvd-fade { from { opacity: 0; } to { opacity: 1; } }
    @keyframes lgvd-pop { from { opacity: 0; transform: translate(-50%, -50%) scale(.985); } to { opacity: 1; transform: translate(-50%, -50%) scale(1); } }
    @keyframes lgvd-spin { to { transform: rotate(360deg); } }
    @keyframes lgvd-shimmer { from { background-position: 180% 0; } to { background-position: -20% 0; } }

    @media (max-width: 920px) {
      .lgvd-panel { width: 100vw; height: 100vh; border-radius: 0; border: 0; }
      .lgvd-body { flex-direction: column; }
      .lgvd-side { width: auto; height: 42%; min-width: 0; max-width: none; border-right: 0; border-bottom: 1px solid var(--border); }
      .lgvd-resizer { display: none; }
      .lgvd-side-head { padding: 8px 12px; }
      .lgvd-quick { padding: 6px 10px 4px; }
      .lgvd-selbar { min-height: 32px; padding: 3px 12px 6px; }
      .lgvd-brand-text h2 { font-size: 15px; }
      .lgvd-sub { max-width: 60vw; }
      .lgvd-launch { right: 14px; bottom: 80px; padding: 9px 13px; }
    }
    @media (prefers-reduced-motion: reduce) {
      .lgvd-root *, .lgvd-root *::before, .lgvd-root *::after {
        animation-duration: .01ms !important;
        animation-iteration-count: 1 !important;
        transition-duration: .01ms !important;
      }
    }
  `;

  /* ------------------------------------------------------------------ *
   *  界面
   * ------------------------------------------------------------------ */

  let host = null;
  let shadow = null;
  let wrap = null;
  let launcherEl = null;
  let modalEl = null;
  let toastTimer = null;
  let prevOverflow = null;
  let themeObserver = null;
  let themeDark = null;
  let lastHref = '';
  let routeTimer = null;

  const state = {
    open: false,
    route: null,
    pid: null,
    title: '',
    rid: null,
    currentRecord: null,
    user: null,
    records: [],
    total: 0,
    pages: 0,
    perPage: 20,
    hasMore: false,
    loadingList: false,
    listError: null,
    onlyAC: false,
    sel: [],
    view: storage.get('view', 'split'),
    ignoreWs: storage.get('ignore-ws', true),
    fold: storage.get('fold', true),
    cmp: null,
    cmpToken: 0,
    requestToken: 0,
    abort: null,
    moreLoading: false,
    sideWidth: storage.get('side-width', 344),
    lastKey: ''
  };

  const SIDE_MIN = 240;
  const SIDE_MAX = 760;

  function applySideWidth(width, persist) {
    const panel = $('.lgvd-panel');
    const panelWidth = panel ? panel.clientWidth : 1440;
    const max = Math.max(SIDE_MIN, Math.min(SIDE_MAX, panelWidth - 360));
    const w = Math.round(clamp(Number(width) || 344, SIDE_MIN, max));
    state.sideWidth = w;
    if (panel) panel.style.setProperty('--side-w', w + 'px');
    const handle = $('[data-resizer]');
    if (handle) {
      handle.setAttribute('aria-valuenow', String(w));
      handle.setAttribute('aria-valuemin', String(SIDE_MIN));
      handle.setAttribute('aria-valuemax', String(Math.round(max)));
    }
    if (persist) storage.set('side-width', w);
    return w;
  }

  let sideDrag = null;

  function onResizePointerDown(e) {
    if (!state.open || e.button !== 0) return;
    const target = e.target;
    if (!(target instanceof Element)) return;
    const handle = target.closest('[data-resizer]');
    if (!handle) return;
    e.preventDefault();
    sideDrag = {
      id: e.pointerId,
      startX: e.clientX,
      startW: state.sideWidth || 344,
      handle: handle
    };
    handle.classList.add('dragging');
    try { handle.setPointerCapture(e.pointerId); } catch { /* ignore */ }
  }

  function onResizePointerMove(e) {
    if (!sideDrag || e.pointerId !== sideDrag.id) return;
    if (e.buttons === 0) {
      onResizePointerUp(e);
      return;
    }
    e.preventDefault();
    applySideWidth(sideDrag.startW + (e.clientX - sideDrag.startX), false);
  }

  function onResizePointerUp(e) {
    if (!sideDrag || e.pointerId !== sideDrag.id) return;
    const handle = sideDrag.handle;
    handle.classList.remove('dragging');
    try { handle.releasePointerCapture(e.pointerId); } catch { /* ignore */ }
    sideDrag = null;
    applySideWidth(state.sideWidth, true);
  }

  function isAbortError(error) {
    return error instanceof LgError && error.kind === 'abort';
  }

  function mount() {
    if (host) return;
    host = document.createElement('div');
    host.id = 'lgvd-host';
    host.style.cssText = 'position:fixed;inset:0;z-index:2147483647;pointer-events:none;';
    shadow = host.attachShadow({ mode: 'open' });
    const style = document.createElement('style');
    style.textContent = CSS;
    shadow.appendChild(style);

    wrap = document.createElement('div');
    wrap.className = 'lgvd-root';
    shadow.appendChild(wrap);

    launcherEl = document.createElement('button');
    launcherEl.type = 'button';
    launcherEl.className = 'lgvd-launch';
    launcherEl.setAttribute('data-act', 'launch');
    launcherEl.title = '比较同一道题的不同提交代码(Alt+D)';
    launcherEl.innerHTML = ICON.compare + '<span>版本对比</span>';
    launcherEl.hidden = true;
    wrap.appendChild(launcherEl);

    modalEl = document.createElement('div');
    modalEl.className = 'lgvd-modal';
    modalEl.hidden = true;
    wrap.appendChild(modalEl);

    (document.body || document.documentElement).appendChild(host);

    // 直接监听按钮,避免个别浏览器/页面对 Shadow DOM 事件委托的干扰。
    launcherEl.addEventListener('click', (e) => {
      e.preventDefault();
      e.stopPropagation();
      openPanel();
    });

    shadow.addEventListener('click', onClick);
    shadow.addEventListener('change', onChange);
    shadow.addEventListener('keydown', onPanelKeyDown);
    shadow.addEventListener('pointerdown', onResizePointerDown);
    shadow.addEventListener('pointermove', onResizePointerMove);
    shadow.addEventListener('pointerup', onResizePointerUp);
    shadow.addEventListener('pointercancel', onResizePointerUp);
    document.addEventListener('keydown', onKeyDown, true);
  }

  function detectTheme(opts) {
    let dark = false;
    const parseRgb = (value) => {
      const m = String(value || '').match(/rgba?\(([^)]+)\)/);
      if (!m) return null;
      const p = m[1].split(',').map((x) => parseFloat(x));
      if (p.length > 3 && p[3] === 0) return null;
      if (p.some((x) => !Number.isFinite(x))) return null;
      return p;
    };
    const luminance = (el) => {
      try {
        const p = parseRgb(getComputedStyle(el).backgroundColor);
        if (!p) return null;
        return (0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]) / 255;
      } catch { return null; }
    };

    const candidates = [];
    const app = document.getElementById('app');
    const lfe = document.querySelector('.lfe-body');
    if (app) candidates.push(app);
    if (lfe && lfe !== app) candidates.push(lfe);
    if (document.body) candidates.push(document.body);
    if (document.documentElement) candidates.push(document.documentElement);

    let lum = null;
    for (const el of candidates) {
      lum = luminance(el);
      if (lum != null) break;
    }
    if (lum != null) {
      dark = lum < 0.5;
    } else {
      // 洛谷的 body 背景可能是透明的,此时用正文颜色判断。
      try {
        const fgEl = app || lfe || document.body || document.documentElement;
        const p = parseRgb(getComputedStyle(fgEl).color);
        if (p) dark = (0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]) / 255 > 0.5;
        else dark = matchMedia('(prefers-color-scheme: dark)').matches;
      } catch { dark = false; }
    }

    try {
      const root = document.documentElement;
      const cls = String((root && root.className) || '') + ' ' + String((document.body && document.body.className) || '');
      const theme = String((root && root.getAttribute('data-theme')) || '').toLowerCase();
      if (theme === 'dark' || /(^|\s)(lfe-)?dark(\s|$)/i.test(cls) || /night/i.test(cls)) dark = true;
      else if (theme === 'light') dark = false;
    } catch { /* ignore */ }

    const changed = themeDark !== null && themeDark !== dark;
    themeDark = dark;
    wrap.classList.toggle('dark', dark);

    // 主题 class 必须在面板内容创建前生效;运行中切换时重绘一次,避免继承文字色停留在旧主题。
    if (changed && state.open && !(opts && opts.silent)) {
      renderList();
      renderCmp();
      renderDiff();
    }
  }

  function setLauncherVisible(visible) {
    if (!launcherEl) return;
    launcherEl.hidden = !visible;
  }

  function lockScroll(lock) {
    if (lock) {
      if (prevOverflow !== null) return;
      prevOverflow = document.documentElement.style.overflow;
      document.documentElement.style.overflow = 'hidden';
    } else if (prevOverflow !== null) {
      document.documentElement.style.overflow = prevOverflow;
      prevOverflow = null;
    }
  }

  async function openPanel(route) {
    if (!route) route = parseRoute();
    if (!route) return;
    mount();
    if (state.open) closePanel();

    state.open = true;
    state.route = route;
    state.pid = route.pid || null;
    state.title = pageProblemTitle(route.pid || null);
    if (route.kind === 'problem') {
      const ctx = readLentilleContext();
      const ctxProblem = ctx && ctx.data && ctx.data.problem;
      if (ctxProblem && ctxProblem.pid === route.pid && ctxProblem.name) state.title = ctxProblem.name;
    } else if (route.kind === 'record') {
      const ctx = readLentilleContext();
      const ctxProblem = ctx && ctx.data && ctx.data.record && ctx.data.record.problem;
      if (ctxProblem) {
        state.pid = ctxProblem.pid || state.pid;
        state.title = ctxProblem.title || ctxProblem.name || state.title;
      }
    }
    state.rid = route.kind === 'record' ? route.rid : null;
    state.currentRecord = null;
    state.user = null;
    state.records = [];
    state.total = 0;
    state.pages = 0;
    state.hasMore = false;
    state.loadingList = true;
    state.listError = null;
    state.sel = [];
    state.cmp = null;
    state.cmpToken++;
    state.requestToken++;
    if (state.abort) state.abort.abort();
    state.abort = new AbortController();
    const signal = state.abort.signal;
    state.onlyAC = false;
    state.moreLoading = false;
    state.lastKey = '';

    const token = state.requestToken;

    launcherEl.hidden = true;
    detectTheme({ silent: true });
    modalEl.innerHTML = shellHtml(route);
    modalEl.hidden = false;
    lockScroll(true);
    applySideWidth(state.sideWidth, false);
    requestAnimationFrame(() => {
      const panel = $('.lgvd-panel');
      if (panel) panel.focus({ preventScroll: true });
    });

    try {
      if (themeObserver) themeObserver.disconnect();
      themeObserver = new MutationObserver(() => { if (state.open) detectTheme(); });
      themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] });
      if (document.body) themeObserver.observe(document.body, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] });
    } catch { /* ignore */ }

    renderList();
    renderSelection();
    renderCmp();
    renderDiff();

    try {
      if (route.kind === 'record') {
        const rec = await getRecordDetail(route.rid, signal);
        if (token !== state.requestToken || !state.open) return;
        const problem = rec.problem || {};
        state.pid = problem.pid || state.pid;
        state.title = problem.title || problem.name || pageProblemTitle(problem.pid || state.pid) || state.title;
        state.currentRecord = normalizeRecord(rec);
        if (typeof rec.sourceCode === 'string' && rec.sourceCode.length) {
          codeCache.set(route.rid, rec.sourceCode);
        }
        updateHeader();
      }

      const user = await getCurrentUser(signal);
      if (token !== state.requestToken || !state.open) return;
      if (!user) throw new LgError('login', '请先登录洛谷');
      state.user = user;
      if (state.currentRecord && state.currentRecord.user && state.currentRecord.user.uid != null
        && user.uid != null && Number(state.currentRecord.user.uid) !== Number(user.uid)) {
        // 从别人的记录页进入时,只比较自己的提交。
        state.currentRecord = null;
        state.rid = null;
      }
      updateHeader();
      renderList();

      // 配置只补全状态/语言名称;登录成功且第一次打开面板时才请求,整个页面会话只请求一次。
      loadConfig().then(() => {
        if (state.open) { renderList(); renderCmp(); }
      });

      const res = await loadRecords(state.pid, state.user, {
        limit: INITIAL_LIMIT,
        signal: signal,
        onProgress: () => {
          if (token === state.requestToken) renderList();
        }
      });
      if (token !== state.requestToken || !state.open) return;

      state.records = res.items;
      state.total = res.total;
      state.pages = res.pages;
      state.perPage = res.perPage;
      state.hasMore = res.hasMore;
      if (state.rid && state.currentRecord && !state.records.some((r) => r.id === state.rid)) {
        state.records.unshift(state.currentRecord);
        state.total = Math.max(state.total, state.records.length);
      }
      state.loadingList = false;
      renderList();
      renderFooter();
      preselect();
    } catch (e) {
      if (token !== state.requestToken || !state.open || isAbortError(e)) return;
      state.loadingList = false;
      state.listError = e;
      updateHeader();
      renderList();
      renderDiff();
    }
  }

  function closePanel() {
    if (!state.open) return;
    state.open = false;
    state.cmpToken++;
    state.requestToken++;
    if (state.abort) { state.abort.abort(); state.abort = null; }
    detailTasks.clear();
    modalEl.hidden = true;
    modalEl.innerHTML = '';
    lockScroll(false);
    launcherEl.hidden = !parseRoute();
    if (themeObserver) { themeObserver.disconnect(); themeObserver = null; }
    state.cmp = null;
    state.sel = [];
  }

  function shellHtml(route) {
    const pid = route.pid || state.pid || '';
    return `
      <div class="lgvd-backdrop" data-act="backdrop"></div>
      <section class="lgvd-panel" role="dialog" aria-modal="true" aria-labelledby="lgvd-title" tabindex="-1">
        <header class="lgvd-head">
          <div class="lgvd-brand">
            <span class="lgvd-mark">${ICON.compare}</span>
            <div class="lgvd-brand-text">
              <h2 id="lgvd-title">提交版本对比</h2>
              <div class="lgvd-sub" data-role="sub">
                ${pid ? `<a class="lgvd-pid" href="/problem/${esc(pid)}" target="_blank" rel="noopener">${esc(pid)}</a><span class="lgvd-sep">·</span>` : ''}
                <span data-role="pname">${esc(state.title || '正在读取题目…')}</span>
              </div>
            </div>
          </div>
          <div class="lgvd-head-actions">
            <span class="lgvd-ver">v${VERSION}</span>
            <button type="button" class="lgvd-icon" data-act="refresh" title="刷新提交列表" aria-label="刷新提交列表">${ICON.refresh}</button>
            <button type="button" class="lgvd-icon" data-act="close" title="关闭(Esc)" aria-label="关闭">${ICON.close}</button>
          </div>
        </header>
        <div class="lgvd-body">
          <aside class="lgvd-side">
            <div class="lgvd-side-head">
              <div class="lgvd-user"><span class="lgvd-avatar" data-role="avatar">·</span><span class="lgvd-user-name" data-role="username">读取中…</span></div>
              <label class="lgvd-switch"><input type="checkbox" data-role="only-ac"><span>只看 AC</span></label>
            </div>
            <div class="lgvd-quick">
              <button type="button" data-act="recent">最近两次</button>
              <button type="button" data-act="recent-ac">最近两次 AC</button>
              ${route.kind === 'record' ? '<button type="button" data-act="prev-ac">当前 ↔ 上次 AC</button>' : ''}
            </div>
            <div class="lgvd-selbar" data-role="selbar"></div>
            <div class="lgvd-list" data-role="list" role="list"></div>
            <div class="lgvd-side-foot" data-role="foot"></div>
          </aside>
          <div class="lgvd-resizer" data-resizer role="separator" aria-orientation="vertical" aria-label="拖动调整提交列表宽度;也可用左右方向键" tabindex="0"></div>
          <main class="lgvd-main">
            <div class="lgvd-toolbar">
              <div class="lgvd-seg" data-role="seg">
                <button type="button" data-view="split">并排</button>
                <button type="button" data-view="unified">统一</button>
              </div>
              <label class="lgvd-check"><input type="checkbox" data-role="ignore-ws"><span>忽略空白</span></label>
              <label class="lgvd-check"><input type="checkbox" data-role="fold"><span>仅显示差异</span></label>
              <div class="lgvd-spacer"></div>
              <button type="button" class="lgvd-btn ghost" data-act="copy">${ICON.copy}<span>复制 patch</span></button>
              <button type="button" class="lgvd-btn ghost" data-act="download">${ICON.download}<span>下载</span></button>
            </div>
            <div class="lgvd-cmp" data-role="cmp"></div>
            <div class="lgvd-diff" data-role="diff" tabindex="-1"></div>
          </main>
        </div>
        <div class="lgvd-toast" data-role="toast" role="status" aria-live="polite"></div>
      </section>
    `;
  }

  function updateHeader() {
    const pname = $('[data-role=pname]');
    if (pname) pname.textContent = state.title || (state.pid || '');
    const sub = $('[data-role=sub]');
    if (sub && state.pid && !sub.querySelector('.lgvd-pid')) {
      sub.insertAdjacentHTML('afterbegin', `<a class="lgvd-pid" href="/problem/${esc(state.pid)}" target="_blank" rel="noopener">${esc(state.pid)}</a><span class="lgvd-sep">·</span>`);
    }
    const uname = $('[data-role=username]');
    const avatar = $('[data-role=avatar]');
    const user = state.user;
    if (uname) uname.textContent = user ? '我的提交 · ' + user.name : '未登录';
    if (avatar) avatar.textContent = user && user.name ? user.name.slice(0, 1).toUpperCase() : '?';
    const onlyAc = $('[data-role=only-ac]');
    if (onlyAc) onlyAc.checked = state.onlyAC;
    const ignoreWs = $('[data-role=ignore-ws]');
    if (ignoreWs) ignoreWs.checked = state.ignoreWs;
    const fold = $('[data-role=fold]');
    if (fold) fold.checked = state.fold;

    const seg = $('[data-role=seg]');
    if (seg) {
      for (const btn of $$('button', seg)) btn.classList.toggle('on', btn.dataset.view === state.view);
    }
  }

  function renderList() {
    const list = $('[data-role=list]');
    if (!list) return;
    const scrollTop = list.scrollTop;

    if (state.listError) {
      list.innerHTML = errorBlock(state.listError, 'list');
      list.scrollTop = 0;
      return;
    }
    if (state.loadingList && !state.records.length) {
      list.innerHTML = '<div class="lgvd-skel"></div>'.repeat(6);
      return;
    }

    const selected = new Map();
    state.sel.forEach((r, i) => selected.set(r.id, i === 0 ? 'A' : 'B'));

    const records = state.onlyAC ? state.records.filter((r) => r.status === 12) : state.records;
    if (!records.length) {
      list.innerHTML = `<div class="lgvd-state"><p>${state.onlyAC ? '没有找到 AC 记录' : '这道题还没有你的提交记录'}</p></div>`;
      list.scrollTop = 0;
      return;
    }

    const html = records.map((r) => {
      const st = statusInfo(r.status);
      const slot = selected.get(r.id) || '';
      const cls = slot === 'A' ? 'a' : slot === 'B' ? 'b' : '';
      return `<div class="lgvd-rec${slot ? ' on ' + cls : ''}" data-rid="${r.id}" role="button" tabindex="0" aria-pressed="${slot ? 'true' : 'false'}" title="${esc('#' + r.id + ' · ' + st.name + ' · ' + fmtFullTime(r.submitTime))}">
        <span class="lgvd-badge ${st.cls}">${esc(st.short)}</span>
        <span class="lgvd-rec-body">
          <span class="lgvd-rec-line1"><a class="lgvd-rid" href="/record/${r.id}" target="_blank" rel="noopener" data-record-link title="打开 #${r.id}">#${r.id}</a><span class="lgvd-lang">${esc(languageName(r.language))}</span>${r.o2 ? '<span class="lgvd-o2">O2</span>' : ''}</span>
          <span class="lgvd-rec-line2">${fmtRunTime(r.time)} · ${fmtMemory(r.memory)} · ${fmtDateTime(r.submitTime)}</span>
        </span>
        <span class="lgvd-slot">${slot}</span>
      </div>`;
    }).join('');

    list.innerHTML = html;
    list.scrollTop = scrollTop;
    renderFooter();
  }

  function renderFooter() {
    const foot = $('[data-role=foot]');
    if (!foot) return;
    if (state.listError || state.loadingList) { foot.innerHTML = ''; return; }
    const shown = state.records.length;
    const total = state.total || shown;
    const more = state.hasMore
      ? `<button type="button" class="lgvd-more" data-act="more"${state.moreLoading ? ' disabled' : ''}>${state.moreLoading ? '加载中…' : '加载更多'}</button>`
      : '';
    const link = state.pid && state.user
      ? `<a href="/record/list?pid=${encodeURIComponent(state.pid)}&user=${encodeURIComponent(state.user.param || state.user.uid || state.user.name)}" target="_blank" rel="noopener">查看全部</a>`
      : '';
    foot.innerHTML = `<span>共 ${total} 条 · 已载入 ${shown}</span><span style="display:flex;align-items:center;gap:8px">${more}${link}</span>`;
  }

  function renderSelection() {
    const bar = $('[data-role=selbar]');
    if (!bar) return;
    if (!state.sel.length) {
      bar.innerHTML = '<span class="hint">选择两条提交记录,或点上方快捷按钮</span>';
      return;
    }
    const chips = state.sel.map((r, i) => {
      const st = statusInfo(r.status);
      return `<span class="lgvd-chip ${i === 0 ? 'a' : 'b'}"><span class="tag">${i === 0 ? 'A' : 'B'}</span><a class="lgvd-chip-rid" href="/record/${r.id}" target="_blank" rel="noopener" title="打开 #${r.id}">#${r.id}</a><em class="${st.cls}">${esc(st.short)}</em></span>`;
    }).join('<span class="lgvd-chip-arrow">→</span>');
    const swap = state.sel.length === 2
      ? `<button type="button" class="lgvd-mini" data-act="swap" title="交换 A / B" aria-label="交换 A / B">${ICON.swap}</button>`
      : '';
    const hint = state.sel.length < 2 ? '<span class="hint">再选一条</span>' : '';
    bar.innerHTML = chips + swap + hint;
  }

  function renderCmp() {
    const cmp = $('[data-role=cmp]');
    if (!cmp) return;
    const c = state.cmp;
    if (!c || !c.a || !c.b) { cmp.innerHTML = ''; updateButtons(); return; }

    const a = c.a;
    const b = c.b;
    const sa = statusInfo(a.status);
    const sb = statusInfo(b.status);
    const parts = [];
    parts.push('<div class="lgvd-cmpbar">');
    parts.push(sideCard('a', 'A', a, sa));
    parts.push('<span class="lgvd-arrow">→</span>');
    parts.push(sideCard('b', 'B', b, sb));

    if (c.loading) {
      parts.push('<span class="lgvd-cmpstat"><span class="blocks">正在读取代码…</span></span>');
    } else if (c.error) {
      parts.push('<span class="lgvd-cmpstat"><span class="blocks">读取失败</span></span>');
    } else {
      parts.push(`<span class="lgvd-cmpstat"><span class="plus">+${c.stats.add}</span><span class="minus">−${c.stats.del}</span><span class="blocks">${c.hunks.length} 处修改</span></span>`);
    }
    parts.push('</div>');

    if (!c.loading && !c.error && a.language !== b.language) {
      parts.push(`<div class="lgvd-lang-note"><b>提示</b>:两次提交使用了不同语言(${esc(languageName(a.language))} / ${esc(languageName(b.language))}),diff 仅供参考。</div>`);
    }
    cmp.innerHTML = parts.join('');
    updateButtons();
  }

  function sideCard(cls, tag, rec, st) {
    return `<span class="lgvd-sidecard ${cls}"><span class="tag">${tag}</span><a class="rid" href="/record/${rec.id}" target="_blank" rel="noopener" title="打开 #${rec.id}">#${rec.id}</a><span class="badge ${st.cls}">${esc(st.short)}</span><span class="meta">${esc(languageName(rec.language))} · ${fmtDateTime(rec.submitTime)}</span></span>`;
  }

  function updateButtons() {
    const copy = $('[data-act=copy]');
    const dl = $('[data-act=download]');
    const ready = !!(state.cmp && !state.cmp.loading && !state.cmp.error && state.cmp.stats && (state.cmp.stats.add || state.cmp.stats.del));
    if (copy) copy.disabled = !ready;
    if (dl) dl.disabled = !ready;
  }

  function renderDiff() {
    const box = $('[data-role=diff]');
    if (!box) return;

    const c = state.cmp;
    if (!state.sel.length) {
      if (state.listError) {
        box.innerHTML = errorBlock(state.listError, 'open');
        updateButtons();
        return;
      }
      box.innerHTML = blankState('选择两条提交记录', '左侧列表里点选任意两条记录,就会在这里显示它们的代码差异。');
      box.dataset.key = '';
      updateButtons();
      return;
    }
    if (!c) {
      if (state.listError) {
        box.innerHTML = errorBlock(state.listError, 'open');
        updateButtons();
        return;
      }
      box.innerHTML = blankState('准备比较', '正在加载提交信息…');
      updateButtons();
      return;
    }
    if (c.loading) {
      box.innerHTML = `<div class="lgvd-state"><div class="lgvd-spinner"></div><h3>正在获取两份代码</h3><p>#${c.a.id} 与 #${c.b.id}</p></div>`;
      updateButtons();
      return;
    }
    if (c.error) {
      box.innerHTML = errorBlock(c.error, 'cmp');
      updateButtons();
      return;
    }

    const key = c.a.id + '-' + c.b.id + '-' + (state.ignoreWs ? 'w' : 'x');
    const changed = key !== state.lastKey;
    const prevTop = box.scrollTop;
    const prevLeft = box.scrollLeft;

    if (!c.stats.add && !c.stats.del) {
      box.innerHTML = `<div class="lgvd-note ok">${ICON.check}<span>两次提交的代码完全相同。</span></div>`;
      state.lastKey = key;
      updateButtons();
      return;
    }

    const built = buildRows(c.runs, c.aLines, c.bLines, state.fold, CONTEXT);
    let html = '';
    if (state.view === 'unified') {
      html = renderUnified(built.rows);
    } else {
      html = renderSplit(buildSplitRows(built.rows));
    }

    box.innerHTML = html;
    box.dataset.key = key;
    state.lastKey = key;
    updateButtons();

    if (changed) {
      box.scrollTop = 0;
      box.scrollLeft = 0;
      requestAnimationFrame(() => {
        const first = box.querySelector('.lgvd-code.del, .lgvd-code.ins');
        if (first) {
          const top = first.getBoundingClientRect().top - box.getBoundingClientRect().top;
          box.scrollTop += top - 60;
        }
      });
    } else {
      box.scrollTop = prevTop;
      box.scrollLeft = prevLeft;
    }
  }

  function blankState(title, text) {
    return `<div class="lgvd-state">
      <div class="glyph">${ICON.compare}</div>
      <h3>${esc(title)}</h3>
      <p>${esc(text)}</p>
    </div>`;
  }

  function errorBlock(err, where) {
    const kind = err && err.kind;
    const msg = err && err.message ? err.message : '未知错误';
    let actions = '';
    if (kind === 'login') {
      actions = `<a class="lgvd-btn primary" href="/auth/login" target="_blank" rel="noopener">去登录</a>`;
    } else if (kind === 'code' || kind === 'forbidden') {
      const rid = state.cmp && state.cmp.a ? state.cmp.a.id : state.rid;
      actions = `<button type="button" class="lgvd-btn" data-act="retry-compare">重试</button>${rid ? `<a class="lgvd-btn" href="/record/${rid}" target="_blank" rel="noopener">查看记录</a>` : ''}`;
    } else {
      actions = `<button type="button" class="lgvd-btn primary" data-act="retry-${where === 'cmp' ? 'compare' : 'open'}">重试</button>`;
    }
    return `<div class="lgvd-state">
      <div class="glyph">${ICON.compare}</div>
      <h3>${kind === 'login' ? '需要登录' : kind === 'code' ? '代码不可见' : '加载失败'}</h3>
      <p>${esc(msg)}</p>
      <div class="actions">${actions}</div>
    </div>`;
  }

  function escText(line) {
    const s = String(line == null ? '' : line).replace(/\t/g, '    ');
    return s ? esc(s) : '&#8203;';
  }

  function renderSplit(rows) {
    const parts = [];
    for (const row of rows) {
      if (row.type === 'gap') {
        parts.push(`<div class="lgvd-gap">… 折叠 ${row.count} 行相同代码 …</div>`);
        continue;
      }
      if (row.type === 'eq') {
        parts.push(`<div class="lgvd-srow eq">
          <span class="lgvd-ln">${row.l.no}</span><span class="lgvd-code">${escText(row.l.text)}</span>
          <span class="lgvd-ln">${row.r.no}</span><span class="lgvd-code">${escText(row.r.text)}</span>
        </div>`);
        continue;
      }

      const l = row.l;
      const r = row.r;
      let lh = l ? escText(l.text) : '';
      let rh = r ? escText(r.text) : '';
      if (row.type === 'chg' && l && r) {
        const pair = inlinePair(l.text, r.text);
        if (pair) { lh = pair.a; rh = pair.b; }
      }
      const leftCls = l ? (row.type === 'ins' ? 'empty' : 'del') : 'empty';
      const rightCls = r ? (row.type === 'del' ? 'empty' : 'ins') : 'empty';

      parts.push(`<div class="lgvd-srow ${row.type}">
        <span class="lgvd-ln ${leftCls}">${l ? l.no : ''}</span><span class="lgvd-code ${leftCls}">${lh || '&#8203;'}</span>
        <span class="lgvd-ln right ${rightCls}">${r ? r.no : ''}</span><span class="lgvd-code ${rightCls}">${rh || '&#8203;'}</span>
      </div>`);
    }
    return `<div class="lgvd-rows split">${parts.join('')}</div>`;
  }

  function renderUnified(rows) {
    const parts = [];
    for (const row of rows) {
      if (row.type === 'gap') {
        parts.push(`<div class="lgvd-gap">… 折叠 ${row.count} 行相同代码 …</div>`);
        continue;
      }
      const cls = row.type === '+' ? 'add' : row.type === '-' ? 'del' : 'eq';
      const sign = row.type === '+' ? '+' : row.type === '-' ? '−' : ' ';
      const text = escText(row.text);
      parts.push(`<div class="lgvd-urow ${cls}">
        <span class="lgvd-ln ${row.type === '-' ? 'del' : ''}">${row.aNo || ''}</span>
        <span class="lgvd-ln ${row.type === '+' ? 'ins' : ''}">${row.bNo || ''}</span>
        <span class="lgvd-sign">${sign}</span>
        <span class="lgvd-code ${row.type === '+' ? 'ins' : row.type === '-' ? 'del' : ''}">${text}</span>
      </div>`);
    }
    return `<div class="lgvd-rows unified">${parts.join('')}</div>`;
  }

  function preselect() {
    if (!state.records.length) return;

    if (state.rid) {
      const idx = state.records.findIndex((r) => r.id === state.rid);
      if (idx >= 0) {
        const cur = state.records[idx];
        const prev = state.records[idx + 1];
        state.sel = prev ? [prev, cur] : [cur];
        startCompareIfReady();
        return;
      }
    }

    if (state.records.length >= 2) {
      state.sel = [state.records[1], state.records[0]];
      startCompareIfReady();
    } else {
      state.sel = [state.records[0]];
      renderList();
      renderSelection();
    }
  }

  function startCompareIfReady() {
    renderList();
    renderSelection();
    if (state.sel.length === 2) compareSelected();
    else { state.cmp = null; renderCmp(); renderDiff(); }
  }

  async function compareSelected() {
    if (state.sel.length !== 2) return;
    const a = state.sel[0];
    const b = state.sel[1];
    if (state.cmp && state.cmp.loading && state.cmp.a && state.cmp.b
      && state.cmp.a.id === a.id && state.cmp.b.id === b.id) {
      return;
    }
    const token = ++state.cmpToken;
    state.cmp = { loading: true, a: a, b: b };
    renderCmp();
    renderDiff();

    try {
      const signal = state.abort ? state.abort.signal : undefined;
      const [codeA, codeB] = await Promise.all([getCode(a.id, signal), getCode(b.id, signal)]);
      if (token !== state.cmpToken || !state.open) return;
      if (codeA.length + codeB.length > MAX_CODE_CHARS * 2) {
        throw new LgError('huge', '代码过长,无法在浏览器中比较');
      }
      const diff = computeDiff(codeA, codeB, state.ignoreWs);
      const stats = runStats(diff.runs);
      const hunks = buildHunks(diff.runs, CONTEXT, diff.aLines.length, diff.bLines.length);
      state.cmp = {
        loading: false,
        a: a,
        b: b,
        aLines: diff.aLines,
        bLines: diff.bLines,
        ops: diff.ops,
        runs: diff.runs,
        stats: stats,
        hunks: hunks
      };
      renderCmp();
      renderDiff();
    } catch (e) {
      if (token !== state.cmpToken || !state.open || isAbortError(e)) return;
      state.cmp = { loading: false, a: a, b: b, error: e };
      renderCmp();
      renderDiff();
    }
  }

  function recomputeWithOptions() {
    const c = state.cmp;
    if (!c || c.loading || c.error || !c.aLines) return;
    const diff = computeDiff(c.aLines.join('\n'), c.bLines.join('\n'), state.ignoreWs);
    const stats = runStats(diff.runs);
    const hunks = buildHunks(diff.runs, CONTEXT, diff.aLines.length, diff.bLines.length);
    state.cmp = {
      loading: false,
      a: c.a,
      b: c.b,
      aLines: diff.aLines,
      bLines: diff.bLines,
      ops: diff.ops,
      runs: diff.runs,
      stats: stats,
      hunks: hunks
    };
    renderCmp();
    renderDiff();
  }

  function selectRecord(id) {
    const idx = state.sel.findIndex((r) => r.id === id);
    if (idx >= 0) {
      state.sel.splice(idx, 1);
    } else {
      const rec = state.records.find((r) => r.id === id);
      if (!rec) return;
      if (state.sel.length >= 2) state.sel.shift();
      state.sel.push(rec);
    }
    renderList();
    renderSelection();
    if (state.sel.length === 2) compareSelected();
    else {
      state.cmp = null;
      renderCmp();
      renderDiff();
    }
  }

  function pickPair(a, b) {
    if (!a || !b) return;
    state.sel = [a, b];
    renderList();
    renderSelection();
    compareSelected();
  }

  function quickRecent() {
    if (state.records.length < 2) { toast('提交记录不足两条'); return; }
    pickPair(state.records[1], state.records[0]);
  }

  function quickRecentAC() {
    const acs = state.records.filter((r) => r.status === 12);
    if (acs.length < 2) { toast('AC 记录不足两条'); return; }
    pickPair(acs[1], acs[0]);
  }

  function quickPrevAC() {
    const cur = state.records.find((r) => r.id === state.rid) || state.currentRecord;
    if (!cur) { toast('还没有读取到当前提交'); return; }
    const older = state.records
      .filter((r) => r.status === 12 && r.submitTime < cur.submitTime)
      .sort((x, y) => y.submitTime - x.submitTime)[0];
    if (!older) { toast('没有找到更早的 AC 记录'); return; }
    pickPair(older, cur);
  }

  async function loadMore() {
    if (state.moreLoading || !state.hasMore || !state.user) return;
    if (state.records.length >= MAX_RECORDS) {
      toast('最多载入 ' + MAX_RECORDS + ' 条提交');
      return;
    }
    state.moreLoading = true;
    renderFooter();
    try {
      const room = MAX_RECORDS - state.records.length;
      const signal = state.abort ? state.abort.signal : undefined;
      const res = await loadMoreRecords(state.pid, state.user, state.pages + 1, Math.min(INITIAL_LIMIT, room), signal);
      state.records = dedupeRecords(state.records.concat(res.items));
      state.total = Math.max(state.total, res.total);
      state.pages = res.page;
      state.perPage = res.perPage;
      state.hasMore = state.records.length < state.total;
      saveListCache(state.pid, state.user, {
        items: state.records,
        total: state.total,
        perPage: state.perPage,
        pages: state.pages,
        param: state.user.param
      });
      renderList();
    } catch (e) {
      if (!isAbortError(e)) toast(e.message || '加载失败');
    } finally {
      state.moreLoading = false;
      renderFooter();
    }
  }

  async function refreshList() {
    if (state.loadingList) return;
    const token = ++state.requestToken;
    if (state.abort) state.abort.abort();
    state.abort = new AbortController();
    detailTasks.clear();
    const signal = state.abort.signal;
    state.loadingList = true;
    state.listError = null;
    state.hasMore = false;
    renderList();
    renderFooter();
    try {
      const res = await loadRecords(state.pid, state.user, { limit: INITIAL_LIMIT, force: true, signal: signal });
      if (token !== state.requestToken || !state.open) return;
      const keep = state.sel.map((r) => r.id);
      state.records = res.items;
      state.total = res.total;
      state.pages = res.pages;
      state.perPage = res.perPage;
      state.hasMore = res.hasMore;
      state.loadingList = false;
      state.sel = keep.map((id) => state.records.find((r) => r.id === id)).filter(Boolean);
      renderList();
      renderSelection();
      if (state.sel.length === 2) compareSelected();
      else {
        state.cmp = null;
        renderCmp();
        renderDiff();
      }
    } catch (e) {
      if (token !== state.requestToken || !state.open || isAbortError(e)) return;
      state.loadingList = false;
      state.listError = e;
      renderList();
      renderDiff();
    }
  }

  function toast(msg) {
    const el = $('[data-role=toast]');
    if (!el) return;
    el.textContent = msg;
    el.classList.add('show');
    clearTimeout(toastTimer);
    toastTimer = setTimeout(() => el.classList.remove('show'), 2400);
  }

  function patchText() {
    const c = state.cmp;
    if (!c || !c.runs || !c.aLines) return '';
    const a = c.a;
    const b = c.b;
    const ext = languageExt(a.language);
    return toUnifiedDiff(
      c.runs,
      c.aLines,
      c.bLines,
      `record-${a.id}.${ext}`,
      `record-${b.id}.${ext}`,
      CONTEXT
    );
  }

  async function copyPatch() {
    const text = patchText();
    if (!text) return;
    try {
      await navigator.clipboard.writeText(text);
      toast('patch 已复制到剪贴板');
    } catch {
      const ta = document.createElement('textarea');
      ta.value = text;
      ta.style.position = 'fixed';
      ta.style.opacity = '0';
      wrap.appendChild(ta);
      ta.select();
      try { document.execCommand('copy'); toast('patch 已复制到剪贴板'); }
      catch { toast('复制失败,请手动选择文本'); }
      finally { ta.remove(); }
    }
  }

  function downloadPatch() {
    const text = patchText();
    if (!text) return;
    const a = state.cmp.a;
    const b = state.cmp.b;
    const name = `${state.pid || 'luogu'}_${a.id}_${b.id}.diff`;
    const blob = new Blob([text], { type: 'text/x-diff;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = name;
    wrap.appendChild(link);
    link.click();
    link.remove();
    setTimeout(() => URL.revokeObjectURL(url), 4000);
    toast('已下载 ' + name);
  }

  function languageExt(id) {
    const map = {
      2: 'c', 3: 'cpp', 4: 'cpp', 11: 'cpp', 12: 'cpp', 27: 'cpp', 28: 'cpp', 34: 'cpp',
      7: 'py', 25: 'py', 6: 'py', 24: 'py', 8: 'java', 33: 'java', 9: 'js', 14: 'go',
      15: 'rs', 1: 'pas', 13: 'rb', 16: 'php', 19: 'hs', 31: 'jl', 32: 'lua'
    };
    return map[id] || 'txt';
  }

  function onClick(e) {
    const target = e.target;
    if (!(target instanceof Element)) return;
    // 记录编号是真实链接:交给浏览器打开,不触发行选中。
    if (target.closest('a[href]')) return;
    const actEl = target.closest('[data-act], [data-view]');

    if (!actEl) {
      const rec = target.closest('[data-rid]');
      if (rec && state.open) selectRecord(Number(rec.dataset.rid));
      return;
    }

    if (actEl.dataset.view) {
      state.view = actEl.dataset.view;
      storage.set('view', state.view);
      updateHeader();
      renderDiff();
      return;
    }

    const act = actEl.dataset.act;
    if (act === 'launch') { openPanel(); return; }
    if (act === 'close' || act === 'backdrop') { closePanel(); return; }
    if (act === 'refresh') { refreshList(); return; }
    if (act === 'recent') { quickRecent(); return; }
    if (act === 'recent-ac') { quickRecentAC(); return; }
    if (act === 'prev-ac') { quickPrevAC(); return; }
    if (act === 'swap') {
      if (state.sel.length === 2) {
        state.sel.reverse();
        renderList();
        renderSelection();
        compareSelected();
      }
      return;
    }
    if (act === 'copy') { copyPatch(); return; }
    if (act === 'download') { downloadPatch(); return; }
    if (act === 'more') { loadMore(); return; }
    if (act === 'retry-compare') { compareSelected(); return; }
    if (act === 'retry-open') { openPanel(state.route); return; }
    if (act === 'retry-list') { refreshList(); return; }
  }

  function onChange(e) {
    const t = e.target;
    if (t.dataset.role === 'only-ac') {
      state.onlyAC = !!t.checked;
      renderList();
    } else if (t.dataset.role === 'ignore-ws') {
      state.ignoreWs = !!t.checked;
      storage.set('ignore-ws', state.ignoreWs);
      recomputeWithOptions();
    } else if (t.dataset.role === 'fold') {
      state.fold = !!t.checked;
      storage.set('fold', state.fold);
      renderDiff();
    }
  }

  function onPanelKeyDown(e) {
    const target = e.target;
    if (!(target instanceof Element)) return;
    if (target.closest('[data-resizer]')) {
      if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
        e.preventDefault();
        applySideWidth((state.sideWidth || 344) + (e.key === 'ArrowLeft' ? -16 : 16), true);
      }
      return;
    }
    if (e.key !== 'Enter' && e.key !== ' ') return;
    // 链接自己处理 Enter;不要把它当成行选择。
    if (target.closest('a[href]')) return;
    const rec = target.closest('[data-rid]');
    if (!rec) return;
    e.preventDefault();
    selectRecord(Number(rec.dataset.rid));
  }

  function onKeyDown(e) {
    if (e.altKey && !e.ctrlKey && !e.metaKey && (e.key === 'd' || e.key === 'D')) {
      const tag = (e.target && e.target.tagName) || '';
      if (tag === 'INPUT' || tag === 'TEXTAREA' || (e.target && e.target.isContentEditable)) return;
      e.preventDefault();
      if (state.open) closePanel();
      else openPanel();
      return;
    }
    if (!state.open) return;
    if (e.key === 'Escape') {
      e.preventDefault();
      closePanel();
      return;
    }
    if (e.key === 'Tab') {
      const focusables = $$('button, a[href], input, [tabindex="0"]', modalEl).filter((el) => !el.disabled && el.offsetParent !== null);
      if (!focusables.length) return;
      const first = focusables[0];
      const last = focusables[focusables.length - 1];
      const active = (shadow && shadow.activeElement) || document.activeElement;
      if (e.shiftKey && active === first) {
        e.preventDefault();
        last.focus();
      } else if (!e.shiftKey && active === last) {
        e.preventDefault();
        first.focus();
      }
    }
  }

  function onRouteChange() {
    if (state.open) closePanel();
    const route = parseRoute();
    setLauncherVisible(!!route);
    if (route) {
      // 页面切换后,若用户已经打开过面板,不自动打开,避免打断浏览。
    }
  }

  /* ------------------------------------------------------------------ *
   *  启动
   * ------------------------------------------------------------------ */

  function boot() {
    if (window.__LGVD_BOOTED__) return;
    window.__LGVD_BOOTED__ = true;
    mount();
    setLauncherVisible(!!parseRoute());
    lastHref = location.href;

    routeTimer = setInterval(() => {
      if (location.href === lastHref) return;
      lastHref = location.href;
      onRouteChange();
    }, 600);
    window.addEventListener('popstate', () => setTimeout(onRouteChange, 30));

    window.addEventListener('resize', () => {
      if (!state.open) return;
      detectTheme();
      applySideWidth(state.sideWidth, false);
    });

    // 调试 / 演示钩子
    window.__LGVD__ = {
      version: VERSION,
      open: (r) => openPanel(r || parseRoute()),
      close: () => closePanel(),
      setView: (v) => {
        if (v !== 'split' && v !== 'unified') return;
        state.view = v;
        storage.set('view', v);
        if (state.open) { updateHeader(); renderDiff(); }
      }
    };
  }

  if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
      splitLines,
      canonLine,
      diffLines,
      buildRuns,
      buildHunks,
      buildRows,
      buildSplitRows,
      computeDiff,
      diffStats,
      toUnifiedDiff,
      inlinePair,
      parseRoute,
      normalizeRecord,
      statusInfo,
      languageName,
      fmtRunTime,
      fmtMemory,
      fmtDateTime,
      tokenize,
      retryDelay,
      requestKey
    };
    return;
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', boot, { once: true });
  } else {
    boot();
  }
})();
原文