Greasy Fork is available in English.

Atcoder Better!

Atcoder界面汉化、题目翻译、markdown视图、一键复制题目、跳转到洛谷

נכון ליום 16-03-2024. ראה הגרסה האחרונה.

  1. // ==UserScript==
  2. // @name Atcoder Better!
  3. // @namespace https://greatest.deepsurf.us/users/747162
  4. // @version 1.14.2
  5. // @description Atcoder界面汉化、题目翻译、markdown视图、一键复制题目、跳转到洛谷
  6. // @author 北极小狐
  7. // @match *://atcoder.jp/*
  8. // @run-at document-start
  9. // @connect www2.deepl.com
  10. // @connect api-free.deepl.com
  11. // @connect api.deepl.com
  12. // @connect api.deeplx.org
  13. // @connect www.iflyrec.com
  14. // @connect m.youdao.com
  15. // @connect api.interpreter.caiyunai.com
  16. // @connect translate.google.com
  17. // @connect openai.api2d.net
  18. // @connect api.openai.com
  19. // @connect www.luogu.com.cn
  20. // @connect vjudge.net
  21. // @connect clist.by
  22. // @connect greatest.deepsurf.us
  23. // @connect staticfile.net
  24. // @connect aowuucdn.oss-cn-beijing.aliyuncs.com
  25. // @connect aowuucdn.oss-accelerate.aliyuncs.com
  26. // @connect 127.0.0.1
  27. // @connect *
  28. // @grant GM_xmlhttpRequest
  29. // @grant GM_info
  30. // @grant GM_setValue
  31. // @grant GM_getValue
  32. // @grant GM_listValues
  33. // @grant GM_deleteValue
  34. // @grant GM_addStyle
  35. // @grant GM_setClipboard
  36. // @grant GM_getResourceText
  37. // @icon https://aowuucdn.oss-accelerate.aliyuncs.com/atcoder.png
  38. // @require https://cdn.staticfile.net/turndown/7.1.2/turndown.min.js
  39. // @require https://cdn.staticfile.net/markdown-it/13.0.1/markdown-it.min.js
  40. // @require https://cdn.bootcdn.net/ajax/libs/crypto-js/4.1.1/crypto-js.min.js
  41. // @require https://cdn.staticfile.net/chroma-js/2.4.2/chroma.min.js
  42. // @require https://cdn.staticfile.net/xterm/3.9.2/xterm.min.js
  43. // @require https://cdn.staticfile.net/dexie/3.2.4/dexie.min.js
  44. // @require https://cdn.staticfile.net/i18next/23.5.1/i18next.min.js
  45. // @require https://cdn.staticfile.net/i18next-http-backend/2.2.2/i18nextHttpBackend.min.js
  46. // @require https://cdn.staticfile.net/jquery-i18next/1.2.1/jquery-i18next.min.js
  47. // @require https://cdn.staticfile.net/highlight.js/11.3.1/highlight.min.js
  48. // @require https://update.greatest.deepsurf.us/scripts/484742/1311040/i18nextChainedBackendjs.js
  49. // @require https://update.greatest.deepsurf.us/scripts/484743/1311041/i18next-localstorage-backendjs.js
  50. // @resource acwing_cpp_code_completer https://aowuucdn.oss-accelerate.aliyuncs.com/acwing_cpp_code_completer-0.0.11.json
  51. // @resource wandboxlist https://wandbox.org/api/list.json
  52. // @resource xtermcss https://cdn.staticfile.net/xterm/3.9.2/xterm.min.css
  53. // @license GPL3
  54. // @compatible Chrome
  55. // @compatible Firefox
  56. // @compatible Edge
  57. // @incompatible safari
  58. // @supportURL https://github.com/beijixiaohu/OJBetter/issues
  59. // @name:zh-TW Atcoder Better!
  60. // @name:en Atcoder Better!
  61. // @name:de Atcoder Better!
  62. // @name:fr Atcoder Better!
  63. // @name:ko Atcoder Better!
  64. // @name:pt Atcoder Better!
  65. // @name:ja Atcoder Better!
  66. // @name:es Atcoder Better!
  67. // @name:it Atcoder Better!
  68. // @name:hi Atcoder Better!
  69. // @description 一个适用于 AtCoder 的 Tampermonkey 脚本,增强功能与界面。
  70. // @description:zh-TW 一個適用於 AtCoder 的 Tampermonkey 腳本,增強功能與界面。
  71. // @description:en A Tampermonkey script for AtCoder that enhances functionality and interface.
  72. // @description:de Ein Tampermonkey-Skript für AtCoder, das Funktionalität und Benutzeroberfläche verbessert.
  73. // @description:fr Un script Tampermonkey pour AtCoder qui améliore les fonctionnalités et l'interface.
  74. // @description:ko AtCoder를 위한 Tampermonkey 스크립트로 기능과 인터페이스를 개선합니다.
  75. // @description:pt Um script Tampermonkey para AtCoder que aprimora a funcionalidade e a interface.
  76. // @description:ja AtCoder用のTampermonkeyスクリプトで機能とインターフェースを強化します。
  77. // @description:es Un script Tampermonkey para AtCoder que mejora la funcionalidad y la interfaz.
  78. // @description:it Uno script Tampermonkey per AtCoder che migliora la funzionalità e l'interfaccia.
  79. // @description:hi AtCoder के लिए एक Tampermonkey स्क्रिप्ट जो कार्यक्षमता और इंटरफ़ेस को बेहतर बनाता है।
  80. // ==/UserScript==
  81.  
  82. /**
  83. * @namespace OJBetter
  84. * @desc 主命名空间
  85. */
  86. const OJBetter = {};
  87.  
  88. /**
  89. * @namespace state
  90. * @desc 描述脚本的当前状态。
  91. * @memberof OJBetter
  92. */
  93. OJBetter.state = {
  94. /** @type {string} 脚本名*/
  95. name: GM_info.script.name,
  96. /** @type {string} 格式化后的脚本名*/
  97. formatName: undefined,
  98. /** @type {string} 版本号*/
  99. version: GM_info.script.version,
  100. /** @type {boolean?} 是否跳过页面加载等待 */
  101. notWaiteLoaded: undefined,
  102. /** @type {string} 最后公告版本,用于标识版本更新完成提示 */
  103. lastAnnounceVer: undefined,
  104. /** @type {string} 最后读取的有效公告版本 */
  105. lastReadAnnounceVer: undefined,
  106. /** @type {number} 当前已打开的模态对话框数量*/
  107. openDialogCount: 0
  108. };
  109.  
  110. /**
  111. * @namespace common
  112. * @desc 通用设置和属性。
  113. * @memberof OJBetter
  114. */
  115. OJBetter.common = {
  116. /** @type {string} 网站的主机地址 */
  117. hostAddress: location.origin,
  118. /** @type {string?} Atcoder的CSRF令牌 */
  119. at_csrf_token: undefined,
  120. /** @type {Array?} 任务队列 */
  121. taskQueue: undefined,
  122. /** @type {object} OJBetter数据库连接实例*/
  123. database: undefined
  124. };
  125.  
  126. /**
  127. * @namespace basic
  128. * @desc 基本的用户界面设置。
  129. * @memberof OJBetter
  130. */
  131. OJBetter.basic = {
  132. /** @type {string} 黑暗模式设置 */
  133. darkMode: undefined,
  134. /** @type {boolean?} 是否展开折叠块 */
  135. expandFoldingblocks: undefined,
  136. /** @type {boolean?} 是否开启折叠块渲染性能优化 */
  137. renderPerfOpt: undefined,
  138. /** @type {boolean?} 评论区分页 */
  139. commentPaging: undefined,
  140. /** @type {boolean?} 显示跳转到Luogu按钮 */
  141. showJumpToLuogu: undefined,
  142. /** @type {boolean?} 显示跳转到Virtual Judge按钮 */
  143. showCF2vjudge: undefined,
  144. /** @type {boolean?} 比赛排行榜重新着色 */
  145. standingsRecolor: undefined
  146. };
  147.  
  148. /**
  149. * @namespace typeOfPage
  150. * @desc 页面类型判断。
  151. * @memberof OJBetter
  152. */
  153. OJBetter.typeOfPage = {
  154. /** @type {boolean?} 是否是轻量站 */
  155. is_mSite: false,
  156. /** @type {boolean?} 是否是acmsguru页面 */
  157. is_acmsguru: false,
  158. /** @type {boolean?} 是否是旧版LaTeX页面 */
  159. is_oldLatex: false,
  160. /** @type {boolean?} 是否是题目集页面 */
  161. is_contest: undefined,
  162. /** @type {boolean?} 是否是题目页面 */
  163. is_problem: undefined,
  164. /** @type {boolean?} 是否是完整的问题集页面 */
  165. is_completeProblemset: false,
  166. /** @type {boolean?} 是否是问题集中的问题页面 */
  167. is_problemset_problem: false,
  168. /** @type {boolean?} 是否是问题集页面 */
  169. is_problemset: false,
  170. /** @type {boolean?} 是否是Codeforces排名页面 */
  171. is_cfStandings: false,
  172. /** @type {boolean?} 是否是提交页面 */
  173. is_submitPage: false,
  174. /** @type {boolean?} 是否是主页 */
  175. is_homepage: undefined,
  176. /** @type {boolean?} 是否选择的是英语页面 */
  177. isEnglishLanguage: undefined,
  178. };
  179.  
  180. /**
  181. * @namespace localization
  182. * @desc 本地化设置。
  183. * @memberof OJBetter
  184. */
  185. OJBetter.localization = {
  186. /** @type {string?} 网站语言 */
  187. websiteLang: undefined,
  188. /** @type {string?} 脚本语言 */
  189. scriptLang: undefined
  190. };
  191.  
  192. /**
  193. * @namespace translation
  194. * @desc 翻译设置。
  195. * @memberof OJBetter
  196. */
  197. OJBetter.translation = {
  198. /** @type {string?} 翻译服务选择 */
  199. choice: undefined,
  200. /** @type {string?} 目标语言 */
  201. targetLang: undefined,
  202. comment: {
  203. /** @type {string?} 评论翻译服务选择 */
  204. choice: undefined,
  205. /** @type {string?} 评论翻译模式 */
  206. transMode: undefined
  207. },
  208. auto: {
  209. /** @type {boolean?} 自动翻译开关 */
  210. enabled: undefined,
  211. /** @type {number?} 短文本长度限制 */
  212. shortTextLength: undefined,
  213. mixTrans: {
  214. /** @type {boolean?} 混合翻译开关 */
  215. enabled: undefined,
  216. /** @type {Array?} 混合翻译服务列表 */
  217. servers: undefined
  218. }
  219. },
  220. memory: {
  221. /** @type {boolean?} 翻译记忆开关 */
  222. enabled: undefined,
  223. /** @type {Object?} 翻译记忆树 */
  224. ttTree: undefined
  225. },
  226. /** @type {string?} 重翻译时的行为 */
  227. retransAction: undefined,
  228. /** @type {number?} 等待时间 */
  229. waitTime: undefined,
  230. /** @type {boolean?} 替换符 */
  231. replaceSymbol: undefined,
  232. /** @type {boolean?} 过滤文本中的*号 */
  233. filterTextWithoutEmphasis: undefined
  234. };
  235.  
  236. /**
  237. * @namespace clist
  238. * @desc Clist相关设置。
  239. * @memberof OJBetter
  240. */
  241. OJBetter.clist = {
  242. enabled: {
  243. /** @type {boolean?} 比赛页面开关 */
  244. contest: undefined,
  245. /** @type {boolean?} 问题页面开关 */
  246. problem: undefined,
  247. /** @type {boolean?} 问题集页面开关 */
  248. problemset: undefined
  249. },
  250. /** @type {boolean?} Rating数据防剧透 */
  251. ratingHidden: undefined,
  252. /** @type {string?} Clist key */
  253. authorization: undefined
  254. };
  255.  
  256. /**
  257. * @namespace monaco
  258. * @desc Monaco编辑器配置。
  259. * @memberof OJBetter
  260. */
  261. OJBetter.monaco = {
  262. /** @type {boolean?} 在问题页面上启用Monaco编辑器 */
  263. enableOnProblemPage: undefined,
  264. /** @type {boolean?} 美化pre代码块 */
  265. beautifyPreBlocks: undefined,
  266. /** @type {boolean} Monaco编辑器加载完成标志 */
  267. loaderOnload: false,
  268. lsp: {
  269. /** @type {Array?} LSP套接字数组 */
  270. socket: [],
  271. /** @type {boolean?} 是否启用LSP */
  272. enabled: undefined,
  273. /** @type {string?} 工作路径 */
  274. workUri: undefined,
  275. /** @type {string?} 套接字URL */
  276. socketUrl: undefined
  277. },
  278. complet: {
  279. /** @type {boolean?} 是否启用C++代码补全模板 */
  280. cppCodeTemplate: undefined,
  281. /** @type {Object?} 自定义配置 */
  282. customConfig: undefined
  283. },
  284. /** @type {Object?} Monaco编辑器实例 */
  285. editor: null,
  286. /** @type {string?} 在线编译器选择 */
  287. onlineCompilerChoice: undefined,
  288. /** @type {string?} 记忆编译器语言选择 */
  289. compilerSelection: undefined,
  290. /** @type {string?} 当前选择的语言 */
  291. nowLangSelect: undefined,
  292. setting: {
  293. /** @type {Array?} 语言设置数组 */
  294. language: [],
  295. /** @type {string?} 位置 */
  296. position: undefined,
  297. /** @type {boolean} 位置初始化标志 */
  298. position_initialized: false,
  299. /** @type {number?} 字体大小 */
  300. fontsize: undefined,
  301. /** @type {boolean?} 鼠标滚动锁定 */
  302. alwaysConsumeMouseWheel: undefined,
  303. /** @type {boolean?} 提交代码二次确认 */
  304. isCodeSubmitDoubleConfirm: undefined,
  305. /** @type {string?} 提交按钮位置 */
  306. submitButtonPosition: undefined
  307. }
  308. };
  309.  
  310. /**
  311. * @namespace deepl
  312. * @desc DeepL翻译服务配置。
  313. * @memberof OJBetter
  314. */
  315. OJBetter.deepl = {
  316. /** @type {Object?} DeepL配置对象 */
  317. configs: undefined,
  318. config: {
  319. /** @type {string?} 类型 */
  320. type: undefined,
  321. /** @type {string?} 名称 */
  322. name: undefined,
  323. /** @type {string?} API类型 */
  324. apiGenre: undefined,
  325. /** @type {string?} API密钥 */
  326. key: undefined,
  327. /** @type {string?} 代理 */
  328. proxy: undefined,
  329. /** @type {Object?} 额外请求头 */
  330. header: undefined,
  331. /** @type {Object?} 额外请求数据 */
  332. data: undefined,
  333. quota: {
  334. /** @type {string?} 余额URL */
  335. url: undefined,
  336. /** @type {string?} 余额请求方法 */
  337. method: undefined,
  338. /** @type {Object?} 余额请求头 */
  339. header: undefined,
  340. /** @type {Object?} 余额请求数据 */
  341. data: undefined,
  342. /** @type {number?} 剩余配额 */
  343. surplus: undefined
  344. }
  345. },
  346. /** @type {boolean?} 启用重点保护 */
  347. enableEmphasisProtection: undefined,
  348. /** @type {boolean?} 启用链接保护 */
  349. enableLinkProtection: undefined
  350. };
  351.  
  352. /**
  353. * @namespace chatgpt
  354. * @desc ChatGPT服务配置。
  355. * @memberof OJBetter
  356. */
  357. OJBetter.chatgpt = {
  358. /** @type {Object?} ChatGPT配置对象 */
  359. configs: undefined,
  360. config: {
  361. /** @type {string?} 名称 */
  362. name: undefined,
  363. /** @type {string?} 模型 */
  364. model: undefined,
  365. /** @type {string?} API密钥 */
  366. key: undefined,
  367. /** @type {string?} 代理 */
  368. proxy: undefined,
  369. /** @type {Object?} 额外请求头 */
  370. header: undefined,
  371. /** @type {Object?} 额外请求数据 */
  372. data: undefined,
  373. quota: {
  374. /** @type {string?} 余额URL */
  375. url: undefined,
  376. /** @type {string?} 余额请求方法 */
  377. method: undefined,
  378. /** @type {Object?} 余额请求头 */
  379. header: undefined,
  380. /** @type {Object?} 余额请求数据 */
  381. data: undefined,
  382. /** @type {number?} 剩余配额 */
  383. surplus: undefined
  384. }
  385. },
  386. /** @type {boolean?} 是否为流式传输 */
  387. isStream: undefined
  388. };
  389.  
  390. /**
  391. * @namespace preference
  392. * @desc 偏好设置
  393. * @memberof OJBetter
  394. */
  395. OJBetter.preference = {
  396. /** @type {boolean?} 是否显示加载动画 */
  397. showLoading: undefined,
  398. /** @type {boolean?} 是否显示悬停目标区域 */
  399. hoverTargetAreaDisplay: undefined,
  400. /** @type {string?} 按钮图标大小 */
  401. iconButtonSize: undefined,
  402. };
  403.  
  404. /**
  405. * @namespace about
  406. * @desc 关于页信息
  407. * @memberof OJBetter
  408. */
  409. OJBetter.about = {
  410. /** @type {string?} 更新通道 */
  411. updateChannel: undefined,
  412. /** @type {string?} 更新源 */
  413. updateSource: undefined
  414. };
  415.  
  416. /**
  417. * @namespace supportList
  418. * @desc 支持列表
  419. * @memberof OJBetter
  420. */
  421. OJBetter.supportList = {
  422. /** @type {object} 翻译支持列表和对应语言代码*/
  423. translationSupport: {
  424. 'deepl': { 'zh': 'ZH', 'de': 'DE', 'fr': 'FR', 'ko': 'KO', 'pt': 'PT', 'ja': 'JA', 'es': 'ES', 'it': 'IT' },
  425. 'iflyrec': { 'zh': '1' },
  426. 'youdao': { 'zh': 'AUTO' },
  427. 'google': { 'zh': 'zh-CN', 'zh-Hant': 'zh-TW', 'de': 'de', 'fr': 'fr', 'ko': 'ko', 'pt': 'pt', 'ja': 'ja', 'es': 'es', 'it': 'it', 'hi': 'hi' },
  428. 'caiyun': { 'zh': 'auto2zh', 'ja': 'auto2ja', 'ko': 'auto2ko', 'es': 'auto2es', 'fr': 'auto2fr' },
  429. 'openai': { 'zh': 'Chinese', 'zh-Hant': 'Traditional Chinese', 'de': 'German', 'fr': 'French', 'ko': 'Korean', 'pt': 'Portuguese', 'ja': 'Japanese', 'es': 'Spanish', 'it': 'Italian', 'hi': 'Hindi' }
  430. },
  431. /** @type {object} 更新源支持列表*/
  432. updateSourceSupportList: {
  433. 'greasyfork': {
  434. 'release': true,
  435. 'dev': false
  436. },
  437. 'github': {
  438. 'release': true,
  439. 'dev': true
  440. },
  441. 'aliyunoss': {
  442. 'release': true,
  443. 'dev': true
  444. }
  445. }
  446. }
  447.  
  448. // ------------------------------
  449. // 一些工具函数
  450. // ------------------------------
  451.  
  452. /**
  453. * 安全地创建jQuery元素
  454. * @description 通过jQuery创建HTML字符串时,如果字符串以空格开头,在某些Jquery版本中会发生错误,过滤空格以安全的创建元素。
  455. * @param {string} htmlString - HTML字符串。
  456. * @returns jQuery对象
  457. */
  458. const OJB_safeCreateJQElement = function (htmlString) {
  459. return $(htmlString.replace(/^\s+/, ""));
  460. }
  461.  
  462.  
  463. /**
  464. * 将数字或者字符串解析为数字。
  465. * @memberof OJBetter.common
  466. * @param {string} val 要解析的字符串
  467. * @param {boolean} [strict=false] 是否进行严格类型检查
  468. * @returns {number} 解析结果
  469. * @throws {Error} 如果解析失败,则抛出错误
  470. */
  471. const OJB_parseNumber = (val, strict = false) => {
  472. const num = Number(val);
  473. if (isNaN(num) || (strict && val.toString() !== num.toString())) {
  474. throw new Error('Invalid number');
  475. }
  476. return num;
  477. };
  478.  
  479. /**
  480. * 将字符串解析为布尔值
  481. * @param {string} val - 要解析的字符串
  482. * @param {boolean} strict - 是否进行严格类型检查
  483. * @returns {boolean} - 解析结果
  484. * @throws {Error} - 如果解析失败,则抛出错误
  485. */
  486. const OJB_parseBoolean = (val, strict) => {
  487. if (strict) {
  488. if (val === true || val === false) return val;
  489. throw new Error('Invalid boolean');
  490. }
  491. return val === 'true' ? true : val === 'false' ? false : val;
  492. };
  493.  
  494. /**
  495. * 将字符串解析为对象
  496. * @param {string} val - 要解析的字符串
  497. * @returns {Object} - 解析结果
  498. * @throws {Error} - 如果解析失败,则抛出错误
  499. */
  500. const OJB_parseObject = val => {
  501. try {
  502. return JSON.parse(val);
  503. } catch {
  504. throw new Error('Invalid JSON');
  505. }
  506. };
  507.  
  508. /**
  509. * 将字符串解析为键值对数组
  510. * @param {string} val - 要解析的字符串
  511. * @returns {Object[]} - 解析结果
  512. * @throws {Error} - 如果解析失败,则抛出错误
  513. */
  514. const OJB_parseLinePairArray = val => {
  515. if (typeof val !== 'string' || val.trim() === '') return [];
  516. return val.split("\n").filter(line => line.trim() !== '').map(line => {
  517. const indexOfFirstColon = line.indexOf(":");
  518. if (indexOfFirstColon === -1) throw new Error('Invalid LinePairArray format: ":" is missing');
  519. const key = line.substring(0, indexOfFirstColon).trim();
  520. const value = line.substring(indexOfFirstColon + 1).trim();
  521. return { [key]: value };
  522. });
  523. };
  524.  
  525. /**
  526. * 移除文本中的HTML标签
  527. * @param {string} text - 包含HTML标签的文本
  528. * @returns {string} - 移除HTML标签后的文本
  529. */
  530. const OJB_removeHTMLTags = function (text) {
  531. return text.replace(/<\/?[a-zA-Z]+("[^"]*"|'[^']*'|[^'">])*>/g, '');
  532. }
  533.  
  534. /**
  535. * 获取对象中指定路径表达式的值
  536. * @param {Object} obj - 要计算的对象
  537. * @param {string} pathOrExpression - 要计算的路径表达式
  538. * @returns {any} - 计算结果
  539. * @example
  540. * const obj = {
  541. * "a": {
  542. * "b": 1
  543. * },
  544. * "c": 2
  545. * };
  546. * evaluatePathOrExpression(obj, "a.b"); // 1
  547. * evaluatePathOrExpression(obj, "a.b + c"); // 3
  548. * evaluatePathOrExpression(obj, "a.b + a.c"); // 1
  549. */
  550. function OJB_evaluatePathOrExpression(obj, pathOrExpression) {
  551. const hasOperator = /[\+\-\*\/]/.test(pathOrExpression);
  552. const getPathValue = (obj, path) => {
  553. return path.split('.').reduce((acc, part) => {
  554. return acc !== undefined && acc !== null && acc.hasOwnProperty(part) ? acc[part] : undefined;
  555. }, obj);
  556. };
  557. const evaluateExpression = (obj, expression) => {
  558. const tokens = expression.split(/([\+\-\*\/])/).map(token => token.trim());
  559. const values = tokens.map(token => {
  560. if (/[\+\-\*\/]/.test(token)) {
  561. return token;
  562. } else {
  563. const value = getPathValue(obj, token);
  564. return value !== undefined ? value : 0;
  565. }
  566. });
  567. const evaluatedExpression = values.join(' ');
  568. try {
  569. return Function(`'use strict'; return (${evaluatedExpression});`)();
  570. } catch (e) {
  571. console.error('Expression evaluation error:', e);
  572. return undefined;
  573. }
  574. };
  575. return hasOperator ? evaluateExpression(obj, pathOrExpression) : getPathValue(obj, pathOrExpression);
  576. }
  577.  
  578. /**
  579. * 获取 GM 存储的值并根据类型进行处理
  580. * @param {string} key - 要检索的值的键。
  581. * @param {any} defaultValue - 如果值未找到,则返回的默认值。
  582. * @param {Object} [options={}] - 配置选项对象。
  583. * @param {string} [options.type='string'] - 期望的值的类型。可选值:'string', 'number', 'boolean', 'object', 'array', 'linePairArray'。
  584. * @param {boolean} [options.strict=false] - 用于数字和布尔类型,表示是否进行严格类型检查。
  585. * @param {string} [options.pathOrExpression=''] - 用于对象或数组类型,表示路径表达式或获取元素的索引。
  586. * @returns {any} - 检索到的值。
  587. */
  588. const OJB_getGMValue = (key, defaultValue, { type = 'string', strict = false, pathOrExpression = '' } = {}) => {
  589. let value = GM_getValue(key);
  590. if (value === undefined || value === null || value === "") {
  591. GM_setValue?.(key, defaultValue);
  592. return defaultValue;
  593. }
  594.  
  595. const parsers = {
  596. string: val => val,
  597. number: (val) => OJB_parseNumber(val, strict),
  598. boolean: (val) => OJB_parseBoolean(val, strict),
  599. object: OJB_parseObject,
  600. array: OJB_parseObject,
  601. linePairArray: OJB_parseLinePairArray
  602. };
  603.  
  604. if (!(type in parsers)) {
  605. console.error(`Unsupported type: ${type}`);
  606. return defaultValue;
  607. }
  608.  
  609. try {
  610. value = parsers[type](value);
  611. } catch (e) {
  612. console.error('Error:', e.message);
  613. return defaultValue;
  614. }
  615.  
  616. // The pathOrExpression processing is not applicable to linePairArray type
  617. if ((type === 'object' || type === 'array') && pathOrExpression) {
  618. const evaluated = OJB_evaluatePathOrExpression(value, pathOrExpression);
  619. if (evaluated === undefined) {
  620. console.error('Path or expression evaluation returned undefined');
  621. return defaultValue;
  622. }
  623. value = evaluated;
  624. }
  625.  
  626. return value;
  627. };
  628.  
  629. /**
  630. * 版本号比较方法
  631. * @param {string} version1 版本号1
  632. * @param {string} version2 版本号2
  633. * @returns {number} -1: version1 < version2, 0: version1 = version2, 1: version1 > version2
  634. */
  635. const OJB_compareVersions = function (version1 = "0", version2 = "0") {
  636. const v1Array = version1.split(".").map(Number);
  637. const v2Array = version2.split(".").map(Number);
  638. const length = Math.max(v1Array.length, v2Array.length);
  639. for (let i = 0; i < length; i++) {
  640. const diff = (v1Array[i] || 0) - (v2Array[i] || 0);
  641. if (diff) return Math.sign(diff);
  642. }
  643. return 0;
  644. }
  645.  
  646. /**
  647. * 获取上一个主版本号
  648. * @param {string} currentVersion 当前版本号
  649. * @returns {string} 上一个主版本号
  650. */
  651. const OJB_getPreviousVersion = function (currentVersion) {
  652. const versionArray = currentVersion.split(".").map(Number);
  653. let lastNonZeroIndex = versionArray.length - 1;
  654. while (lastNonZeroIndex >= 0 && versionArray[lastNonZeroIndex] === 0) {
  655. lastNonZeroIndex--;
  656. }
  657. if (lastNonZeroIndex >= 0) {
  658. versionArray[lastNonZeroIndex]--;
  659. for (let i = lastNonZeroIndex + 1; i < versionArray.length; i++) {
  660. versionArray[i] = 0;
  661. }
  662. }
  663. return versionArray.join(".");
  664. };
  665.  
  666. /**
  667. * 在指定根节点下观察指定选择器的元素,当元素存在时,执行回调函数
  668. * @param {Object} options - 配置对象
  669. * @param {string} options.selector - CSS选择器文本
  670. * @param {Function} options.callback - 回调函数,接收变动的节点作为参数
  671. * @param {Boolean} [options.triggerOnExist=true] - 如果为true,元素已存在时立即触发一次回调
  672. * @param {Element} [options.root=document.body] - 在哪个根节点下监听变化
  673. * @param {Boolean} [options.subtree=false] - 是否监听子树变化(即非直接子元素)
  674. */
  675. function OJB_observeElement({
  676. selector,
  677. callback,
  678. triggerOnExist = true,
  679. root = document.body,
  680. subtree = false
  681. }) {
  682. // 尝试获取选择器指定的元素
  683. const targetNode = root.querySelector(selector);
  684.  
  685. if (targetNode) {
  686. // 如果元素已存在,直接开始观察
  687. observeAndReport(targetNode, callback);
  688. // 如果triggerOnExist为true,则立即触发一次回调
  689. if (triggerOnExist) {
  690. callback(targetNode);
  691. }
  692. } else {
  693. // 如果元素不存在,监听DOM变化直到该元素被添加
  694. const observer = new MutationObserver((mutations) => {
  695. mutations.forEach((mutation) => {
  696. mutation.addedNodes.forEach((node) => {
  697. if (node.nodeType === Node.ELEMENT_NODE && node.matches(selector)) {
  698. observeAndReport(node, callback);
  699. if (triggerOnExist) {
  700. callback(node);
  701. }
  702. observer.disconnect(); // 停止监听
  703. }
  704. });
  705. });
  706. });
  707.  
  708. observer.observe(root, { childList: true, subtree, attributes: false });
  709. }
  710.  
  711. function observeAndReport(node, callback) {
  712. const childObserver = new MutationObserver((mutations) => {
  713. mutations.forEach((mutation) => {
  714. if (childList) {
  715. mutation.addedNodes.forEach((addedNode) => {
  716. if (addedNode.nodeType === Node.ELEMENT_NODE) {
  717. callback(addedNode); // 执行回调函数
  718. }
  719. });
  720. }
  721. if (attributes && mutation.type === 'attributes') {
  722. callback(mutation.target); // 执行回调函数
  723. }
  724. });
  725. });
  726.  
  727. childObserver.observe(node, { childList: true, subtree: true, attributes: false });
  728. }
  729. }
  730.  
  731. /**
  732. * 初始化全局变量
  733. */
  734. async function initVar() {
  735. const { hostname, href } = window.location;
  736. OJBetter.state.formatName = (() => OJBetter.state.name
  737. .toLowerCase()
  738. .replace(/\s+/g, '-')
  739. .replace(/[^a-z0-9-]/g, ''))();
  740. OJBetter.state.lastAnnounceVer = OJB_getGMValue("lastAnnounceVer", "0");
  741. OJBetter.state.lastReadAnnounceVer = OJB_getGMValue("lastReadAnnounceVer", "0");
  742. OJBetter.typeOfPage.is_contest = /\/contests\/[^\/]+\/tasks\/?$/.test(href);
  743. OJBetter.typeOfPage.is_problem = href.includes('/tasks/');
  744. OJBetter.typeOfPage.is_homepage = (href === 'https://atcoder.jp/' || href === 'https://atcoder.jp/?lang=ja');
  745. OJBetter.localization.websiteLang = OJB_getGMValue("localizationLanguage", "zh");
  746. OJBetter.localization.scriptLang = OJB_getGMValue("scriptL10nLanguage", "zh");
  747. OJBetter.basic.renderPerfOpt = OJB_getGMValue("renderPerfOpt", false);
  748. OJBetter.basic.commentPaging = OJB_getGMValue("commentPaging", true);
  749. OJBetter.basic.showJumpToLuogu = OJB_getGMValue("showJumpToLuogu", true);
  750. OJBetter.basic.showCF2vjudge = OJB_getGMValue("showCF2vjudge", true);
  751. OJBetter.basic.standingsRecolor = OJB_getGMValue("standingsRecolor", true);
  752. OJBetter.state.notWaiteLoaded = OJB_getGMValue("notWaiteLoaded", false);
  753. OJBetter.translation.targetLang = OJB_getGMValue("transTargetLang", "zh");
  754. OJBetter.translation.choice = OJB_getGMValue("translation", "deepl");
  755. OJBetter.translation.comment.transMode = OJB_getGMValue("commentTranslationMode", "0");
  756. OJBetter.translation.comment.choice = OJB_getGMValue("commentTranslationChoice", "0");
  757. OJBetter.translation.memory.enabled = OJB_getGMValue("memoryTranslateHistory", true);
  758. OJBetter.translation.auto.enabled = OJB_getGMValue("autoTranslation", false);
  759. OJBetter.translation.auto.shortTextLength = OJB_getGMValue("shortTextLength", "2000");
  760. OJBetter.translation.retransAction = OJB_getGMValue("retransAction", "0");
  761. OJBetter.translation.waitTime = OJB_getGMValue("transWaitTime", "200");
  762. OJBetter.translation.auto.mixTrans.enabled = OJB_getGMValue("allowMixTrans", true);
  763. OJBetter.translation.auto.mixTrans.servers = OJB_getGMValue("mixedTranslation", ['deepl', 'iflyrec', 'youdao', 'caiyun']);
  764. OJBetter.common.taskQueue = new TaskQueue();
  765. OJBetter.translation.replaceSymbol = OJB_getGMValue("replaceSymbol", "2");
  766. OJBetter.translation.filterTextWithoutEmphasis = OJB_getGMValue("filterTextWithoutEmphasis", false);
  767. OJBetter.clist.enabled.contest = OJB_getGMValue("showClistRating_contest", false);
  768. OJBetter.clist.enabled.problem = OJB_getGMValue("showClistRating_problem", false);
  769. OJBetter.clist.enabled.problemset = OJB_getGMValue("showClistRating_problemset", false);
  770. OJBetter.clist.ratingHidden = OJB_getGMValue("RatingHidden", false);
  771. OJBetter.clist.authorization = OJB_getGMValue("clist_Authorization", "");
  772. //deepl
  773. OJBetter.deepl.config.type = OJB_getGMValue("deepl_type", "free");
  774. OJBetter.deepl.configs = OJB_getGMValue("deepl_config", {
  775. "choice": "",
  776. "configurations": []
  777. });
  778. if (OJBetter.deepl.configs.choice !== "" && OJBetter.deepl.configs.configurations.length !== 0) {
  779. const choice = OJBetter.deepl.configs.choice;
  780. const configuration = OJBetter.deepl.configs.configurations.find(obj => obj.name === choice);;
  781. if (configuration == undefined) {
  782. let existingConfig = GM_getValue('deepl_config');
  783. existingConfig.choice = "";
  784. GM_setValue('deepl_config', existingConfig);
  785. location.reload();
  786. }
  787. OJBetter.deepl.config.name = configuration.name;
  788. OJBetter.deepl.config.apiGenre = configuration.apiGenre;
  789. OJBetter.deepl.config.key = configuration.key;
  790. OJBetter.deepl.config.proxy = configuration.proxy;
  791. OJBetter.deepl.config.header = OJB_parseLinePairArray(configuration._header);
  792. OJBetter.deepl.config.data = OJB_parseLinePairArray(configuration._data);
  793. OJBetter.deepl.config.quota.url = configuration.quota_url;
  794. OJBetter.deepl.config.quota.method = configuration.quota_method;
  795. OJBetter.deepl.config.quota.header = OJB_parseLinePairArray(configuration.quota_header);
  796. OJBetter.deepl.config.quota.data = OJB_parseLinePairArray(configuration.quota_data);
  797. OJBetter.deepl.config.quota.surplus = configuration.quota_surplus;
  798. }
  799. OJBetter.deepl.enableEmphasisProtection = OJB_getGMValue("enableEmphasisProtection", true);
  800. OJBetter.deepl.enableLinkProtection = OJB_getGMValue("enableLinkProtection", true);
  801. //openai
  802. OJBetter.chatgpt.isStream = OJB_getGMValue("openai_isStream", true);
  803. OJBetter.chatgpt.configs = OJB_getGMValue("chatgpt_config", {
  804. "choice": "",
  805. "configurations": []
  806. });
  807. if (OJBetter.chatgpt.configs.choice !== "" && OJBetter.chatgpt.configs.configurations.length !== 0) {
  808. const choice = OJBetter.chatgpt.configs.choice;
  809. const configuration = OJBetter.chatgpt.configs.configurations.find(obj => obj.name === choice);;
  810. if (configuration == undefined) {
  811. let existingConfig = GM_getValue('chatgpt_config');
  812. existingConfig.choice = "";
  813. GM_setValue('chatgpt_config', existingConfig);
  814. location.reload();
  815. }
  816. OJBetter.chatgpt.config.name = configuration.name;
  817. OJBetter.chatgpt.config.model = configuration.model;
  818. OJBetter.chatgpt.config.key = configuration.key;
  819. OJBetter.chatgpt.config.proxy = configuration.proxy;
  820. OJBetter.chatgpt.config.header = OJB_parseLinePairArray(configuration._header);
  821. OJBetter.chatgpt.config.data = OJB_parseLinePairArray(configuration._data);
  822. OJBetter.chatgpt.config.quota.url = configuration.quota_url;
  823. OJBetter.chatgpt.config.quota.method = configuration.quota_method;
  824. OJBetter.chatgpt.config.quota.header = OJB_parseLinePairArray(configuration.quota_header);
  825. OJBetter.chatgpt.config.quota.data = OJB_parseLinePairArray(configuration.quota_data);
  826. OJBetter.chatgpt.config.quota.surplus = configuration.quota_surplus;
  827. }
  828. // 编辑器
  829. // if (!OJBetter.typeOfPage.is_mSite) OJBetter.common.cf_csrf_token = Codeforces.getCsrfToken();
  830. // else OJBetter.common.cf_csrf_token = "";
  831. OJBetter.common.at_csrf_token = csrfToken;
  832. // OJBetter.monaco.compilerSelection = OJB_getGMValue("compilerSelection", "61");
  833. OJBetter.monaco.compilerSelection = OJB_getGMValue("compilerSelection", "5001");
  834. OJBetter.monaco.setting.fontsize = OJB_getGMValue("editorFontSize", "15");
  835. OJBetter.monaco.enableOnProblemPage = OJB_getGMValue("problemPageCodeEditor", true);
  836. OJBetter.monaco.beautifyPreBlocks = OJB_getGMValue("beautifyPreBlocks", true);
  837. OJBetter.monaco.complet.cppCodeTemplate = OJB_getGMValue("cppCodeTemplateComplete", true);
  838. OJBetter.monaco.onlineCompilerChoice = OJB_getGMValue("onlineCompilerChoice", "official");
  839. OJBetter.monaco.setting.isCodeSubmitDoubleConfirm = OJB_getGMValue("isCodeSubmitConfirm", true);
  840. OJBetter.monaco.setting.alwaysConsumeMouseWheel = OJB_getGMValue("alwaysConsumeMouseWheel", true);
  841. OJBetter.monaco.setting.submitButtonPosition = OJB_getGMValue("submitButtonPosition", "bottom");
  842. //自定义补全
  843. OJBetter.monaco.complet.customConfig = OJB_getGMValue("Complet_config", {
  844. "choice": -1,
  845. "configurations": []
  846. });
  847. /**
  848. * 加载monaco编辑器资源
  849. */
  850. OJBetter.monaco.lsp.enabled = OJB_getGMValue("useLSP", false);
  851. OJBetter.monaco.setting.position = OJB_getGMValue("monacoEditor_position", "initial");
  852. OJBetter.monaco.lsp.workUri = OJB_getGMValue("OJBetter_Bridge_WorkUri", "C:/OJBetter_Bridge");
  853. OJBetter.monaco.lsp.socketUrl = OJB_getGMValue("OJBetter_Bridge_SocketUrl", "ws://127.0.0.1:2323/");
  854. if (OJBetter.monaco.enableOnProblemPage || OJBetter.monaco.beautifyPreBlocks) {
  855. let monacoLoader = document.createElement("script");
  856. monacoLoader.src = "https://cdn.staticfile.net/monaco-editor/0.44.0/min/vs/loader.min.js";
  857. document.head.prepend(monacoLoader);
  858. monacoLoader.onload = () => {
  859. require.config({
  860. paths: { vs: "https://cdn.staticfile.net/monaco-editor/0.44.0/min/vs" },
  861. "vs/nls": { availableLanguages: { "*": "zh-cn" } },
  862. });
  863. require(["vs/editor/editor.main"], () => {
  864. OJBetter.monaco.loaderOnload = true;
  865. });
  866. }
  867. }
  868. OJBetter.preference.showLoading = OJB_getGMValue("showLoading", true);
  869. OJBetter.preference.hoverTargetAreaDisplay = OJB_getGMValue("hoverTargetAreaDisplay", false);
  870. OJBetter.basic.expandFoldingblocks = OJB_getGMValue("expandFoldingblocks", true);
  871. OJBetter.preference.iconButtonSize = OJB_getGMValue("iconButtonSize", "16");
  872. OJBetter.about.updateChannel = OJB_getGMValue("updateChannel", "release");
  873. OJBetter.about.updateSource = OJB_getGMValue("updateSource", "greasyfork");
  874. }
  875.  
  876. /**
  877. * 显示警告消息
  878. */
  879. function showWarnMessage() {
  880. if (OJBetter.typeOfPage.is_oldLatex) {
  881. const loadingMessage = new LoadingMessage();
  882. loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('warning.is_oldLatex', { ns: 'alert' })}`, 'warning');
  883. }
  884. if (OJBetter.typeOfPage.is_acmsguru) {
  885. const loadingMessage = new LoadingMessage();
  886. loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('warning.is_acmsguru', { ns: 'alert' })}`, 'warning');
  887. }
  888. if (OJBetter.translation.comment.transMode == "1") {
  889. const loadingMessage = new LoadingMessage();
  890. loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('warning.trans_segment', { ns: 'alert' })}`, 'warning');
  891. }
  892. if (OJBetter.translation.comment.transMode == "2") {
  893. const loadingMessage = new LoadingMessage();
  894. loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('warning.trans_select', { ns: 'alert' })}`, 'warning');
  895. }
  896. if (OJBetter.typeOfPage.is_submitPage && OJBetter.monaco.enableOnProblemPage) {
  897. const loadingMessage = new LoadingMessage();
  898. loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('warning.is_submitPage', { ns: 'alert' })}`, 'warning');
  899. }
  900. }
  901.  
  902. // 常量
  903. const helpCircleHTML = '<div class="help-icon"><svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M512 64a448 448 0 1 1 0 896 448 448 0 0 1 0-896zm23.744 191.488c-52.096 0-92.928 14.784-123.2 44.352-30.976 29.568-45.76 70.4-45.76 122.496h80.256c0-29.568 5.632-52.8 17.6-68.992 13.376-19.712 35.2-28.864 66.176-28.864 23.936 0 42.944 6.336 56.32 19.712 12.672 13.376 19.712 31.68 19.712 54.912 0 17.6-6.336 34.496-19.008 49.984l-8.448 9.856c-45.76 40.832-73.216 70.4-82.368 89.408-9.856 19.008-14.08 42.24-14.08 68.992v9.856h80.96v-9.856c0-16.896 3.52-31.68 10.56-45.76 6.336-12.672 15.488-24.64 28.16-35.2 33.792-29.568 54.208-48.576 60.544-55.616 16.896-22.528 26.048-51.392 26.048-86.592 0-42.944-14.08-76.736-42.24-101.376-28.16-25.344-65.472-37.312-111.232-37.312zm-12.672 406.208a54.272 54.272 0 0 0-38.72 14.784 49.408 49.408 0 0 0-15.488 38.016c0 15.488 4.928 28.16 15.488 38.016A54.848 54.848 0 0 0 523.072 768c15.488 0 28.16-4.928 38.72-14.784a51.52 51.52 0 0 0 16.192-38.72 51.968 51.968 0 0 0-15.488-38.016 55.936 55.936 0 0 0-39.424-14.784z"></path></svg></div>';
  904. const closeIcon = `<svg t="1696693011050" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4322" width="14" height="14"><path d="M0 0h1024v1024H0z" fill-opacity="0" p-id="4323"></path><path d="M240.448 168l2.346667 2.154667 289.92 289.941333 279.253333-279.253333a42.666667 42.666667 0 0 1 62.506667 58.026666l-2.133334 2.346667-279.296 279.210667 279.274667 279.253333a42.666667 42.666667 0 0 1-58.005333 62.528l-2.346667-2.176-279.253333-279.253333-289.92 289.962666a42.666667 42.666667 0 0 1-62.506667-58.005333l2.154667-2.346667 289.941333-289.962666-289.92-289.92a42.666667 42.666667 0 0 1 57.984-62.506667z" p-id="4324"></path></svg>`;
  905. const translateIcon = `<svg t="1696837407077" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6325" width="22" height="22"><path d="M536.380952 121.904762a73.142857 73.142857 0 0 1 73.142858 73.142857v219.428571h219.428571a73.142857 73.142857 0 0 1 73.142857 73.142858v341.333333a73.142857 73.142857 0 0 1-73.142857 73.142857H487.619048a73.142857 73.142857 0 0 1-73.142858-73.142857v-219.428571H195.047619a73.142857 73.142857 0 0 1-73.142857-73.142858V195.047619a73.142857 73.142857 0 0 1 73.142857-73.142857h341.333333zM243.809524 682.666667v97.523809h97.523809v73.142857h-97.523809a73.142857 73.142857 0 0 1-73.142857-73.142857v-97.523809h73.142857z m585.142857-195.047619h-219.428571v48.761904a73.142857 73.142857 0 0 1-73.142858 73.142858h-48.761904v219.428571h341.333333V487.619048z m-115.760762 89.526857L787.21219 780.190476h-62.025142l-14.043429-42.715428h-76.068571L620.739048 780.190476h-60.854858l74.605715-203.044571h78.701714z m-38.034286 50.029714h-3.510857l-21.065143 63.488h45.348572l-20.772572-63.488zM536.380952 195.047619H195.047619v341.333333h341.333333V195.047619z
  906. m-195.072 49.883429l44.78781 1.072762v37.278476h87.698286v145.359238h-87.698286v65.974857h-44.78781v-65.974857h-87.698285v-145.359238h87.698285v-38.351238z m0 83.139047h-44.787809v56.05181h44.787809v-56.05181z m89.307429 0h-44.519619v56.05181h44.519619v-56.05181zM780.190476 170.666667a73.142857 73.142857 0 0 1 73.142857 73.142857v97.523809h-73.142857v-97.523809h-97.523809V170.666667h97.523809z" p-id="6326"></path></svg>`;
  907. const clistIcon = `<svg width="37.7pt" height="10pt" viewBox="0 0 181 48" version="1.1" xmlns="http://www.w3.org/2000/svg"><g id="#0057b8ff"><path fill="#0057b8" opacity="1.00" d=" M 17.36 0.00 L 18.59 0.00 C 23.84 6.49 30.28 11.92 36.01 17.98 C 34.01 19.99 32.01 21.99 30.00 23.99 C 26.02 19.97 22.02 15.98 18.02 11.99 C 14.01 15.98 10.01 19.99 6.00 23.99 C 4.16 22.04 2.30 20.05 0.00 18.61 L 0.00 17.37 C 3.44 15.11 6.00 11.84 8.96 9.03 C 11.79 6.05 15.09 3.47 17.36 0.00 Z" /></g><g id="#a0a0a0ff"><path fill="#a0a0a0" opacity="1.00" d=" M 56.76 13.74 C 61.48 4.80 76.07 3.90 81.77 12.27 C 83.09 13.94 83.44 16.10 83.91 18.12 C 81.53 18.23 79.16 18.24 76.78 18.23 C 75.81 15.72 73.99 13.31 71.14 12.95 C 67.14 12.02 63.45 15.29 62.48 18.99 C 61.30 23.27 61.71 28.68 65.34 31.70 C 67.82 34.05 72.19 33.93 74.61 31.55 C 75.97 30.18 76.35 28.23 76.96 26.48 C 79.36 26.43 81.77 26.44 84.17 26.56 C 83.79 30.09 82.43 33.49 79.89 36.02 C 74.14 41.35 64.17 40.80 58.77 35.25 C 53.52 29.56 53.18 20.38 56.76 13.74 Z" />
  908. <path fill="#a0a0a0" opacity="1.00" d=" M 89.01 7.20 C 91.37 7.21 93.74 7.21 96.11 7.22 C 96.22 15.71 96.10 24.20 96.18 32.69 C 101.25 32.76 106.32 32.63 111.39 32.79 C 111.40 34.86 111.41 36.93 111.41 39.00 C 103.94 39.00 96.47 39.00 89.00 39.00 C 89.00 28.40 88.99 17.80 89.01 7.20 Z" /><path fill="#a0a0a0" opacity="1.00" d=" M 115.00 7.21 C 117.33 7.21 119.66 7.21 121.99 7.21 C 122.01 17.81 122.00 28.40 122.00 39.00 C 119.67 39.00 117.33 39.00 115.00 39.00 C 115.00 28.40 114.99 17.80 115.00 7.21 Z" /><path fill="#a0a0a0" opacity="1.00" d=" M 133.35 7.47 C 139.11 5.56 146.93 6.28 150.42 11.87 C 151.42 13.39 151.35 15.31 151.72 17.04 C 149.33 17.05 146.95 17.05 144.56 17.03 C 144.13 12.66 138.66 11.12 135.34 13.30 C 133.90 14.24 133.54 16.87 135.35 17.61 C 139.99 20.02 145.90 19.54 149.92 23.19 C 154.43 26.97 153.16 35.36 147.78 37.72 C 143.39 40.03 137.99 40.11 133.30 38.69 C 128.80 37.34 125.34 32.90 125.91 28.10 C 128.22 28.10 130.53 28.11 132.84 28.16 C 132.98 34.19 142.68 36.07 145.18 30.97 C 146.11 27.99 142.17 27.05 140.05 26.35 C 135.54 25.04 129.83 24.33 127.50 19.63 C 125.30 14.78 128.42 9.00 133.35 7.47 Z" />
  909. <path fill="#a0a0a0" opacity="1.00" d=" M 153.31 7.21 C 161.99 7.21 170.67 7.21 179.34 7.21 C 179.41 9.30 179.45 11.40 179.48 13.50 C 176.35 13.50 173.22 13.50 170.09 13.50 C 170.05 21.99 170.12 30.48 170.05 38.98 C 167.61 39.00 165.18 39.00 162.74 39.00 C 162.64 30.52 162.73 22.04 162.69 13.55 C 159.57 13.49 156.44 13.49 153.32 13.50 C 153.32 11.40 153.31 9.31 153.31 7.21 Z" /></g><g id="#ffd700ff"><path fill="#ffd700" opacity="1.00" d=" M 12.02 29.98 C 14.02 27.98 16.02 25.98 18.02 23.98 C 22.01 27.99 26.03 31.97 30.00 35.99 C 34.01 31.99 38.01 27.98 42.02 23.99 C 44.02 25.98 46.02 27.98 48.01 29.98 C 42.29 36.06 35.80 41.46 30.59 48.00 L 29.39 48.00 C 24.26 41.42 17.71 36.08 12.02 29.98 Z" /></g></svg>`;
  910.  
  911. /**
  912. * 连接数据库
  913. */
  914. async function initDB() {
  915. OJBetter.common.database = new Dexie('OJBetterDB');
  916. OJBetter.common.database.version(3).stores({
  917. samplesData: '&url',
  918. editorCode: '&url',
  919. translateData: '&url',
  920. localizeSubsData: '&lang'
  921. });
  922.  
  923. // 等待数据库打开
  924. await OJBetter.common.database.open();
  925. }
  926.  
  927. /**
  928. * 清空数据库
  929. */
  930. async function clearDatabase() {
  931. const isConfirmed = await OJB_createDialog(
  932. i18next.t('isClearDatabase.title', { ns: 'dialog' }),
  933. i18next.t('isClearDatabase.content', { ns: 'dialog' }),
  934. [
  935. i18next.t('isClearDatabase.buttons.0', { ns: 'dialog' }),
  936. i18next.t('isClearDatabase.buttons.1', { ns: 'dialog' })
  937. ]
  938. );
  939. if (!isConfirmed) {
  940. try {
  941. // 开启一个读写事务,包含数据库中的所有表
  942. await OJBetter.common.database.transaction('rw', OJBetter.common.database.tables, async () => {
  943. // 遍历所有表
  944. for (const table of OJBetter.common.database.tables) {
  945. // 清空当前表
  946. await table.clear();
  947. }
  948. });
  949. console.log("All tables in the database have been cleared.");
  950. alert("All tables in the database have been cleared.");
  951. } catch (error) {
  952. console.error("Error clearing the database:", error);
  953. }
  954. }
  955. }
  956.  
  957. /**
  958. * 导出数据库
  959. * @returns {Promise<string>} 数据库的JSON字符串
  960. */
  961. async function exportDatabase() {
  962. try {
  963. // 创建一个存储数据的对象
  964. const exportData = {};
  965. // 获取数据库中所有表的名称
  966. const tableNames = OJBetter.common.database.tables.map(table => table.name);
  967.  
  968. // 遍历每一个表,获取数据
  969. for (const tableName of tableNames) {
  970. const tableData = await OJBetter.common.database.table(tableName).toArray();
  971. exportData[tableName] = tableData;
  972. }
  973.  
  974. // 将数据对象转换为JSON字符串
  975. const jsonData = JSON.stringify(exportData, null, 4);
  976. return jsonData;
  977. } catch (error) {
  978. console.error("Error exporting database:", error);
  979. }
  980. }
  981.  
  982. /**
  983. * 导入数据库
  984. * @param {string} jsonData 数据库的JSON字符串
  985. */
  986. async function importDatabase(jsonData) {
  987. const isConfirmed = await OJB_createDialog(
  988. i18next.t('isImportDatabase.title', { ns: 'dialog' }),
  989. i18next.t('isImportDatabase.content', { ns: 'dialog' }),
  990. [
  991. i18next.t('isImportDatabase.buttons.0', { ns: 'dialog' }),
  992. i18next.t('isImportDatabase.buttons.1', { ns: 'dialog' })
  993. ]
  994. );
  995. if (!isConfirmed) {
  996. try {
  997. // 将JSON字符串解析为对象
  998. const importData = JSON.parse(jsonData);
  999.  
  1000. // 开启一个事务,并清空现有数据
  1001. await OJBetter.common.database.transaction('rw', OJBetter.common.database.tables, async () => {
  1002. // 清空所有表的数据
  1003. for (const tableName of OJBetter.common.database.tables.map(table => table.name)) {
  1004. await OJBetter.common.database.table(tableName).clear();
  1005. }
  1006.  
  1007. // 插入新数据
  1008. for (const [tableName, rows] of Object.entries(importData)) {
  1009. await OJBetter.common.database.table(tableName).bulkAdd(rows);
  1010. }
  1011. });
  1012. alert("Data imported successfully");
  1013. } catch (error) {
  1014. console.error("Error importing database:", error);
  1015. }
  1016. }
  1017. }
  1018.  
  1019. /**
  1020. * 将数据下载为文件
  1021. * @param {string} data 数据
  1022. * @param {string} filename 文件名,默认为'export.json'
  1023. * @param {string} fileType 文件MIME类型,默认为'application/json'
  1024. * @returns {void}
  1025. */
  1026. function downloadDataAsFile(data, filename = 'export.json', fileType = 'application/json') {
  1027. // 创建一个blob对象,指定文件类型
  1028. const blob = new Blob([data], { type: fileType });
  1029. const url = URL.createObjectURL(blob);
  1030.  
  1031. // 创建一个隐藏的a标签,模拟点击进行下载
  1032. const a = document.createElement('a');
  1033. a.href = url;
  1034. a.download = filename;
  1035. document.body.appendChild(a);
  1036. a.click();
  1037.  
  1038. // 清理
  1039. document.body.removeChild(a);
  1040. URL.revokeObjectURL(url);
  1041. }
  1042.  
  1043.  
  1044. /**
  1045. * 从文件中读取数据
  1046. * @param {Function} callback 回调函数
  1047. * @returns {void}
  1048. */
  1049. function readFileInput(callback) {
  1050. const fileInput = document.createElement('input');
  1051. fileInput.type = 'file';
  1052. fileInput.accept = '.json';
  1053. fileInput.style.display = 'none'; // 隐藏input元素
  1054.  
  1055. fileInput.onchange = (e) => {
  1056. const file = e.target.files[0];
  1057. if (file) {
  1058. const reader = new FileReader();
  1059. reader.onload = (e) => {
  1060. const fileContent = e.target.result;
  1061. if (callback && typeof callback === 'function') {
  1062. callback(fileContent); // 调用回调函数,传入文件内容
  1063. }
  1064. };
  1065. reader.readAsText(file);
  1066. }
  1067. };
  1068.  
  1069. document.body.appendChild(fileInput);
  1070. fileInput.click();
  1071. document.body.removeChild(fileInput);
  1072. }
  1073.  
  1074. /**
  1075. * 删除所有设置
  1076. */
  1077. async function deleteAllConfigSettings() {
  1078. const isConfirmed = await OJB_createDialog(
  1079. i18next.t('isDeleteAllConfigSettings.title', { ns: 'dialog' }),
  1080. i18next.t('isDeleteAllConfigSettings.content', { ns: 'dialog' }),
  1081. [
  1082. i18next.t('isDeleteAllConfigSettings.buttons.0', { ns: 'dialog' }),
  1083. i18next.t('isDeleteAllConfigSettings.buttons.1', { ns: 'dialog' })
  1084. ]
  1085. );
  1086. if (!isConfirmed) {
  1087. const keys = GM_listValues();
  1088.  
  1089. keys.forEach(key => {
  1090. GM_deleteValue(key);
  1091. });
  1092.  
  1093. alert('All settings have been deleted.');
  1094. window.location.reload();
  1095. }
  1096. }
  1097.  
  1098. /**
  1099. * 导出设置到JSON
  1100. * @returns {string} JSON字符串
  1101. */
  1102. function exportSettingsToJSON() {
  1103. const keys = GM_listValues();
  1104. let settings = {};
  1105.  
  1106. keys.forEach(key => {
  1107. settings[key] = GM_getValue(key);
  1108. });
  1109.  
  1110. return JSON.stringify(settings, null, 4);
  1111. }
  1112.  
  1113. /**
  1114. * 从JSON导入设置
  1115. * @param {string} jsonData JSON字符串
  1116. * @returns {void}
  1117. */
  1118. async function importSettingsFromJSON(jsonData) {
  1119. const isConfirmed = await OJB_createDialog(
  1120. i18next.t('isImportSettings.title', { ns: 'dialog' }),
  1121. i18next.t('isImportSettings.content', { ns: 'dialog' }),
  1122. [
  1123. i18next.t('isImportSettings.buttons.0', { ns: 'dialog' }),
  1124. i18next.t('isImportSettings.buttons.1', { ns: 'dialog' })
  1125. ]
  1126. );
  1127. if (!isConfirmed) {
  1128. let settings;
  1129. try {
  1130. settings = JSON.parse(jsonData);
  1131. } catch (e) {
  1132. console.error('JSON parsing error:', e);
  1133. return;
  1134. }
  1135.  
  1136. Object.keys(settings).forEach(key => {
  1137. GM_setValue(key, settings[key]);
  1138. });
  1139.  
  1140. alert('Settings imported successfully!');
  1141. window.location.reload();
  1142. }
  1143. }
  1144.  
  1145. /**
  1146. * 加载元素本地化语言数据
  1147. * @param {JQuery} element jQuery元素
  1148. * @param {number} [retries=10] 重试次数
  1149. * @param {number} [interval=50] 重试间隔
  1150. */
  1151. function elementLocalize(element, retries = 10, interval = 50) {
  1152. if ($.isFunction(element.localize)) {
  1153. element.localize();
  1154. } else if (retries > 0) {
  1155. setTimeout(elementLocalize, interval, element, retries - 1, interval);
  1156. } else {
  1157. console.error('Unable to localize', element);
  1158. }
  1159. }
  1160.  
  1161. // 切换系统黑暗监听
  1162. const mediaQueryList = window.matchMedia('(prefers-color-scheme: dark)');
  1163. const changeEventListeners = [];
  1164. function handleColorSchemeChange(event) {
  1165. event.matches ? $('html').attr('data-theme', 'dark') : $('html').attr('data-theme', 'light');
  1166. if (!event.matches) {
  1167. var originalColor = $(this).data("original-color");
  1168. $(this).css("background-color", originalColor);
  1169. if (OJBetter.monaco.editor) {
  1170. monaco.editor.setTheme('vs');
  1171. }
  1172. } else {
  1173. if (OJBetter.monaco.editor) {
  1174. monaco.editor.setTheme('vs-dark');
  1175. }
  1176. }
  1177. }
  1178.  
  1179. // 黑暗模式
  1180. (function setDark() {
  1181. // 初始化
  1182. function setDarkTheme() {
  1183. const htmlElement = document.querySelector('html');
  1184. if (htmlElement) {
  1185. htmlElement.setAttribute('data-theme', 'dark');
  1186. } else {
  1187. setTimeout(setDarkTheme, 100);
  1188. }
  1189. }
  1190. OJBetter.basic.darkMode = OJB_getGMValue("darkMode", "follow")
  1191. if (OJBetter.basic.darkMode == "dark") {
  1192. setDarkTheme();
  1193. } else if (OJBetter.basic.darkMode == "follow") {
  1194. // 添加事件监听器
  1195. changeEventListeners.push(handleColorSchemeChange);
  1196. mediaQueryList.addEventListener('change', handleColorSchemeChange);
  1197.  
  1198. if (window.matchMedia('(prefers-color-scheme: dark)').matches) setDarkTheme();
  1199. }
  1200.  
  1201. // 定义全局变量
  1202. GM_addStyle(`
  1203. /* 黑暗支持 */
  1204. html[data-theme=dark]:root {
  1205. color-scheme: light dark;
  1206. }
  1207. /* 颜色 */
  1208. :root {
  1209. /* 文字颜色 */
  1210. --ojb-color-text-primary: #a0adb9; /* 主要文字颜色 */
  1211. --ojb-color-text-secondary: #9AA4B1; /* 次要文字颜色 */
  1212. --ojb-color-text-tertiary: #9BA5B2; /* 第三级文字颜色 */
  1213. --ojb-color-text-success: #43A047; /* 成功状态文字颜色 */
  1214. --ojb-color-text-highlight: #cbd6e2; /* 高亮文字颜色 */
  1215. --ojb-color-text-disabled: #506778; /* 禁用状态文字颜色 */
  1216. --ojb-color-text-icon-success: #2e7d32; /* 成功状态图标颜色 */
  1217. --ojb-color-text-link: #4b8eda; /* 链接颜色 */
  1218.  
  1219. /* 背景颜色 */
  1220. --ojb-color-bg-primary: #22272e; /* 主背景颜色 */
  1221. --ojb-color-bg-secondary: #2d333b; /* 次级背景颜色 */
  1222. --ojb-color-bg-disabled: #24292e; /* 禁用元素背景颜色 */
  1223.  
  1224. /* 边框颜色 */
  1225. --ojb-color-border-primary: #48535F; /* 主要边框颜色 */
  1226. --ojb-color-border-disabled: #404950; /* 禁用状态边框颜色 */
  1227. --ojb-color-border-dashed-hover: #03A9F4; /* 虚线边框悬浮颜色 */
  1228. --ojb-color-border-radio-checked: #326154; /* 选中的单选框边框颜色 */
  1229.  
  1230. /* 阴影颜色 */
  1231. --ojb-shadow-standard: 0px 0px 0.5px 0.5px #3A4048; /* 标准阴影 */
  1232. --ojb-shadow-menu-modal: 0px 0px 0px 4px #2d333b; /* 菜单和模态框阴影 */
  1233.  
  1234. /* 区域遮罩颜色 */
  1235. --ojb-overlay-background: repeating-linear-gradient(135deg, #49525f6e, #49525f6e 30px, #49525f29 0px, #49525f29 55px); /* 区域遮罩背景 */
  1236.  
  1237. /* 文字阴影 */
  1238. --ojb-text-shadow-icon: 1px 1px 0px #2d333b, 1px -1px 0px #2d333b, -1px -1px 0px #2d333b, -1px 1px 0px #2d333b; /* 图标文字阴影 */
  1239. }
  1240. /* 边框样式 */
  1241. :root {
  1242. /* 边框样式 */
  1243. --ojb-border-width: 1px; /* 边框宽度 */
  1244. --ojb-border-style-solid: solid; /* 实线样式 */
  1245. --ojb-border-style-dashed: dashed; /* 虚线样式 */
  1246. --ojb-border-radius-small: 4px; /* 小圆角 */
  1247. --ojb-border-radius-medium: 8px; /* 中圆角 */
  1248. --ojb-border-radius-large: 12px; /* 大圆角 */
  1249. /* 组合边框样式 */
  1250. --ojb-border-solid-primary: var(--ojb-border-width) var(--ojb-border-style-solid) var(--ojb-color-border-primary); /* 主要实线边框 */
  1251. --ojb-border-dashed: var(--ojb-border-width) var(--ojb-border-style-dashed) var(--ojb-color-border-primary); /* 主要虚线边框 */
  1252. --ojb-border-dashed-hover: var(--ojb-border-width) var(--ojb-border-style-dashed) var(--ojb-color-border-dashed-hover); /* 悬浮虚线边框 */
  1253. --ojb-border-solid-disabled: var(--ojb-border-width) var(--ojb-border-style-solid) var(--ojb-color-border-disabled); /* 禁用状态实线边框 */
  1254. }
  1255. `);
  1256.  
  1257. // OJBetter界面样式
  1258. GM_addStyle(`
  1259. /* 主要文字颜色 */
  1260. html[data-theme=dark] .alert-success, html[data-theme=dark] .alert-info, html[data-theme=dark] .alert-error,
  1261. html[data-theme=dark] .alert-warning, html[data-theme=dark] .markItUpEditor,
  1262. html[data-theme=dark] .translate-problem-statement, html[data-theme=dark] .OJBetter_setting_menu,
  1263. html[data-theme=dark] .help_tip .tip_text,
  1264. html[data-theme=dark] .OJBetter_setting_menu input, html[data-theme=dark] .OJBetter_setting_menu textarea,
  1265. html[data-theme=dark] #OJBetter_SubmitForm input, html[data-theme=dark] #OJBetter_SubmitForm textarea, html[data-theme=dark] #OJBetter_SubmitForm select,
  1266. html[data-theme=dark] #items-per-page, html[data-theme=dark] #pagBar,
  1267. html[data-theme=dark] .OJBetter_setting_sidebar li a:link,
  1268. html[data-theme=dark] .popup .content{
  1269. color: var(--ojb-color-text-primary);
  1270. }
  1271. /* 次要文字颜色 */
  1272. html[data-theme=dark] .ojb_btn:hover, html[data-theme=dark] .OJBetter_modal button, html[data-theme=dark] #OJBetter_statusBar,
  1273. html[data-theme=dark] #RunTestButton, html[data-theme=dark] #programTypeId, html[data-theme=dark] #addCustomTest,
  1274. html[data-theme=dark] #customTestBlock, html[data-theme=dark] .OJBetter_setting_list.alert_info{
  1275. color: var(--ojb-color-text-secondary);
  1276. }
  1277. /* 文字颜色3 */
  1278. html[data-theme=dark] .ojb_btn{
  1279. color: var(--ojb-color-text-tertiary);
  1280. }
  1281. /* 文字颜色 浅绿 */
  1282. html[data-theme=dark] #SubmitButton{
  1283. color: var(--ojb-color-text-success);
  1284. }
  1285. /* 禁止文字颜色 */
  1286. html[data-theme=dark] .ojb_btn[disabled]{
  1287. color: var(--ojb-color-text-disabled);
  1288. }
  1289. /* 主要背景层次 */
  1290. html[data-theme=dark] .OJBetter_setting_menu, html[data-theme=dark] .help_tip .tip_text, html[data-theme=dark] li#add_button:hover,
  1291. html[data-theme=dark] .ojb_btn:hover,
  1292. html[data-theme=dark] .OJBetter_setting_menu input, html[data-theme=dark] .OJBetter_setting_menu textarea,
  1293. html[data-theme=dark] #OJBetter_SubmitForm input,
  1294. html[data-theme=dark] .OJBetter_setting_menu input[type="checkbox"], html[data-theme=dark] .OJBetter_setting_menu input[type="checkbox"]:checked,
  1295. html[data-theme=dark] #OJBetter_SubmitForm textarea, html[data-theme=dark] #OJBetter_SubmitForm select,
  1296. html[data-theme=dark] .OJBetter_setting_sidebar li a.active, html[data-theme=dark] .OJBetter_setting_sidebar li,
  1297. html[data-theme=dark] .OJBetter_setting_menu::-webkit-scrollbar-track, html[data-theme=dark] .OJBetter_setting_content::-webkit-scrollbar-track,
  1298. html[data-theme=dark] .OJBetter_modal, html[data-theme=dark] .OJBetter_modal button:hover,
  1299. html[data-theme=dark] .popup .content,
  1300. html[data-theme=dark] .config_bar_list, html[data-theme=dark] #LSPLog,
  1301. html[data-theme=dark] .OJBetter_setting_menu .OJBetter_checkboxs,
  1302. html[data-theme=dark] .OJBetter_setting_menu .OJBetter_checkboxs input[type="checkbox"]::before,
  1303. html[data-theme=dark] .OJBetter_setting_menu a, html[data-theme=dark] .OJBetter_setting_menu .OJBetter_setting_list button:hover,
  1304. html[data-theme=dark] .OJBetter_setting_menu select{
  1305. background-color: var(--ojb-color-bg-primary);
  1306. background-image: none;
  1307. }
  1308. /* 次要背景层次 */
  1309. html[data-theme=dark] .ojb_btn,
  1310. html[data-theme=dark] .alert-success, html[data-theme=dark] .alert-info, html[data-theme=dark] .alert-error,
  1311. html[data-theme=dark] .alert-warning, html[data-theme=dark] .SumoSelect>.optWrapper>.options li.opt:hover,
  1312. html[data-theme=dark] .translate-problem-statement-panel,
  1313. html[data-theme=dark] .translate-problem-statement,
  1314. html[data-theme=dark] .OJBetter_setting_list,
  1315. html[data-theme=dark] .OJBetter_setting_menu hr,
  1316. html[data-theme=dark] .OJBetter_setting_sidebar li a,
  1317. html[data-theme=dark] .OJBetter_setting_menu::-webkit-scrollbar-thumb, html[data-theme=dark] .OJBetter_setting_content::-webkit-scrollbar-thumb,
  1318. html[data-theme=dark] .OJBetter_modal button, html[data-theme=dark] .test-for-popup pre,
  1319. html[data-theme=dark] .popup .content pre, html[data-theme=dark] .popup .content pre code,
  1320. html[data-theme=dark] ul.config_bar_ul::-webkit-scrollbar-thumb, html[data-theme=dark] #OJBetter_statusBar,
  1321. html[data-theme=dark] #RunTestButton, html[data-theme=dark] #programTypeId, html[data-theme=dark] .sampleDiv,
  1322. html[data-theme=dark] #addCustomTest, html[data-theme=dark] #LSPLog li:nth-child(odd),
  1323. html[data-theme=dark] .OJBetter_setting_menu .OJBetter_checkboxs input[type="checkbox"]:checked::before,
  1324. html[data-theme=dark] .config::before, html[data-theme=dark] .config li.tempConfig_add_button:hover,
  1325. html[data-theme=dark] .OJBetter_setting_menu details, html[data-theme=dark] #config_bar_menu,
  1326. html[data-theme=dark] .OJBetter_setting_menu .OJBetter_setting_list button,
  1327. html[data-theme=dark] .OJBetter_setting_menu .badge, html[data-theme=dark] #OJBetter_SubmitForm #SubmitButton{
  1328. background-color: var(--ojb-color-bg-secondary);
  1329. }
  1330. /* 禁止背景层次 */
  1331. html[data-theme=dark] .ojb_btn[disabled]{
  1332. background-color: var(--ojb-color-bg-disabled);
  1333. }
  1334. /* 实线边框颜色-圆角 */
  1335. html[data-theme=dark] .alert-success, html[data-theme=dark] .alert-info, html[data-theme=dark] .alert-error,
  1336. html[data-theme=dark] .alert-warning, html[data-theme=dark] .translate-problem-statement{
  1337. border: var(--ojb-border-solid-primary);
  1338. border-radius: 2px;
  1339. }
  1340. /* 实线边框颜色-无圆角 */
  1341. html[data-theme=dark] .ojb_btn,
  1342. html[data-theme=dark] .OJBetter_setting_list, html[data-theme=dark] .config_bar_list,
  1343. html[data-theme=dark] label.config_bar_ul_li_text,
  1344. html[data-theme=dark] .OJBetter_setting_sidebar li, html[data-theme=dark] .OJBetter_setting_menu select,
  1345. html[data-theme=dark] .translate-problem-statement-panel, html[data-theme=dark] .OJBetter_modal button, html[data-theme=dark] #OJBetter_SubmitForm select,
  1346. html[data-theme=dark] #OJBetter_editor, html[data-theme=dark] #OJBetter_statusBar,
  1347. html[data-theme=dark] #OJBetter_SubmitForm #RunTestButton, html[data-theme=dark] #programTypeId, html[data-theme=dark] #customTestBlock,
  1348. html[data-theme=dark] #OJBetter_SubmitForm #addCustomTest, html[data-theme=dark] #OJBetter_SubmitForm #SubmitButton,
  1349. html[data-theme=dark] .OJBetter_setting_menu input,
  1350. html[data-theme=dark] .OJBetter_setting_menu input[type="checkbox"], html[data-theme=dark] .OJBetter_setting_menu input[type="checkbox"]:checked,
  1351. html[data-theme=dark] .OJBetter_setting_menu textarea,
  1352. html[data-theme=dark] #OJBetter_SubmitForm input, html[data-theme=dark] #OJBetter_SubmitForm textarea,
  1353. html[data-theme=dark] #CompilerSetting select, html[data-theme=dark] #CompilerSetting textarea, html[data-theme=dark] #CompilerBox,
  1354. html[data-theme=dark] .OJBetter_setting_menu .OJBetter_checkboxs,
  1355. html[data-theme=dark] .help_tip .tip_text, html[data-theme=dark] .config::before,
  1356. html[data-theme=dark] #statePanel, html[data-theme=dark] .test-case, html[data-theme=dark] .OJBetter_setting_menu .badge{
  1357. border: var(--ojb-border-solid-primary);
  1358. }
  1359. html[data-theme=dark] #customTestBlock #customTests{
  1360. border-top: var(--ojb-border-solid-primary);
  1361. }
  1362. html[data-theme=dark] .OJBetter_setting_sidebar {
  1363. border-right: var(--ojb-border-solid-primary);
  1364. }
  1365. /* 实线边框-禁止 */
  1366. html[data-theme=dark] .ojb_btn[disabled]{
  1367. border: var(--ojb-border-solid-disabled);
  1368. }
  1369. /* 虚线边框 */
  1370. html[data-theme=dark] li#add_button,
  1371. html[data-theme=dark] .OJBetter_setting_menu_label_text{
  1372. border: var(--ojb-border-dashed);
  1373. }
  1374. /* 虚线边框-悬浮 */
  1375. html[data-theme=dark] li#add_button:hover{
  1376. border: var(--ojb-border-dashed-hover);
  1377. background-color: var(--ojb-color-bg-secondary);
  1378. color: var(--ojb-color-border-dashed-hover);
  1379. }
  1380. /* 无边框 */
  1381. html[data-theme=dark] .translate-problem-statement-panel .ojb_btn{
  1382. border: none;
  1383. }
  1384. /* 区域遮罩 */
  1385. html[data-theme=dark] .overlay::before {
  1386. background: var(--ojb-overlay-background);
  1387. color: var(--ojb-color-text-secondary);
  1388. text-shadow: 0px 0px 2px #000000;
  1389. }
  1390. /* 阴影 */
  1391. html[data-theme=dark] .translate-problem-statement-panel, html[data-theme=dark] .translate-problem-statement{
  1392. box-shadow: var(--ojb-shadow-standard);
  1393. }
  1394. /* 图标按钮状态样式 */
  1395. html[data-theme=dark] .ojb_btn_popover.success i:before, html[data-theme=dark] .ojb_btn_popover.success i {
  1396. color: var(--ojb-color-text-icon-success);
  1397. }
  1398. html[data-theme=dark] .ojb_btn_popover i:before {
  1399. text-shadow: var(--ojb-text-shadow-icon);
  1400. }
  1401. /* 其他样式 */
  1402. html[data-theme=dark] .OJBetter_setting_menu, html[data-theme=dark] .OJBetter_modal{
  1403. box-shadow: var(--ojb-shadow-menu-modal);
  1404. border: 1px solid var(--ojb-color-bg-secondary);
  1405. }
  1406. html[data-theme=dark] input[type="radio"]:checked+.OJBetter_setting_menu_label_text {
  1407. color: var(--ojb-color-text-primary);
  1408. border: 1px solid var(--ojb-color-border-radio-checked);
  1409. }
  1410. html[data-theme=dark] .alert{
  1411. text-shadow: none;
  1412. }
  1413. `);
  1414.  
  1415. // 网站界面样式
  1416. GM_addStyle(`
  1417. /* 文字颜色1 */
  1418. html[data-theme=dark] body, html[data-theme=dark] .float-container>#main-container,
  1419. html[data-theme=dark] .panel-default>.panel-heading, html[data-theme=dark] #header a,
  1420. html[data-theme=dark] .pagination>li>a, html[data-theme=dark] .pagination>li>span, html[data-theme=dark] .dropdown-menu,
  1421. html[data-theme=dark] .select2-container--bootstrap .select2-selection--single .select2-selection__rendered,
  1422. html[data-theme=dark] .ace-tm .ace_gutter, html[data-theme=dark] .translate-problem-statement-panel,
  1423. html[data-theme=dark] .select2-container--bootstrap .select2-results__option--highlighted[aria-selected],
  1424. html[data-theme=dark] .nav-pills>li.active>a, html[data-theme=dark] .user-unrated, html[data-theme=dark] #header .header-page li.is-active a,
  1425. html[data-theme=dark] .m-box_inner, html[data-theme=dark] .m-list-job_item, html[data-theme=dark] .a-btn_arrow,
  1426. html[data-theme=dark] #header, html[data-theme=dark] #header .header-sub_page li a,
  1427. html[data-theme=dark] .select2-container--default .select2-selection--single .select2-selection__rendered, html[data-theme=dark] .select2-results{
  1428. color: var(--ojb-color-text-primary) !important;
  1429. }
  1430. /* 文字颜色2 */
  1431. html[data-theme=dark] pre, html[data-theme=dark] .html2mdButton, html[data-theme=dark] .btn-default, html[data-theme=dark] .btn-pre,
  1432. html[data-theme=dark] small.contest-duration, html[data-theme=dark] .select2-container--bootstrap .select2-results__option,
  1433. html[data-theme=dark] #ace_settingsmenu, #kbshortcutmenu, html[data-theme=dark] code{
  1434. color: var(--ojb-color-text-secondary) !important;
  1435. }
  1436. /* 文字颜色3 */
  1437. html[data-theme=dark] input, html[data-theme=dark] #header .header-page li a:hover{
  1438. color: var(--ojb-color-text-secondary);
  1439. }
  1440. /* 文字颜色4 */
  1441. html[data-theme=dark] .katex{
  1442. color: var(--ojb-color-text-highlight) !important;
  1443. }
  1444. /* 链接颜色 */
  1445. html[data-theme=dark] a:link {
  1446. color: var(--ojb-color-text-link);
  1447. }
  1448. html[data-theme=dark] a:visited {
  1449. color: var(--ojb-color-text-secondary);
  1450. }
  1451. /* 按钮 */
  1452. html[data-theme=dark] input:hover, html[data-theme=dark] .btn-default:hover{
  1453. background-color: var(--ojb-color-bg-primary) !important;
  1454. }
  1455. /* 背景层次1 */
  1456. html[data-theme=dark] body, html[data-theme=dark] #main-div.float-container, html[data-theme=dark] pre,
  1457. html[data-theme=dark] .html2mdButton:hover, html[data-theme=dark] .pagination>.active>a, html[data-theme=dark] .ace-tm,
  1458. html[data-theme=dark] .dropdown-menu>li>a:hover, html[data-theme=dark] .dropdown-menu>li>a:focus,
  1459. html[data-theme=dark] .dropdown-menu .divider, html[data-theme=dark] .select2-container--bootstrap .select2-selection,
  1460. html[data-theme=dark] .ace-tm .ace_gutter-active-line, html[data-theme=dark] .select2-dropdown,
  1461. html[data-theme=dark] input, html[data-theme=dark] button, html[data-theme=dark] select, html[data-theme=dark] textarea,
  1462. html[data-theme=dark] code, html[data-theme=dark] #keyvisual .keyvisual-inner:before, html[data-theme=dark] .m-box_inner,
  1463. html[data-theme=dark] .m-list-job_item, html[data-theme=dark] .select2-container--default .select2-selection--single,
  1464. html[data-theme=dark] ol.linenums, html[data-theme=dark] li.L0, html[data-theme=dark] li.L1, html[data-theme=dark] li.L2,
  1465. html[data-theme=dark] li.L3, html[data-theme=dark] li.L4, html[data-theme=dark] li.L5, html[data-theme=dark] li.L6,
  1466. html[data-theme=dark] li.L7, html[data-theme=dark] li.L8, html[data-theme=dark] li.L9{
  1467. background-color: var(--ojb-color-bg-primary) !important;
  1468. }
  1469. /* 背景层次2 */
  1470. html[data-theme=dark] .float-container>#main-container, html[data-theme=dark] #contest-nav-tabs,
  1471. html[data-theme=dark] .btn-default, html[data-theme=dark] .html2mdButton,
  1472. html[data-theme=dark] .nav-tabs>li.active>a, html[data-theme=dark] .nav-tabs>li.active>a:hover, html[data-theme=dark] .nav-tabs>li.active>a:focus,
  1473. html[data-theme=dark] .nav>li>a:hover, html[data-theme=dark] .nav>li>a:focus, html[data-theme=dark] .panel,
  1474. html[data-theme=dark] .table-striped>tbody>tr:nth-of-type(odd), html[data-theme=dark] .insert-participant-box,
  1475. html[data-theme=dark] .btn-pre, html[data-theme=dark] .alert-success, html[data-theme=dark] .alert-info, html[data-theme=dark] .alert-danger,
  1476. html[data-theme=dark] .alert-warning, html[data-theme=dark] .panel-default>.panel-heading,
  1477. html[data-theme=dark] .pagination>li>a, html[data-theme=dark] .pagination>li>span, html[data-theme=dark] .dropdown-menu,
  1478. html[data-theme=dark] .ace-tm .ace_gutter, html[data-theme=dark] .select2-container--bootstrap .select2-results__option[aria-selected=true],
  1479. html[data-theme=dark] #ace_settingsmenu, #kbshortcutmenu, html[data-theme=dark] #header .header-inner,
  1480. html[data-theme=dark] ul#config_bar_ul::-webkit-scrollbar-thumb, html[data-theme=dark] .panel-info>.panel-heading,
  1481. html[data-theme=dark] .post-footer, html[data-theme=dark] .a-btn_arrow:before,
  1482. html[data-theme=dark] .table-hover>tbody>tr:hover,
  1483. html[data-theme=dark] li.L1, html[data-theme=dark] li.L3, html[data-theme=dark] li.L5, html[data-theme=dark] li.L7,
  1484. html[data-theme=dark] li.L9{
  1485. background-color: var(--ojb-color-bg-secondary) !important;
  1486. }
  1487. /* 实线边框颜色-圆角 */
  1488. html[data-theme=dark] input{
  1489. border: var(--ojb-border-solid-primary) !important;
  1490. border-radius: 2px;
  1491. }
  1492. /* 实线边框颜色-无圆角 */
  1493. html[data-theme=dark] .btn-default, html[data-theme=dark] .html2mdButton, html[data-theme=dark] .nav-tabs>li>a:hover,
  1494. html[data-theme=dark] .nav-tabs>li.active>a, html[data-theme=dark] .nav-tabs>li.active>a:hover,
  1495. html[data-theme=dark] .nav-tabs>li.active>a:focus, html[data-theme=dark] .btn-pre, html[data-theme=dark] .btn-pre:hover,
  1496. html[data-theme=dark] pre, html[data-theme=dark] .pagination>li>a, html[data-theme=dark] .pagination>li>span,
  1497. html[data-theme=dark] .table-bordered>thead>tr>th, html[data-theme=dark] .table-bordered>tbody>tr>th, html[data-theme=dark] .table-bordered>tfoot>tr>th,
  1498. html[data-theme=dark] .table-bordered>thead>tr>td, html[data-theme=dark] .table-bordered>tbody>tr>td, html[data-theme=dark] .table-bordered>tfoot>tr>td,
  1499. html[data-theme=dark] .panel, html[data-theme=dark] #editor, html[data-theme=dark] div#config_bar_list, html[data-theme=dark] label.config_bar_ul_li_text,
  1500. html[data-theme=dark] .select2-container--bootstrap .select2-selection, html[data-theme=dark] .select2-container--default .select2-selection--single{
  1501. border: var(--ojb-border-solid-primary) !important;
  1502. }
  1503. html[data-theme=dark] hr, html[data-theme=dark] .panel-footer,
  1504. html[data-theme=dark] .table>thead>tr>th, html[data-theme=dark] .table>tbody>tr>th, html[data-theme=dark] .table>tfoot>tr>th,
  1505. html[data-theme=dark] .table>thead>tr>td, html[data-theme=dark] .table>tbody>tr>td, html[data-theme=dark] .table>tfoot>tr>td{
  1506. border-top: var(--ojb-border-solid-primary) !important;
  1507. }
  1508. html[data-theme=dark] .nav-tabs, html[data-theme=dark] .panel-info>.panel-heading, html[data-theme=dark] .panel-default>.panel-heading,
  1509. html[data-theme=dark] .a-btn_arrow{
  1510. border-bottom: var(--ojb-border-solid-primary) !important;
  1511. }
  1512. html[data-theme=dark] .table>thead>tr>th{
  1513. border-bottom: 2px solid var(--ojb-color-border-primary) !important;
  1514. }
  1515. /* 双实线边框 */
  1516. html[data-theme=dark] #header .header-inner{
  1517. border-bottom: 5px double var(--ojb-color-border-primary) !important;
  1518. }
  1519. /* 阴影 */
  1520. html[data-theme=dark] .float-container>#main-container{
  1521. box-shadow: 0px 0px 10px 5px #fff0;
  1522. }
  1523. /* 图片-亮度 */
  1524. html[data-theme=dark] img{
  1525. opacity: .75;
  1526. }
  1527. /* 反转 */
  1528. html[data-theme=dark] .ace_content, html[data-theme=dark] #header .header-logo img, html[data-theme=dark] pre code{
  1529. filter: invert(1) hue-rotate(.5turn);
  1530. }
  1531. /* 区域遮罩 */
  1532. html[data-theme=dark] .overlay {
  1533. background: repeating-linear-gradient(135deg, #49525f6e, #49525f6e 30px, #49525f29 0px, #49525f29 55px);
  1534. color: #9099a3;
  1535. text-shadow: 0px 0px 2px #000000;
  1536. }
  1537. /* 其他样式 */
  1538. html[data-theme=dark] .nav-tabs>li.active>a, html[data-theme=dark] .nav-tabs>li.active>a:hover, html[data-theme=dark] .nav-tabs>li.active>a:focus{
  1539. border-bottom-color: transparent !important;
  1540. }
  1541. html[data-theme=dark] .collapsible-topic.collapsed .content .collapsible-topic-options:before{
  1542. background-image: linear-gradient(#22272e00, #22272e);
  1543. }
  1544. html[data-theme=dark] .alert{
  1545. text-shadow: none;
  1546. }
  1547. html[data-theme=dark] .m-box-news_post:before{
  1548. background: linear-gradient(0deg, #22272e 50%, rgba(255,255,255,0) 100%);
  1549. }
  1550. html[data-theme=dark] #header .header-sub_page li a:before, html[data-theme=dark] #header .header-page li a:before{
  1551. background-color: #9e9e9e !important;
  1552. }
  1553. html[data-theme=dark] .standings-score{
  1554. color: #2196f3;
  1555. }
  1556. html[data-theme=dark] pre code{
  1557. background-color: transparent !important;
  1558. }
  1559. html[data-theme=dark] #fixed-server-timer {
  1560. color: #000;
  1561. }
  1562. `);
  1563. })()
  1564.  
  1565. /**
  1566. * 黑暗模式额外的处理事件
  1567. */
  1568. function darkModeStyleAdjustment() {
  1569.  
  1570. }
  1571.  
  1572. /**
  1573. * 美化Pre代码块
  1574. */
  1575. async function beautifyPreBlocksWithMonaco() {
  1576. // 用于替换 <pre> 标签为 Monaco 编辑器的函数
  1577. function replacePreWithMonaco(preElement) {
  1578. const pre = $(preElement);
  1579. if (pre.hasClass('source-code-for-copy')) return; // 跳过复制块
  1580. const code = OJB_getCodeFromPre(pre.get(0));
  1581. if (!code) return;
  1582. const language = OJB_codeLangDetect(code);
  1583.  
  1584. // 创建一个用于 Monaco 编辑器的容器
  1585. const container = $('<div></div>');
  1586. const lineCount = code.split('\n').length; // 代码的行数
  1587.  
  1588. // 计算容器的高度
  1589. const calculateContainerHeight = (lineCount) => {
  1590. const lineHeight = 20; // 每行代码的高度
  1591. const minHeight = 100; // 最小高度
  1592. const maxHeight = 1000; // 最大高度
  1593. const dynamicHeight = lineCount * lineHeight;
  1594. return Math.min(Math.max(dynamicHeight, minHeight), maxHeight) + 'px';
  1595. };
  1596.  
  1597. // 应用样式
  1598. container.css({
  1599. height: calculateContainerHeight(lineCount),
  1600. width: '100%'
  1601. });
  1602. pre.replaceWith(container);
  1603.  
  1604. // 初始化 Monaco 编辑器
  1605. monaco.editor.create(container[0], {
  1606. value: code,
  1607. language: language,
  1608. readOnly: true,
  1609. tabSize: 4,
  1610. theme: OJBetter.basic.darkMode == "dark" ? "vs-dark" : "vs",
  1611. scrollbar: {
  1612. verticalScrollbarSize: 10,
  1613. horizontalScrollbarSize: 10,
  1614. alwaysConsumeMouseWheel: false
  1615. },
  1616. automaticLayout: true,
  1617. scrollBeyondLastLine: false
  1618. });
  1619. }
  1620. // 全局替换页面上所有的 <pre> 元素
  1621. $('pre').each(function () {
  1622. replacePreWithMonaco(this);
  1623. });
  1624. // 监听页面上的提交状态页面窗口的 <pre> 元素
  1625. if (OJBetter.typeOfPage.is_statePage) {
  1626. OJB_observeElement({
  1627. selector: '#facebox',
  1628. callback: (node) => {
  1629. // 如果 facebox 中存在 pre 元素,则替换它们
  1630. const preElements = $(node).find('pre');
  1631. preElements.each(function () {
  1632. replacePreWithMonaco(this);
  1633. });
  1634. }
  1635. });
  1636. }
  1637. }
  1638.  
  1639. // 样式
  1640. GM_addStyle(`
  1641. /*动画*/
  1642. @keyframes shake {
  1643. 0% { transform: translateX(-5px); }
  1644. 100% { transform: translateX(5px); }
  1645. }
  1646. @keyframes rotate {
  1647. from {
  1648. transform: rotate(0deg);
  1649. }
  1650.  
  1651. to {
  1652. transform: rotate(360deg);
  1653. }
  1654. }
  1655. @keyframes rippleout {
  1656. 0% {
  1657. box-shadow: 0 0 0 0 rgba(96, 98, 102, 0.2);
  1658. }
  1659.  
  1660. 100% {
  1661. box-shadow: 0 0 0 6px rgba(0, 0, 0, 0);
  1662. }
  1663. }
  1664. @keyframes bounce-in {
  1665. 20%,40%,60%,80%,from,to {
  1666. animation-timing-function: cubic-bezier(.215,.61,.355,1);
  1667. }
  1668.  
  1669. 0% {
  1670. opacity: 0;
  1671. transform: scale3d(.995,.995,.995);
  1672. }
  1673.  
  1674. 20% {
  1675. opacity: 1;
  1676. transform: scale3d(1.005,1.005,1.005);
  1677. }
  1678.  
  1679. 40% {
  1680. transform: scale3d(.998,.998,.998);
  1681. }
  1682.  
  1683. 60% {
  1684. transform: scale3d(1.002,1.002,1.002);
  1685. }
  1686.  
  1687. 80% {
  1688. transform: scale3d(.995,.995,.995);
  1689. }
  1690.  
  1691. to {
  1692. opacity: 1;
  1693. transform: scale3d(1,1,1);
  1694. }
  1695. }
  1696. /*iconfont图标*/
  1697. .iconfont {
  1698. font-family: "iconfont" !important;
  1699. font-size: 16px;
  1700. font-style: normal !important;
  1701. -webkit-font-smoothing: antialiased;
  1702. -moz-osx-font-smoothing: grayscale;
  1703. }
  1704. @font-face {
  1705. font-family: 'iconfont'; /* Project id 4284341 */
  1706. src: url('//aowuucdn.oss-accelerate.aliyuncs.com/iconfont/iconfont.woff2') format('woff2'),
  1707. url('//aowuucdn.oss-accelerate.aliyuncs.com/iconfont/iconfont.woff2.ttf') format('truetype');
  1708. }
  1709. html {
  1710. scroll-behavior: smooth;
  1711. }
  1712. :root {
  1713. --vp-font-family-base: "Chinese Quotes", "Inter var", "Inter", ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Helvetica, Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
  1714. }
  1715. span.mdViewContent {
  1716. white-space: pre-wrap;
  1717. }
  1718.  
  1719. /* dialog */
  1720. dialog {
  1721. margin: 0px;
  1722. }
  1723. dialog::backdrop {
  1724. background-color: rgba(0, 0, 0, 0.4);
  1725. }
  1726.  
  1727. /*题目页链接栏样式*/
  1728. #problemToolbar {
  1729. display: flex;
  1730. flex-wrap: wrap;
  1731. justify-content: flex-end;
  1732. overflow: auto;
  1733. height: 100%;
  1734. margin: 0.5em;
  1735. }
  1736.  
  1737. /*html2md面板*/
  1738. .html2md-panel {
  1739. display: flex;
  1740. justify-content: flex-end;
  1741. align-items: center;
  1742. }
  1743. .html2md-panel a {
  1744. text-decoration: none;
  1745. }
  1746. .html2md-panel > button {
  1747. margin: 5px;
  1748. }
  1749. .html2md-panel.is_simple {
  1750. position: absolute;
  1751. right: 2%;
  1752. }
  1753.  
  1754. /*通用按钮*/
  1755. .ojb_btn {
  1756. display: flex;
  1757. align-items: center;
  1758. justify-content: center;
  1759. cursor: pointer;
  1760. background-color: #ffffff;
  1761. color: #606266;
  1762. width: auto;
  1763. font-size: 13px;
  1764. border-radius: 0.3rem;
  1765. padding: 2px 5px;
  1766. margin: 0px 5px;
  1767. border: 1px solid #dcdfe6;
  1768. }
  1769. .ojb_btn[disabled] {
  1770. cursor: not-allowed !important;
  1771. color: rgb(168, 171, 178) !important;
  1772. border: 1px solid #e4e7ed;
  1773. background-color: #ffffff;
  1774. }
  1775. .ojb_btn:hover {
  1776. color: #409eff;
  1777. border-color: #409eff;
  1778. background-color: #f1f8ff;
  1779. z-index: 150;
  1780. }
  1781. .ojb_btn.primary {
  1782. color: #ffffff;
  1783. border: 1px solid #409eff;
  1784. background-color: #409eff;
  1785. }
  1786. .ojb_btn.primary:hover {
  1787. color: #ffffff;
  1788. border: 1px solid #79bbff;
  1789. background-color: #79bbff;
  1790. }
  1791. .ojb_btn.success {
  1792. color: #4caf50;
  1793. border: 1px solid #C8E6C9;
  1794. background-color: #f0f9eb;
  1795. }
  1796. .ojb_btn.warning {
  1797. color: #e6a23c;
  1798. border: 1px solid #f3d19e;
  1799. background-color: #fdf6ec;
  1800. }
  1801. .ojb_btn.error {
  1802. color: #f56c6c;
  1803. border: 1px solid #fab6b6;
  1804. background-color: #fef0f0;
  1805. }
  1806. .ojb_btn.enabled {
  1807. color: #42A5F5;
  1808. border: 1px solid #90CAF9;
  1809. background-color: #fafbff;
  1810. }
  1811. .ojb_btn.active {
  1812. animation: rippleout 0.5s ease-in-out;
  1813. }
  1814. a.ojb_btn {
  1815. text-decoration: none;
  1816. }
  1817. a.ojb_btn:link {
  1818. color: #606266;
  1819. }
  1820. a.ojb_btn span {
  1821. margin-left: 2px;
  1822. }
  1823. /*按钮图标和popover*/
  1824. .ojb_btn_popover {
  1825. display: flex;
  1826. justify-content: center;
  1827. position: relative;
  1828. outline: none;
  1829. appearance: none;
  1830. }
  1831. .ojb_btn_popover:hover span {
  1832. opacity: 1;
  1833. visibility: visible;
  1834. }
  1835. .ojb_btn_popover i:before {
  1836. position: absolute;
  1837. text-shadow: 1px 1px 0px #ffffff, 1px -1px 0px #ffffff, -1px -1px 0px #ffffff, -1px 1px 0px #ffffff;
  1838. }
  1839. .ojb_btn_popover span {
  1840. cursor: initial;
  1841. position: absolute;
  1842. left: 50%;
  1843. opacity: 0;
  1844. visibility: hidden;
  1845. padding: 4px 8px;
  1846. background-color: rgba(33, 33, 33, 0.8);
  1847. color: rgba(255, 255, 255, 0.9019607843);
  1848. font-size: 12px;
  1849. border-radius: 6px;
  1850. line-height: 1.6;
  1851. text-align: left;
  1852. white-space: nowrap;
  1853. transition: all 0.15s ease-in-out;
  1854. z-index: 999;
  1855. }
  1856. .ojb_btn_popover span:hover {
  1857. opacity: 0;
  1858. visibility: hidden;
  1859. }
  1860. .ojb_btn_popover.top:hover span {
  1861. transform: translate(-50%, 0);
  1862. }
  1863. .ojb_btn_popover.top span {
  1864. bottom: 100%;
  1865. transform: translate(-50%, -20%);
  1866. margin-bottom: 4px;
  1867. }
  1868. .ojb_btn_popover.top span:hover {
  1869. transform: translate(-50%, -20%);
  1870. }
  1871. .ojb_btn_popover.bottom:hover span {
  1872. transform: translate(-50%, 105%);
  1873. }
  1874. .ojb_btn_popover.bottom span {
  1875. bottom: -2%;
  1876. transform: translate(-50%, 100%);
  1877. margin-top: 4px;
  1878. }
  1879. .ojb_btn_popover.bottom span:hover {
  1880. transform: translate(-50%, 50%);
  1881. }
  1882. .ojb_btn_popover.loading i {
  1883. color: rgba(33, 33, 33, 0.1);
  1884. }
  1885. .ojb_btn_popover.loading i:before {
  1886. content: "\\e640";
  1887. color: rgb(168, 171, 178);
  1888. animation: rotate 2s cubic-bezier(0.65, 0.05, 0.36, 1) infinite;
  1889. }
  1890. .ojb_btn_popover.running i {
  1891. color: rgba(33, 33, 33, 0.1);
  1892. }
  1893. .ojb_btn_popover.running i:before {
  1894. content: "\\e600";
  1895. color: rgb(168, 171, 178);
  1896. animation: rotate 1s linear infinite;
  1897. }
  1898. .ojb_btn_popover.warning i {
  1899. color: rgba(230, 162, 61, 0.8);
  1900. }
  1901. .ojb_btn_popover.warning i:before {
  1902. content: "\\e68b";
  1903. font-size: 15px;
  1904. left: 10px;
  1905. bottom: 0%;
  1906. color: #ff9800;
  1907. }
  1908. .ojb_btn_popover.error i {
  1909. color: rgba(245, 108, 108, 0.8);
  1910. }
  1911. .ojb_btn_popover.error i:before {
  1912. content: "\\e651";
  1913. font-size: 15px;
  1914. left: 10px;
  1915. bottom: 0%;
  1916. color: #F44336;
  1917. }
  1918. .ojb_btn_popover.success i {
  1919. color: rgba(76, 175, 80, 0.9);
  1920. }
  1921. .ojb_btn_popover.success i:before {
  1922. content: "\\e61e";
  1923. font-size: 15px;
  1924. left: 10px;
  1925. bottom: 0%;
  1926. color: #4caf50;
  1927. }
  1928. .ojb_btn_popover.enabled i {
  1929. color: rgba(33, 150, 243, 0.6);
  1930. }
  1931. .ojb_btn_popover.enabled i:before {
  1932. content: "\\e6f4";
  1933. font-size: 15px;
  1934. left: 10px;
  1935. bottom: 0%;
  1936. color: #2196F3;
  1937. }
  1938. .ojb_btn_popover.redo i {
  1939. color: rgba(33, 33, 33, 0.1);
  1940. }
  1941. .ojb_btn_popover.redo i:before {
  1942. content: "\\e831";
  1943. color: #616161;
  1944. }
  1945. .ojb_btn_popover.reverse i {
  1946. transform: rotate(180deg);
  1947. }
  1948.  
  1949. /*translateDiv样式*/
  1950. .translateDiv .topText {
  1951. display: flex;
  1952. margin-left: 5px;
  1953. color: #9e9e9e;
  1954. font-size: 13px;
  1955. align-items: center;
  1956. }
  1957. .translateDiv .borderlessButton{
  1958. display: flex;
  1959. align-items: center;
  1960. margin: 2.5px 7px;
  1961. fill: #9E9E9E;
  1962. }
  1963. .translateDiv .borderlessButton:hover{
  1964. cursor: pointer;
  1965. fill: #059669;
  1966. }
  1967. .translateDiv.bounce-in {
  1968. animation: bounce-in 1s forwards;
  1969. }
  1970. html:not([data-theme='dark']) .translateDiv {
  1971. box-shadow: 0px 0px 0.5px 0.5px #defdf378;
  1972. }
  1973. .translate-problem-statement {
  1974. justify-items: start;
  1975. letter-spacing: 1.8px;
  1976. color: #059669;
  1977. background-color: #f9f9fa;
  1978. border: 1px solid #c5ebdf;
  1979. border-radius: 0rem 0rem 0.3rem 0.3rem;
  1980. padding: 5px;
  1981. margin: -5px 0px 6px 0px;
  1982. width: 100%;
  1983. box-sizing: border-box;
  1984. font-size: 13px;
  1985. }
  1986. .translate-problem-statement h3 {
  1987. font-size: 1.3em;
  1988. font-weight: 700;
  1989. }
  1990. .translate-problem-statement-panel{
  1991. display: flex;
  1992. justify-content: space-between;
  1993. background-color: #f9f9fa;
  1994. border: 1px solid #c5ebdf;
  1995. border-radius: 0.3rem;
  1996. margin: 4px 0px;
  1997. }
  1998. .translate-problem-statement-panel .ojb_btn {
  1999. background: none;
  2000. border: none;
  2001. color: #9e9e9e;
  2002. }
  2003. .translate-problem-statement-panel.error, .translate-problem-statement.error {
  2004. color: red;
  2005. border-color: red;
  2006. }
  2007. .translate-problem-statement a, .translate-problem-statement a:link {
  2008. color: #10b981;
  2009. font-weight: 600;
  2010. background: 0 0;
  2011. text-decoration: none;
  2012. }
  2013. .translate-problem-statement ol, .translate-problem-statement ul {
  2014. display: grid;
  2015. margin-inline-start: 0.8em;
  2016. margin-block-start: 0em;
  2017. margin: 0.5em 0 0 3em;
  2018. padding-inline-start: 0px;
  2019. }
  2020. .translate-problem-statement li {
  2021. display: list-item;
  2022. height: auto;
  2023. word-wrap: break-word;
  2024. }
  2025. .translate-problem-statement ol li {
  2026. list-style-type: auto;
  2027. }
  2028. .translate-problem-statement ul li {
  2029. list-style-type: disc;
  2030. }
  2031. .translate-problem-statement img {
  2032. max-width: 100.0%;
  2033. max-height: 100.0%;
  2034. }
  2035. #task-statement .translate-problem-statement .MathJax {
  2036. color: #059669!important;
  2037. }
  2038. .translate-problem-statement span.math {
  2039. margin: 0px 2.5px !important;
  2040. }
  2041. .translate-problem-statement a:hover {
  2042. background-color: #800;
  2043. color: #fff;
  2044. text-decoration: none;
  2045. }
  2046. .translate-problem-statement table {
  2047. border: 1px #ccc solid !important;
  2048. margin: 1.5em 0 !important;
  2049. color: #059669 !important;
  2050. }
  2051. .translate-problem-statement table thead th {
  2052. border: 1px #ccc solid !important;
  2053. color: #059669 !important;
  2054. }
  2055. .translate-problem-statement table td {
  2056. border-right: 1px solid #ccc;
  2057. border-top: 1px solid #ccc;
  2058. padding: 0.7143em 0.5em;
  2059. }
  2060. .translate-problem-statement table th {
  2061. padding: 0.7143em 0.5em;
  2062. }
  2063. .translate-problem-statement p:not(:first-child) {
  2064. margin: 1.5em 0 0;
  2065. }
  2066. .translate-problem-statement p {
  2067. line-height: 20px !important;
  2068. word-wrap: break-word;
  2069. font-size: 13px !important
  2070. }
  2071. .problem-statement p:last-child {
  2072. margin-bottom: 0px !important;
  2073. }
  2074.  
  2075. /*设置按钮*/
  2076. header .enter-or-register-box, header .languages {
  2077. position: absolute;
  2078. right: 170px;
  2079. }
  2080. .ojb_btn.OJBetter_setting {
  2081. float: right;
  2082. height: 30px;
  2083. background: #60a5fa;
  2084. color: white;
  2085. margin: 10px;
  2086. border: 1px solid #60a5fa;
  2087. }
  2088. .ojb_btn.OJBetter_setting.open {
  2089. background-color: #e6e6e6;
  2090. color: #727378;
  2091. cursor: not-allowed;
  2092. }
  2093.  
  2094. /*设置面板*/
  2095. .OJBetter_setting_menu {
  2096. box-shadow: 0px 0px 0px 4px #ffffff;
  2097. position: fixed;
  2098. top: 50%;
  2099. left: 50%;
  2100. width: 600px;
  2101. min-height: 600px;
  2102. transform: translate(-50%, -50%);
  2103. border-radius: 6px;
  2104. background-color: #f0f4f9;
  2105. border-collapse: collapse;
  2106. border: 1px solid #ffffff;
  2107. color: #697e91;
  2108. font-family: var(--vp-font-family-base);
  2109. padding: 10px 20px 20px 10px;
  2110. box-sizing: content-box;
  2111. }
  2112. .OJBetter_setting_menu h3 {
  2113. margin-top: 10px;
  2114. font-size: 1.4em;
  2115. font-weight: 700;
  2116. }
  2117. .OJBetter_setting_menu h4 {
  2118. margin: 15px 0px 10px 0px;
  2119. }
  2120. .OJBetter_setting_menu h4,.OJBetter_setting_menu h5 {
  2121. font-weight: 600;
  2122. }
  2123. .OJBetter_setting_menu hr {
  2124. border: none;
  2125. height: 1px;
  2126. background-color: #ccc;
  2127. margin: 10px 0;
  2128. }
  2129. .OJBetter_setting_menu details {
  2130. padding: 10px;
  2131. margin-bottom: 5px;
  2132. background-color: #ffffff;
  2133. border-bottom: 1px solid #c9c6c696;
  2134. border-radius: 8px;
  2135. }
  2136. .OJBetter_setting_menu .badge {
  2137. border-radius: 4px;
  2138. border: 1px solid #009688;
  2139. color: #009688;
  2140. background-color: #fff;
  2141. padding: 0.5px 4px;
  2142. margin-left: 5px;
  2143. margin-right: auto;
  2144. line-height: initial;
  2145. font-weight: initial;
  2146. }
  2147. .OJBetter_setting_menu .missing {
  2148. box-shadow: inset 0px 0px 1px 1px red;
  2149. }
  2150. /* 页面切换 */
  2151. .OJBetter_setting_menu .settings-page {
  2152. display: none;
  2153. }
  2154. .OJBetter_setting_menu .settings-page.active {
  2155. display: block;
  2156. }
  2157. .OJBetter_setting_container {
  2158. display: flex;
  2159. }
  2160. .OJBetter_setting_sidebar {
  2161. flex: 0 0 auto;
  2162. min-width: 110px;
  2163. padding: 6px 10px 6px 6px;
  2164. margin: 20px 0px;
  2165. border-right: 1px solid #d4d8e9;
  2166. }
  2167. .OJBetter_setting_content {
  2168. flex-grow: 1;
  2169. margin: 20px 0px 0px 12px;
  2170. padding-right: 10px;
  2171. max-height: 580px;
  2172. overflow-y: auto;
  2173. box-sizing: border-box;
  2174. }
  2175. .OJBetter_setting_sidebar h3 {
  2176. margin-top: 0;
  2177. }
  2178. .OJBetter_setting_sidebar hr {
  2179. margin-top: 10px;
  2180. margin-bottom: 10px;
  2181. border: none;
  2182. border-top: 1px solid #DADCE0;
  2183. }
  2184. .OJBetter_setting_sidebar ul {
  2185. list-style-type: none;
  2186. margin: 0;
  2187. padding: 0;
  2188. }
  2189. .OJBetter_setting_sidebar li {
  2190. margin: 5px 0px;
  2191. background-color: #ffffff;
  2192. border: 1px solid #d4d8e9;
  2193. border-radius: 4px;
  2194. font-size: 16px;
  2195. }
  2196. .OJBetter_setting_sidebar li a {
  2197. text-decoration: none;
  2198. display: flex;
  2199. width: 100%;
  2200. font-size: 16px;
  2201. color: gray;
  2202. background-color: #ffffff;
  2203. border: none;
  2204. letter-spacing: 2px;
  2205. padding: 7px;
  2206. margin: 0px;
  2207. border-radius: 4px;
  2208. align-items: center;
  2209. -webkit-box-sizing: border-box;
  2210. -moz-box-sizing: border-box;
  2211. box-sizing: border-box;
  2212. }
  2213. .OJBetter_setting_sidebar li a.active {
  2214. background-color: #eceff1c7;
  2215. }
  2216. /* 链接样式 */
  2217. .OJBetter_setting_menu a {
  2218. font-size: 13px;
  2219. color: #009688;
  2220. background-color: #E0F2F1;
  2221. border: 1px solid #009688;
  2222. border-radius: 4px;
  2223. padding: 0px 5px;
  2224. margin: 0px 5px;
  2225. text-decoration: none;
  2226. }
  2227. /* 下拉选择框 */
  2228. .OJBetter_setting_menu select {
  2229. appearance: none;
  2230. padding: 5px 10px;
  2231. margin: -5px 0px;
  2232. border-radius: 6px;
  2233. border-style: solid;
  2234. border: 1px solid #ced4da;
  2235. color: #009688;
  2236. background: #ffffff;
  2237. font-size: 15px;
  2238. }
  2239. .OJBetter_setting_menu select:focus-visible {
  2240. outline: none;
  2241. }
  2242. .OJBetter_setting_menu select option:disabled {
  2243. color: #EEEEEE;
  2244. }
  2245. /* 数值输入框 */
  2246. .OJBetter_setting_menu input[type="number"] {
  2247. width: 40px;
  2248. color: #009688;
  2249. font-size: 15px;
  2250. appearance: none;
  2251. padding: 5px 10px;
  2252. margin: -5px 3px;
  2253. border-radius: 6px;
  2254. border-style: solid;
  2255. border: 1px solid #ced4da;
  2256. }
  2257. .OJBetter_setting_menu input[type="number"]:focus-visible {
  2258. outline: none;
  2259. }
  2260. .OJBetter_setting_menu input[type="number"]::-webkit-inner-spin-button,
  2261. .OJBetter_setting_menu input[type="number"]::-webkit-outer-spin-button {
  2262. -webkit-appearance: none;
  2263. margin: 0;
  2264. }
  2265. /*设置面板-滚动条*/
  2266. .OJBetter_setting_menu::-webkit-scrollbar, .OJBetter_setting_content::-webkit-scrollbar,
  2267. .OJBetter_modal .content::-webkit-scrollbar {
  2268. width: 5px;
  2269. height: 7px;
  2270. background-color: #aaa;
  2271. }
  2272. .OJBetter_setting_menu::-webkit-scrollbar-thumb, .OJBetter_setting_content::-webkit-scrollbar-thumb,
  2273. .OJBetter_modal .content::-webkit-scrollbar-thumb {
  2274. background-clip: padding-box;
  2275. background-color: #d7d9e4;
  2276. }
  2277. .OJBetter_setting_menu::-webkit-scrollbar-track, .OJBetter_setting_content::-webkit-scrollbar-track,
  2278. .OJBetter_modal .content::-webkit-scrollbar-track {
  2279. background-color: #f1f1f1;
  2280. }
  2281. /*设置面板-关闭按钮*/
  2282. .OJBetter_setting_menu .tool-box {
  2283. position: absolute;
  2284. width: 20px;
  2285. height: 20px;
  2286. top: 3px;
  2287. right: 3px;
  2288. }
  2289. .OJBetter_setting_menu .btn-close {
  2290. width: 20px;
  2291. height: 20px;
  2292. border-radius: 50%;
  2293. border: none;
  2294. margin: 0px;
  2295. padding: 0px;
  2296. background-color: #ff000080;
  2297. transition: .15s ease all;
  2298. box-sizing: border-box;
  2299. text-align: center;
  2300. color: transparent;
  2301. }
  2302. .OJBetter_setting_menu .iconfont {
  2303. font-size: 10px;
  2304. font-weight: bolder;
  2305. }
  2306. .OJBetter_setting_menu .btn-close:hover {
  2307. color: #ffffff;
  2308. background-color: #ff0000cc;
  2309. box-shadow: 0 5px 5px 0 #00000026;
  2310. }
  2311. .OJBetter_setting_menu .btn-close:active {
  2312. color: #ffffffde;
  2313. background-color: #ff000080;
  2314. }
  2315. /*设置面板-checkbox*/
  2316. .OJBetter_setting_menu input[type=checkbox]:focus {
  2317. outline: 0px;
  2318. }
  2319. .OJBetter_setting_menu .OJBetter_setting_list input[type="checkbox"] {
  2320. margin: 0px;
  2321. appearance: none;
  2322. -webkit-appearance: none;
  2323. width: 40px;
  2324. height: 20px;
  2325. border: 1.5px solid #D7CCC8;
  2326. padding: 0px !important;
  2327. border-radius: 20px;
  2328. background: #efebe978;
  2329. position: relative;
  2330. box-sizing: border-box;
  2331. }
  2332. .OJBetter_setting_menu .OJBetter_setting_list input[type="checkbox"]::before {
  2333. content: "";
  2334. width: 17px;
  2335. height: 17px;
  2336. background: #D7CCC8;
  2337. border: 1.5px solid #BCAAA4;
  2338. border-radius: 50%;
  2339. position: absolute;
  2340. top: 0;
  2341. left: 0;
  2342. transform: translate(2%, 2%);
  2343. transition: all 0.3s ease-in-out;
  2344. box-sizing: border-box;
  2345. }
  2346. .OJBetter_setting_menu .OJBetter_setting_list input[type="checkbox"]::after {
  2347. content: url("data:image/svg+xml,%3Csvg xmlns='://www.w3.org/2000/svg' width='23' height='23' viewBox='0 0 23 23' fill='none'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M6.55021 5.84315L17.1568 16.4498L16.4497 17.1569L5.84311 6.55026L6.55021 5.84315Z' fill='%23EA0707' fill-opacity='0.89'/%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M17.1567 6.55021L6.55012 17.1568L5.84302 16.4497L16.4496 5.84311L17.1567 6.55021Z' fill='%23EA0707' fill-opacity='0.89'/%3E%3C/svg%3E");
  2348. position: absolute;
  2349. top: 0;
  2350. left: 24px;
  2351. }
  2352. .OJBetter_setting_menu .OJBetter_setting_list input[type="checkbox"]:checked {
  2353. border: 1.5px solid #C5CAE9;
  2354. background: #E8EAF6;
  2355. }
  2356. .OJBetter_setting_menu .OJBetter_setting_list input[type="checkbox"]:checked::before {
  2357. background: #C5CAE9;
  2358. border: 1.5px solid #7986CB;
  2359. transform: translate(122%, 2%);
  2360. transition: all 0.3s ease-in-out;
  2361. }
  2362. .OJBetter_setting_menu .OJBetter_setting_list input[type="checkbox"]:checked::after {
  2363. content: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 15 13' fill='none'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M14.8185 0.114533C15.0314 0.290403 15.0614 0.605559 14.8855 0.818454L5.00187 12.5L0.113036 6.81663C-0.0618274 6.60291 -0.0303263 6.2879 0.183396 6.11304C0.397119 5.93817 0.71213 5.96967 0.886994 6.18339L5.00187 11L14.1145 0.181573C14.2904 -0.0313222 14.6056 -0.0613371 14.8185 0.114533Z' fill='%2303A9F4' fill-opacity='0.9'/%3E%3C/svg%3E");
  2364. position: absolute;
  2365. top: 1.5px;
  2366. left: 4.5px;
  2367. }
  2368. .OJBetter_setting_menu .OJBetter_setting_list button {
  2369. cursor: pointer;
  2370. color: #7986cb;
  2371. background-color: #e8eaf6;
  2372. border: 1px solid #7986cb;
  2373. border-radius: 6px;
  2374. width: 100px;
  2375. margin: -5px 2px;
  2376. padding: 5px 10px;
  2377. }
  2378. .OJBetter_setting_menu .OJBetter_setting_list button:hover {
  2379. color: #e8eaf6;
  2380. background-color: #7986cb;
  2381. border: 1px solid #7986cb;
  2382. }
  2383. .OJBetter_setting_menu label, #darkMode_span, #loaded_span {
  2384. font-size: 16px;
  2385. }
  2386. .OJBetter_setting_list {
  2387. display: flex;
  2388. flex-wrap: wrap;
  2389. align-items: center;
  2390. padding: 10px;
  2391. margin: 5px 0px;
  2392. background-color: #ffffff;
  2393. border: 1px solid #c9c6c642;
  2394. border-bottom-color: #c9c6c696;
  2395. border-radius: 8px;
  2396. justify-content: space-between;
  2397. }
  2398. .OJBetter_setting_list.alert_danger {
  2399. color: #F44336;
  2400. background-color: #FFEBEE;
  2401. border: 1px solid #F44336;
  2402. margin: 10px 0px;
  2403. }
  2404. .OJBetter_setting_list.alert_warn {
  2405. color: #E65100;
  2406. background-color: #FFF3E0;
  2407. border: 1px solid #FF9800;
  2408. margin: 10px 0px;
  2409. }
  2410. .OJBetter_setting_list.alert_tip {
  2411. color: #009688;
  2412. background-color: #E0F2F1;
  2413. border: 1px solid #009688;
  2414. margin: 10px 0px;
  2415. }
  2416. .OJBetter_setting_list.alert_info {
  2417. color: #ffffff;
  2418. background-color: #009688;
  2419. margin: 10px 0px;
  2420. box-shadow: rgba(0, 0, 0, 0.06) 0px 2px 4px 0px inset;
  2421. }
  2422. .OJBetter_setting_list p:not(:last-child) {
  2423. margin-bottom: 10px;
  2424. }
  2425. .OJBetter_setting_list p:not(:first-child) {
  2426. margin-top: 10px;
  2427. }
  2428. /*设置面板-checkboxs*/
  2429. .OJBetter_setting_menu .OJBetter_checkboxs {
  2430. flex-basis: 100%;
  2431. display: flex;
  2432. padding: 8px;
  2433. margin: 10px 0px 0px 0px;
  2434. border-bottom: 1px solid #c9c6c696;
  2435. border-radius: 8px;
  2436. border: 1px solid #c5cae9;
  2437. background-color: #f0f8ff;
  2438. }
  2439. .OJBetter_setting_menu .OJBetter_checkboxs label {
  2440. font-size: 13px;
  2441. margin: 0px 6px 0px 3px;
  2442. }
  2443. .OJBetter_setting_menu .OJBetter_checkboxs input[type=checkbox]:checked+label{
  2444. color: #7986cb;
  2445. }
  2446. .OJBetter_setting_menu .OJBetter_checkboxs input[type="checkbox"] {
  2447. border: none;
  2448. width: 16px;
  2449. height: 16px;
  2450. }
  2451. .OJBetter_setting_menu .OJBetter_checkboxs input[type="checkbox"]::before{
  2452. background: #ffffff;
  2453. transform: none;
  2454. width: 16px;
  2455. height: 16px;
  2456. }
  2457. .OJBetter_setting_menu .OJBetter_checkboxs input[type="checkbox"]:checked {
  2458. background: none;
  2459. border: none;
  2460. }
  2461. .OJBetter_setting_menu .OJBetter_checkboxs input[type="checkbox"]:checked::before {
  2462. border: 1.5px solid #95a2de;
  2463. background: #e8eaf6;
  2464. transform: none;
  2465. }
  2466. .OJBetter_setting_menu .OJBetter_checkboxs input[type="checkbox"]:checked::after {
  2467. content: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='9' height='9' viewBox='0 0 15 13' fill='none'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M14.8185 0.114533C15.0314 0.290403 15.0614 0.605559 14.8855 0.818454L5.00187 12.5L0.113036 6.81663C-0.0618274 6.60291 -0.0303263 6.2879 0.183396 6.11304C0.397119 5.93817 0.71213 5.96967 0.886994 6.18339L5.00187 11L14.1145 0.181573C14.2904 -0.0313222 14.6056 -0.0613371 14.8185 0.114533Z' fill='%2303A9F4' fill-opacity='0.9'/%3E%3C/svg%3E");
  2468. top: 0px;
  2469. left: 3.5px;
  2470. }
  2471. .OJBetter_setting_menu .OJBetter_checkboxs input[type="checkbox"]:disabled+label {
  2472. color: #BDBDBD;
  2473. }
  2474. /*设置面板-radio*/
  2475. .OJBetter_setting_menu label {
  2476. display: block;
  2477. font-weight: initial;
  2478. list-style-type: none;
  2479. padding-inline-start: 0px;
  2480. overflow-x: auto;
  2481. max-width: 100%;
  2482. margin: 3px 0px;
  2483. overflow-x: visible;
  2484. }
  2485. .OJBetter_setting_menu_label_text {
  2486. display: flex;
  2487. border: 1px dashed #00aeeccc;
  2488. height: 35px;
  2489. width: 100%;
  2490. color: #6e6e6e;
  2491. font-weight: 300;
  2492. font-size: 14px;
  2493. letter-spacing: 2px;
  2494. padding: 7px;
  2495. margin-bottom: 4px;
  2496. align-items: center;
  2497. -webkit-box-sizing: border-box;
  2498. -moz-box-sizing: border-box;
  2499. box-sizing: border-box;
  2500. }
  2501. input[type="radio"]:checked+.OJBetter_setting_menu_label_text {
  2502. background: #41e49930;
  2503. border: 1px solid green;
  2504. color: green;
  2505. text-shadow: 0px 0px 0.5px green;
  2506. }
  2507. input[type="radio"]:disabled+.OJBetter_setting_menu_label_text {
  2508. background: #fafafa00;
  2509. border: 1px solid #e0e0e07a;
  2510. color: #e0e0e0;
  2511. }
  2512. .OJBetter_setting_menu label input[type="radio"], .OJBetter_contextmenu label input[type="radio"]{
  2513. appearance: none;
  2514. list-style: none;
  2515. padding: 0px !important;
  2516. margin: 0px;
  2517. clip: rect(0 0 0 0);
  2518. -webkit-clip-path: inset(100%);
  2519. clip-path: inset(100%);
  2520. height: 1px;
  2521. overflow: hidden;
  2522. position: absolute;
  2523. white-space: nowrap;
  2524. width: 1px;
  2525. }
  2526. /*设置面板-文本输入框*/
  2527. .OJBetter_setting_menu input[type="text"] {
  2528. display: block;
  2529. height: 25px !important;
  2530. width: 100%;
  2531. background-color: #ffffff;
  2532. color: #727378;
  2533. font-size: 12px;
  2534. border-radius: 0.3rem;
  2535. padding: 1px 5px !important;
  2536. box-sizing: border-box;
  2537. margin: 5px 0px 5px 0px;
  2538. border: 1px solid #00aeeccc;
  2539. box-shadow: 0 0 1px #0000004d;
  2540. }
  2541. .OJBetter_setting_menu .OJBetter_setting_list input[type="text"] {
  2542. margin-left: 5px;
  2543. }
  2544. .OJBetter_setting_menu input[type="text"]:focus-visible{
  2545. border-style: solid;
  2546. border-color: #3f51b5;
  2547. outline: none;
  2548. }
  2549. .OJBetter_setting_menu_config_box {
  2550. width: 100%;
  2551. display: grid;
  2552. margin-top: 5px;
  2553. -webkit-box-sizing: border-box;
  2554. -moz-box-sizing: border-box;
  2555. box-sizing: border-box;
  2556. }
  2557. .OJBetter_setting_menu input::placeholder {
  2558. color: #727378;
  2559. }
  2560. .OJBetter_setting_menu input.no_default::placeholder{
  2561. color: #BDBDBD;
  2562. }
  2563. .OJBetter_setting_menu input.is_null::placeholder{
  2564. color: red;
  2565. border-width: 1.5px;
  2566. }
  2567. .OJBetter_setting_menu input.is_null{
  2568. border-color: red;
  2569. }
  2570. .OJBetter_setting_menu textarea {
  2571. resize: vertical;
  2572. display: block;
  2573. width: 100%;
  2574. height: 60px;
  2575. background-color: #ffffff;
  2576. color: #727378;
  2577. font-size: 12px;
  2578. padding: 1px 5px !important;
  2579. box-sizing: border-box;
  2580. margin: 5px 0px 5px 0px;
  2581. border: 1px solid #00aeeccc;
  2582. box-shadow: 0 0 1px #0000004d;
  2583. }
  2584. .OJBetter_setting_menu textarea:focus-visible{
  2585. border-style: solid;
  2586. border-color: #3f51b5;
  2587. outline: none;
  2588. }
  2589. .OJBetter_setting_menu textarea::placeholder{
  2590. color: #BDBDBD;
  2591. font-size: 14px;
  2592. }
  2593. .OJBetter_setting_menu #tempConfig_save {
  2594. cursor: pointer;
  2595. display: inline-flex;
  2596. padding: 5px;
  2597. background-color: #1aa06d;
  2598. color: #ffffff;
  2599. font-size: 14px;
  2600. line-height: 1.5rem;
  2601. font-weight: 500;
  2602. justify-content: center;
  2603. width: 100%;
  2604. border-radius: 0.375rem;
  2605. border: none;
  2606. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  2607. margin-top: 20px
  2608. }
  2609. .OJBetter_setting_menu button#debug_button.debug_button {
  2610. width: 18%;
  2611. }
  2612. .OJBetter_setting_menu span.tip {
  2613. color: #999;
  2614. font-size: 12px;
  2615. font-weight: 500;
  2616. padding: 5px 0px;
  2617. }
  2618. /*设置面板-tip*/
  2619. .help_tip {
  2620. margin-right: auto;
  2621. }
  2622. span.input_label {
  2623. font-size: 14px;
  2624. }
  2625. .help_tip .tip_text {
  2626. display: none;
  2627. position: absolute;
  2628. color: #697e91;
  2629. font-weight: 400;
  2630. font-size: 14px;
  2631. letter-spacing: 0px;
  2632. background-color: #ffffff;
  2633. padding: 10px;
  2634. margin: 5px 0px;
  2635. border-radius: 4px;
  2636. border: 1px solid #e4e7ed;
  2637. box-shadow: 0px 0px 12px rgba(0, 0, 0, .12);
  2638. z-index: 100;
  2639. }
  2640. .help_tip .tip_text p {
  2641. margin-bottom: 5px;
  2642. }
  2643. .help_tip .tip_text:before {
  2644. content: "";
  2645. position: absolute;
  2646. top: -20px;
  2647. right: -10px;
  2648. bottom: -10px;
  2649. left: -10px;
  2650. z-index: -1;
  2651. }
  2652. .help-icon {
  2653. cursor: help;
  2654. width: 15px;
  2655. color: #b4b9d4;
  2656. margin-left: 5px;
  2657. margin-top: 3px;
  2658. }
  2659. .OJBetter_setting_menu .OJBetter_setting_menu_label_text .help_tip .help-icon {
  2660. color: #7fbeb2;
  2661. }
  2662. .help_tip .help-icon:hover + .tip_text, .help_tip .tip_text:hover {
  2663. display: block;
  2664. cursor: help;
  2665. width: 250px;
  2666. }
  2667. /* 版本信息 */
  2668. .OJBetter_setting_menu .versionInfo{
  2669. display: grid;
  2670. justify-items: center;
  2671. font-size: 16px;
  2672. padding: 10px;
  2673. }
  2674. .OJBetter_setting_menu .versionInfo>* {
  2675. margin: 10px 0px;
  2676. }
  2677.  
  2678. /* 配置管理面板 */
  2679. .config{
  2680. width: 100%;
  2681. margin: 10px 0px;
  2682. }
  2683. .config li.tempConfig_add_button {
  2684. cursor: pointer;
  2685. height: 40px;
  2686. border: 1px dashed #BDBDBD;
  2687. border-radius: 8px;
  2688. background-color: #fcfbfb36;
  2689. color: #bdbdbd;
  2690. font-size: 14px;
  2691. align-items: center;
  2692. justify-content: center;
  2693. }
  2694. .config li.tempConfig_add_button:hover {
  2695. border: 1px dashed #03A9F4;
  2696. background-color: #d7f0fb8c;
  2697. color: #03A9F4;
  2698. }
  2699. .config .config_bar_list {
  2700. display: flex;
  2701. width: 100%;
  2702. padding-bottom: 2px;
  2703. border: 1px solid #c5cae9;
  2704. background-color: #f0f8ff;
  2705. box-sizing: border-box;
  2706. border-radius: 0px 0px 8px 8px;
  2707. }
  2708. .config .config_bar_list input[type="radio"] {
  2709. appearance: none;
  2710. width: 0;
  2711. height: 0;
  2712. overflow: hidden;
  2713. }
  2714. .config .config_bar_list input[type="radio"] {
  2715. margin: 0px;
  2716. }
  2717. .config .config_bar_list input[type=radio]:focus {
  2718. outline: 0px;
  2719. }
  2720. .config .config_bar_ul_li_text {
  2721. display: flex;
  2722. align-items: center;
  2723. justify-content: center;
  2724. max-width: 100%;
  2725. height: 40px;
  2726. overflow-x: auto;
  2727. font-size: 14px;
  2728. font-weight: 400;
  2729. margin: 0px 4px;
  2730. padding: 3px;
  2731. border: 1px solid #dedede;
  2732. border-radius: 10px;
  2733. box-shadow: 0px 2px 4px 0px rgba(0,0,0,.05);
  2734. box-sizing: border-box;
  2735. }
  2736. .config .config_bar_ul li button {
  2737. background-color: #e6e6e6;
  2738. color: #727378;
  2739. height: 23px;
  2740. font-size: 14px;
  2741. border-radius: 0.3rem;
  2742. padding: 1px 5px;
  2743. margin: 5px;
  2744. border: none;
  2745. box-shadow: 0 0 1px #0000004d;
  2746. }
  2747. .config .config_bar_ul {
  2748. display: flex;
  2749. align-items: center;
  2750. list-style-type: none;
  2751. padding-inline-start: 0px;
  2752. overflow-x: auto;
  2753. max-width: 100%;
  2754. margin: 0px;
  2755. padding: 5px;
  2756. }
  2757. .config .config_bar_ul li {
  2758. width: 80px;
  2759. display: grid;
  2760. margin: 4px 4px;
  2761. min-width: 100px;
  2762. box-sizing: border-box;
  2763. }
  2764. .config .config_bar_ul_li_text:hover {
  2765. background-color: #eae4dc24;
  2766. }
  2767. input[type="radio"]:checked + .config_bar_ul_li_text {
  2768. background: #41b3e430;
  2769. border: 1px solid #5e7ce0;
  2770. color: #5e7ce0;
  2771. }
  2772. .config .config_bar_ul::-webkit-scrollbar {
  2773. width: 5px;
  2774. height: 4px;
  2775. }
  2776. .config .config_bar_ul::-webkit-scrollbar-thumb {
  2777. background-clip: padding-box;
  2778. background-color: #d7d9e4;
  2779. border-radius: 8px;
  2780. }
  2781. .config .config_bar_ul::-webkit-scrollbar-button:start:decrement {
  2782. width: 4px;
  2783. background-color: transparent;
  2784. }
  2785. .config .config_bar_ul::-webkit-scrollbar-button:end:increment {
  2786. width: 4px;
  2787. background-color: transparent;
  2788. }
  2789. .config .config_bar_ul::-webkit-scrollbar-track {
  2790. border-radius: 5px;
  2791. }
  2792. .config .config_bar_ul_li_text::-webkit-scrollbar {
  2793. width: 5px;
  2794. height: 7px;
  2795. background-color: #aaa;
  2796. }
  2797. .config .config_bar_ul_li_text::-webkit-scrollbar-thumb {
  2798. background-clip: padding-box;
  2799. background-color: #d7d9e4;
  2800. }
  2801. .config .config_bar_ul_li_text::-webkit-scrollbar-track {
  2802. background-color: #f1f1f1;
  2803. }
  2804. .config .config_bar_list_add_div {
  2805. display: flex;
  2806. height: 40px;
  2807. margin: 4px 2px;
  2808. }
  2809.  
  2810. /* 修改菜单 */
  2811. #config_bar_menu {
  2812. z-index: 400;
  2813. position: fixed;
  2814. width: 60px;
  2815. background: #ffffff;
  2816. box-shadow: 1px 1px 4px 0px #0000004d;
  2817. border: 0px solid rgba(0,0,0,0.04);
  2818. border-radius: 4px;
  2819. padding: 8px 0;
  2820. }
  2821. .config_bar_menu_item {
  2822. cursor: pointer;
  2823. padding: 2px 6px;
  2824. display: flex;
  2825. justify-content: center;
  2826. align-items: center;
  2827. height: 32px;
  2828. font-size: 14px;
  2829. font-weight: 500;
  2830. box-shadow: inset 0px 0px 0px 0px #8bb2d9;
  2831. }
  2832. #config_bar_menu_edit:hover {
  2833. background-color: #00aeec;
  2834. color: white;
  2835. }
  2836. #config_bar_menu_delete:hover {
  2837. background-color: #FF5722;
  2838. color: white;
  2839. }
  2840.  
  2841. /* 配置编辑页面 */
  2842. #config_edit_menu {
  2843. z-index: 300;
  2844. width: 450px;
  2845. }
  2846.  
  2847. /* 黑暗模式选项按钮 */
  2848. .dark-mode-selection {
  2849. display: flex;
  2850. justify-content: center;
  2851. align-items: center;
  2852. max-width: 350px;
  2853. -webkit-user-select: none;
  2854. -moz-user-select: none;
  2855. -ms-user-select: none;
  2856. user-select: none;
  2857. }
  2858. .dark-mode-selection label {
  2859. margin: 8px 0px 8px 8px;
  2860. }
  2861. .dark-mode-selection > * {
  2862. margin: 6px;
  2863. }
  2864. .dark-mode-selection .OJBetter_setting_menu_label_text {
  2865. border-radius: 8px;
  2866. margin-bottom: 0px;
  2867. }
  2868.  
  2869. /*确认弹窗*/
  2870. .OJBetter_modal {
  2871. z-index: 600;
  2872. display: grid;
  2873. position: fixed;
  2874. top: 50%;
  2875. left: 50%;
  2876. transform: translate(-50%, -50%);
  2877. font-size: 12px;
  2878. font-family: var(--vp-font-family-base);
  2879. width: max-content;
  2880. padding: 10px 20px;
  2881. box-shadow: 0px 0px 0px 4px #ffffff;
  2882. border-radius: 6px;
  2883. background-color: #f0f4f9;
  2884. border-collapse: collapse;
  2885. border: 1px solid #ffffff;
  2886. color: #697e91;
  2887. }
  2888. .OJBetter_modal h2 {
  2889. font-size: 1.6em;
  2890. font-weight: 700;
  2891. }
  2892. .OJBetter_modal .content{
  2893. white-space: nowrap;
  2894. max-height: 500px;
  2895. overflow-y: auto;
  2896. }
  2897. .OJBetter_modal .buttons{
  2898. display: flex;
  2899. padding-top: 15px;
  2900. }
  2901. .OJBetter_modal button {
  2902. display: inline-flex;
  2903. justify-content: center;
  2904. align-items: center;
  2905. line-height: 1;
  2906. white-space: nowrap;
  2907. cursor: pointer;
  2908. text-align: center;
  2909. box-sizing: border-box;
  2910. outline: none;
  2911. transition: .1s;
  2912. user-select: none;
  2913. vertical-align: middle;
  2914. -webkit-appearance: none;
  2915. height: 24px;
  2916. padding: 5px 11px;
  2917. margin-right: 15px;
  2918. font-size: 12px;
  2919. border-radius: 4px;
  2920. color: #ffffff;
  2921. background: #009688;
  2922. border-color: #009688;
  2923. border: none;
  2924. }
  2925. .OJBetter_modal button.secondary{
  2926. background-color:#4DB6AC;
  2927. }
  2928. .OJBetter_modal button:hover{
  2929. background-color:#4DB6AC;
  2930. }
  2931. .OJBetter_modal button.secondary:hover {
  2932. background-color: #80CBC4;
  2933. }
  2934. .OJBetter_modal .help-icon {
  2935. margin: 0px 8px 0px 0px;
  2936. height: 1em;
  2937. width: 1em;
  2938. line-height: 1em;
  2939. display: inline-flex;
  2940. justify-content: center;
  2941. align-items: center;
  2942. position: relative;
  2943. fill: currentColor;
  2944. font-size: inherit;
  2945. }
  2946. .OJBetter_modal p {
  2947. margin: 5px 0px;
  2948. }
  2949.  
  2950. /* 右键菜单 */
  2951. .OJBetter_contextmenu {
  2952. z-index: 500;
  2953. display: grid;
  2954. position: absolute;
  2955. background-color: #f0f4f9;
  2956. border-collapse: collapse;
  2957. color: #697e91;
  2958. font-family: var(--vp-font-family-base);
  2959. overflow: hidden;
  2960. box-sizing: content-box;
  2961. box-shadow: 0px 0px 0px 2px #eddbdb4d;
  2962. }
  2963. .OJBetter_contextmenu label {
  2964. margin: 0px;
  2965. }
  2966. input[type="radio"]:checked+.OJBetter_contextmenu_label_text {
  2967. background: #41e49930;
  2968. border: 1px solid green;
  2969. color: green;
  2970. font-weight: 500;
  2971. }
  2972. .OJBetter_contextmenu_label_text {
  2973. display: flex;
  2974. border: 1px dashed #80cbc4;
  2975. height: 26px;
  2976. width: 100%;
  2977. color: gray;
  2978. font-size: 13px;
  2979. font-weight: initial;
  2980. padding: 4px;
  2981. align-items: center;
  2982. -webkit-box-sizing: border-box;
  2983. -moz-box-sizing: border-box;
  2984. box-sizing: border-box;
  2985. }
  2986. .OJBetter_contextmenu_label_text:hover {
  2987. color: #F44336;
  2988. border: 1px dashed #009688;
  2989. background-color: #ffebcd;
  2990. }
  2991.  
  2992. /* RatingByClist */
  2993. .ratingBadge, html[data-theme=dark] button.ratingBadge{
  2994. display: block;
  2995. font-weight: 700;
  2996. font-size: 11px;
  2997. margin-top: 5px;
  2998. padding: 2px;
  2999. border-radius: 4px;
  3000. color: #B0BEC5;
  3001. border: 1px solid #cccccc66;
  3002. }
  3003.  
  3004. /* 多选翻译 */
  3005. .block_selected{
  3006. box-shadow: 0px 0px 0px 1px #FF9800;
  3007. outline: none;
  3008. }
  3009.  
  3010. /* 悬浮菜单 */
  3011. .OJBetter_MiniTranslateButton {
  3012. z-index: 100;
  3013. display: grid;
  3014. position: absolute;
  3015. border-collapse: collapse;
  3016. fill: #F57C00;
  3017. background-color: #FFF3E0;
  3018. overflow: hidden;
  3019. box-sizing: content-box;
  3020. box-shadow: 0px 0px 0px 2px #FFE0B2;
  3021. border-radius: 100%;
  3022. }
  3023. .OJBetter_MiniTranslateButton:hover {
  3024. cursor: pointer;
  3025. box-shadow: 0px 0px 0px 2px #FFB74D;
  3026. }
  3027.  
  3028. /* acmsguru划分块 */
  3029. .OJBetter_acmsguru {
  3030. margin: 0 0 1em!important;
  3031. }
  3032.  
  3033. /* 代码提交表单 */
  3034. #OJBetter_SubmitForm.input-output-copier:hover {
  3035. background-color: #ffffff00;
  3036. }
  3037. #OJBetter_SubmitForm input[type="number"] {
  3038. width: 40px;
  3039. color: #009688;
  3040. appearance: none;
  3041. border-radius: 6px;
  3042. border-style: solid;
  3043. border: none;
  3044. background-color: #ffffff00;
  3045. }
  3046. #OJBetter_SubmitForm :focus-visible {
  3047. outline: none;
  3048. }
  3049. #OJBetter_SubmitForm .topDiv {
  3050. height: 50px;
  3051. display: flex;
  3052. align-items: center;
  3053. justify-content: space-between;
  3054. padding: 10px 0px;
  3055. box-sizing: border-box;
  3056. }
  3057. #OJBetter_SubmitForm .topDiv .topRightDiv {
  3058. height: 100%;
  3059. display: flex;
  3060. flex-wrap: wrap;
  3061. gap: 0px;
  3062. }
  3063. #OJBetter_SubmitForm input[type="checkbox"], #OJBetter_SubmitForm label {
  3064. margin: 0px;
  3065. font-weight: initial;
  3066. }
  3067. #OJBetter_SubmitForm #fontSizeInput {
  3068. border: none;
  3069. background-color: #ffffff00;
  3070. }
  3071.  
  3072. /* 顶部区域 */
  3073. #OJBetter_SubmitForm .topRightDiv>* {
  3074. height: 100%;
  3075. box-sizing: border-box;
  3076. }
  3077. #OJBetter_SubmitForm .topRightDiv>button{
  3078. padding: 0px 8px;
  3079. }
  3080. #OJBetter_SubmitForm .topRightDiv {
  3081. display: flex;
  3082. flex-wrap: wrap;
  3083. gap: 0px;
  3084. align-items: center;
  3085. }
  3086.  
  3087. /* LSP连接Log */
  3088. #LSPLog{
  3089. width: 500px;
  3090. height: 500px;
  3091. position: fixed;
  3092. top: 50%;
  3093. left: 50%;
  3094. padding: 10px;
  3095. transform: translate(-50%, -50%);
  3096. border: 1px solid;
  3097. z-index: 200;
  3098. background-color: #ffffff;
  3099. }
  3100. #LSPLog button{
  3101. position: fixed;
  3102. top: 10px;
  3103. right: 10px;
  3104. z-index: 200;
  3105. }
  3106. #LSPLog #LSPLogList{
  3107. width: 500px;
  3108. height: 500px;
  3109. overflow: auto;
  3110. color: #424242;
  3111. }
  3112. #LSPLog li:nth-child(odd){
  3113. background-color: #f5f5f5;
  3114. }
  3115. #LSPLog details{
  3116. padding: 2px;
  3117. }
  3118.  
  3119. /* 代码编辑器 */
  3120. #OJBetter_editor{
  3121. box-sizing: border-box;
  3122. height: 600px;
  3123. border: 1px solid #d3d3d3;
  3124. width: 100%;
  3125. resize: vertical;
  3126. display: flex;
  3127. flex-direction: column;
  3128. }
  3129. #OJBetter_editor.fullscreen{
  3130. position: fixed;
  3131. top: 0;
  3132. left: 0;
  3133. width: 100%;
  3134. height: 100vh;
  3135. z-index: 2000;
  3136. }
  3137. #OJBetter_editor.bottom{
  3138. position: fixed;
  3139. bottom: 0;
  3140. left: 0;
  3141. width: 100%;
  3142. height: 50vh;
  3143. z-index: 2000;
  3144. }
  3145. .ojb_btn.exit_button_bottom {
  3146. position: fixed;
  3147. bottom: 30px;
  3148. right: 15px;
  3149. z-index: 2000;
  3150. height: 28px;
  3151. }
  3152.  
  3153. /* monaco */
  3154. #OJBetter_monaco {
  3155. flex: 1;
  3156. min-height: 0;
  3157. width: 100%;
  3158. }
  3159. #OJBetter_monaco .highlight {
  3160. border: 1px solid #ffffff00;
  3161. background-color: #ffffff00!important
  3162. }
  3163. .monaco-hover hr {
  3164. margin: 4px -8px 4px !important;
  3165. }
  3166.  
  3167. /* 状态底栏 */
  3168. #OJBetter_statusBar{
  3169. height: 22px;
  3170. font-size: 12px;
  3171. color: #757575;
  3172. border: 1px solid #d3d3d3;
  3173. background-color: #f8f8f8;
  3174. padding: 3px;
  3175. box-sizing: border-box;
  3176. }
  3177.  
  3178. /* 提交 */
  3179. #OJBetter_submitDiv{
  3180. display: flex;
  3181. padding-top: 15px;
  3182. height: 50px;
  3183. box-sizing: border-box;
  3184. }
  3185. #OJBetter_submitDiv >* {
  3186. border-radius: 6px;
  3187. }
  3188. #OJBetter_submitDiv > button {
  3189. height: 100%;
  3190. aspect-ratio: 1 / 1;
  3191. }
  3192. #SubmitButton {
  3193. color: #fff;
  3194. background-color: #209978;
  3195. border-color: #17795E;
  3196. }
  3197. #SubmitButton:hover {
  3198. background-color: #17795e;
  3199. }
  3200. #SubmitButton.disabled {
  3201. background-color: red;
  3202. animation: shake 0.07s infinite alternate;
  3203. }
  3204. #programTypeId{
  3205. height: 100%;
  3206. padding: 5px 10px;
  3207. border-radius: 6px;
  3208. border-style: solid;
  3209. border: 1px solid #ced4da;
  3210. color: #212529;
  3211. }
  3212.  
  3213. /* 调试 */
  3214. .OJBetter_loding{
  3215. padding: 6px 0px 0px 5px;
  3216. height: 22px;
  3217. }
  3218. #CompilerArgsInput{
  3219. flex-grow: 1;
  3220. width: 100%;
  3221. height: 100%;
  3222. margin-bottom: 10px;
  3223. padding: 5px 10px;
  3224. border-radius: 6px;
  3225. box-sizing: border-box;
  3226. border: 1px solid #ccc;
  3227. box-shadow: inset 0px 1px 1px rgba(0,0,0,.075);
  3228. }
  3229. #CompilerArgsInput[disabled] {
  3230. cursor: not-allowed;
  3231. }
  3232. #CompilerSetting{
  3233. font-size: 14px;
  3234. margin-top: 10px;
  3235. display: none;
  3236. }
  3237. #CompilerSetting select, #CompilerSetting textarea{
  3238. padding: 4px 10px;
  3239. border-radius: 6px;
  3240. border-style: solid;
  3241. border: 1px solid #ced4da;
  3242. color: #212529;
  3243. }
  3244. #CompilerBox{
  3245. display: grid;
  3246. margin-top: 10px;
  3247. border: #d0d7de solid 1px;
  3248. border-radius: 6px;
  3249. }
  3250. #CompilerBox > * {
  3251. margin: 5px;
  3252. }
  3253.  
  3254. /* 自定义样例 */
  3255. #customTestBlock {
  3256. margin-top: 10px;
  3257. font-size: 14px;
  3258. color: #616161;
  3259. border: 1px solid #d3d3d3;
  3260. box-sizing: border-box;
  3261. position: relative;
  3262. }
  3263. #customTestBlock #customTests{
  3264. border-top: 1px solid #d3d3d3;
  3265. margin: 0px 0px 40px 0px;
  3266. }
  3267. #customTestBlock summary {
  3268. cursor: pointer;
  3269. padding: 10px;
  3270. }
  3271. #customTestBlock textarea {
  3272. resize: vertical;
  3273. }
  3274. .sampleDiv {
  3275. color: #727378;
  3276. background-color: #FAFAFA;
  3277. padding: 5px;
  3278. margin-bottom: 10px;
  3279. box-shadow: inset 0 0 1px #0000004d;
  3280. position: relative;
  3281. }
  3282. .dynamicTextarea {
  3283. width: 98%;
  3284. height: 120px;
  3285. margin: 10px 5px;
  3286. border: 1px solid #E0E0E0;
  3287. }
  3288. .deleteCustomTest {
  3289. cursor: pointer;
  3290. position: absolute;
  3291. top: 5px;
  3292. right: 5px;
  3293. display: flex;
  3294. fill: #9E9E9E;
  3295. padding: 2px 2px;
  3296. border-radius: 4px;
  3297. border: 1px solid #ffffff00;
  3298. background-color: #ffffff00;
  3299. align-items: center;
  3300. }
  3301. .deleteCustomTest:hover {
  3302. fill: #EF5350;
  3303. border: 1px solid #ef9a9a;
  3304. background-color: #FFEBEE;
  3305. }
  3306. #addCustomTest {
  3307. cursor: pointer;
  3308. position: absolute;
  3309. bottom: 5px;
  3310. right: 5px;
  3311. padding: 3px 10px;
  3312. color: #795548;
  3313. border: 1px solid #ccc;
  3314. border-radius: 4px;
  3315. background-color: #FAFAFA;
  3316. }
  3317. #addCustomTest:hover {
  3318. background-color: #f5f5f5;
  3319. }
  3320.  
  3321. /* 调试结果 */
  3322. #statePanel{
  3323. display: none;
  3324. padding: 5px;
  3325. margin-top: 10px;
  3326. border: 1px solid #ddd;
  3327. border-radius: 4px;
  3328. }
  3329. .test-case {
  3330. padding: 10px;
  3331. border: 1px solid #ddd;
  3332. border-radius: 4px;
  3333. }
  3334. .test-case:not(:first-child){
  3335. margin-top: 5px;
  3336. }
  3337. .test-case > * {
  3338. margin: 5px 0px;
  3339. }
  3340. .test-case > :first-child {
  3341. margin-top: 0px;
  3342. }
  3343. .test-case > :last-child {
  3344. margin-bottom: 0px;
  3345. }
  3346. .test-case-title, .test-case-status {
  3347. font-size: 16px;
  3348. display: inline;
  3349. }
  3350. .test-case-status{
  3351. margin-left: 5px;
  3352. }
  3353. .test-case-status.error{
  3354. color: red;
  3355. }
  3356. .test-case-status.success{
  3357. color: #449d44;
  3358. }
  3359. .test-case-judge {
  3360. font-size: 13px;
  3361. }
  3362.  
  3363. /* 差异对比 */
  3364. .output_diff {
  3365. color: #5d4037;
  3366. margin: 5px 0px;
  3367. display: grid;
  3368. border: 1px solid #bcaaa4;
  3369. font-size: 13px;
  3370. font-family: Consolas, "Lucida Console", "Andale Mono", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace;
  3371. overflow: auto;
  3372. }
  3373. .output_diff .added {
  3374. background-color: #c8f7c5;
  3375. user-select: none;
  3376. }
  3377. .output_diff .removed {
  3378. background-color: #f7c5c5;
  3379. }
  3380. .output_diff .diffLine {
  3381. display: flex;
  3382. }
  3383. .output_diff .diffLine:nth-child(odd) {
  3384. background-color: #f5f5f5;
  3385. }
  3386. .lineNo {
  3387. display: flex;
  3388. align-items: center;
  3389. justify-content: center;
  3390. width: 17px;
  3391. color: #BDBDBD;
  3392. font-size: 10px;
  3393. border-right: 1px solid;
  3394. user-select: none;
  3395. }
  3396. .lineContent {
  3397. display: grid;
  3398. width: 100%;
  3399. }
  3400. .lineContent>span {
  3401. height: 16px;
  3402. padding-left: 3px;
  3403. }
  3404. .output_no_diff {
  3405. padding: 5px;
  3406. border: 1px solid #ddd;
  3407. }
  3408. .diff_note {
  3409. font-size: 10px;
  3410. }
  3411.  
  3412. /* 移动设备 */
  3413. @media (max-device-width: 450px) {
  3414. .ojb_btn{
  3415. height: 2em;
  3416. font-size: 1.2em;
  3417. }
  3418. .ojb_btn.OJBetter_setting{
  3419. height: 2.5em;
  3420. font-size: 1em;
  3421. }
  3422. .OJBetter_setting_menu{
  3423. width: 90%;
  3424. }
  3425. .OJBetter_setting_menu label, #darkMode_span, #loaded_span, .OJBetter_setting_menu_label_text,
  3426. .OJBetter_setting_sidebar li{
  3427. font-size: 1em;
  3428. }
  3429. .translate-problem-statement{
  3430. font-size: 1.2em;
  3431. }
  3432. .OJBetter_modal{
  3433. font-size: 1.5em;
  3434. }
  3435. .OJBetter_setting_list, .translate-problem-statement{
  3436. padding: 0.5em;
  3437. }
  3438. .OJBetter_setting_menu_label_text{
  3439. height: 2.5em;
  3440. padding: 0.5em;
  3441. }
  3442. #pagBar #jump-input, #pagBar #items-per-page, .OJBetter_modal button{
  3443. height: 2.5em;
  3444. font-size: 1em;
  3445. }
  3446. .translate-problem-statement p, .translate-problem-statement ul li{
  3447. line-height: 1.5em !important;
  3448. }
  3449. .OJBetter_contextmenu_label_text{
  3450. height: 3em;
  3451. font-size: 1em;
  3452. }
  3453. }
  3454.  
  3455. /* 覆盖网站原本的样式 */
  3456. div#select-lang {
  3457. padding: 0px;
  3458. }
  3459. `);
  3460.  
  3461. /**
  3462. * 添加一些依赖库和条件加载的css样式
  3463. */
  3464. function addDependencyStyles() {
  3465. GM_addStyle(GM_getResourceText("xtermcss"));
  3466. // 自定义图标大小
  3467. GM_addStyle(`
  3468. .iconfont {
  3469. font-size: ${OJBetter.preference.iconButtonSize}px;
  3470. }
  3471. `);
  3472. }
  3473.  
  3474. /**
  3475. * 添加包含i18n内容的css样式
  3476. */
  3477. function addI18nStyles() {
  3478. GM_addStyle(`
  3479. /* 加载鼠标悬浮覆盖层css */
  3480. .overlay::before {
  3481. content: '';
  3482. position: absolute;
  3483. top: 0;
  3484. left: 0;
  3485. width: 100%;
  3486. height: 100%;
  3487. background: repeating-linear-gradient(135deg, rgb(77 208 225 / 30%), rgb(77 208 225 / 30%) 30px, rgb(77 208 225 / 10%) 0px, rgb(77 208 225 / 10%) 55px);
  3488. z-index: 100;
  3489. }
  3490. .overlay::after {
  3491. content: '${i18next.t('targetArea', { ns: 'common' })}';
  3492. position: absolute;
  3493. top: 50%;
  3494. left: 50%;
  3495. transform: translate(-50%, -50%);
  3496. color: #00695C;
  3497. font-size: 16px;
  3498. font-weight: bold;
  3499. z-index: 100;
  3500. }
  3501.  
  3502. .config::before {
  3503. content: "${i18next.t('common.configManageTitle', { ns: 'settings' })}";
  3504. display: block;
  3505. height: 20px;
  3506. background-color: #f0f8ff;
  3507. border: 1px solid #c5cae9;
  3508. border-bottom: 0px;
  3509. line-height: 20px;
  3510. padding: 2px 10px;
  3511. border-radius: 8px 8px 0px 0px;
  3512. box-sizing: content-box;
  3513. }
  3514. .config.missing::before {
  3515. content: "${i18next.t('common.missing.radio', { ns: 'settings' })}";
  3516. background-color: #fef0f0;
  3517. color: #f56c6c;
  3518. border: 1px solid #fab6b6;
  3519. }
  3520. `);
  3521. }
  3522.  
  3523. // ------------------------------
  3524. // 一些工具类
  3525. // ------------------------------
  3526.  
  3527.  
  3528. /**
  3529. * 自定义错误类,以区分不同的错误类型
  3530. */
  3531. class OJB_GMError extends Error {
  3532. constructor(type, message, originalError) {
  3533. super(message);
  3534. this.name = 'GMError';
  3535. this.type = type;
  3536. this.stack = originalError.stack;
  3537. Object.assign(this, originalError);
  3538. }
  3539. }
  3540.  
  3541. /**
  3542. * 文本块替换/恢复类
  3543. */
  3544. class TextBlockReplacer {
  3545. constructor() {
  3546. /** @type {string[]} 匹配项 */
  3547. this.matches = [];
  3548. /** @type {Map<string, string>} 待还原项 */
  3549. this.replacements = new Map();
  3550. /** @type {Map<string, string>} 暂时未找到的待还原项 */
  3551. this.tempReplacements = new Map();
  3552. /** @type {string} 替换符号 */
  3553. this.replaceSymbol = OJBetter.translation.replaceSymbol;
  3554. }
  3555.  
  3556. /**
  3557. * 替换文本
  3558. * @param {string} text 原文本
  3559. * @param {RegExp} regex 匹配规则
  3560. * @returns {string} 替换后的文本
  3561. */
  3562. replace(text, regex) {
  3563. this.matches = text.match(regex) || [];
  3564. try {
  3565. for (let i = 0; i < this.matches.length; i++) {
  3566. const match = this.matches[i];
  3567. const id = OJB_getRandomNumber(8);
  3568. let replacement = '';
  3569. switch (this.replaceSymbol) {
  3570. case "1":
  3571. replacement = `【${id}】`;
  3572. break;
  3573. case "2":
  3574. replacement = `{${id}}`;
  3575. break;
  3576. case "3":
  3577. replacement = `[${id}]`;
  3578. break;
  3579. default:
  3580. replacement = `【${id}】`;
  3581. break;
  3582. }
  3583. text = text.replace(match, replacement);
  3584. this.replacements.set(id, match);
  3585. }
  3586. } catch (e) { }
  3587. return text;
  3588. }
  3589.  
  3590.  
  3591. /**
  3592. * 恢复替换的文本
  3593. * @param {string} text 还原前的文本
  3594. * @returns {string} 还原后的文本
  3595. */
  3596. recover(text) {
  3597. let textCopy = text;
  3598.  
  3599. /**
  3600. * 替换文本
  3601. * @param {string} replacement 替换的文本
  3602. * @param {string} regexPattern 匹配规则
  3603. * @returns {void}
  3604. */
  3605. const replaceText = (replacement, regexPattern) => {
  3606. const latexMatch = '(?<latex_block>\\$\\$(\\\\.|[^\\$])*?\\$\\$)|(?<latex_inline>\\$(\\\\.|[^\\$])*?\\$)|';
  3607. const regex = new RegExp(latexMatch + regexPattern, 'g');
  3608. textCopy = textCopy.replace(regex, (match, ...args) => {
  3609. // LaTeX中的不替换
  3610. const groups = args[args.length - 1]; // groups是replace方法的最后一个参数
  3611. if (groups.latex_block || groups.latex_inline) return match;
  3612. // 没有空格则加一个
  3613. const offset = args[args.length - 3]; // offset是replace方法的倒数第三个参数
  3614. let leftSpace = "", rightSpace = "";
  3615. if (!/\s/.test(textCopy[offset - 1])) leftSpace = " ";
  3616. if (!/\s/.test(textCopy[offset + match.length])) rightSpace = " ";
  3617. return leftSpace + replacement + rightSpace;
  3618. });
  3619. };
  3620.  
  3621. /**
  3622. * 尝试还原
  3623. * @param {string} replacement 替换的文本
  3624. * @param {string} id 替换的 id
  3625. * @returns {boolean} 是否替换成功
  3626. */
  3627. const tryRecover = (replacement, id) => {
  3628. // 尝试还原,如果还原成功,则从 replacements 中删除
  3629. const originalText = textCopy;
  3630. replaceText(replacement, `【\\s*${id}\\s*】|\\[\\s*${id}\\s*\\]|{\\s*${id}\\s*}`); // 替换符完整匹配(考虑了多出空格的情况)
  3631. replaceText(replacement, `【\\s*${id}(?![】\\d])|(?<![【\\d])${id}\\s*】|\\[\\s*${id}(?![\\]\\d])|(?<![\\[\\d])${id}\\s*\\]|{\\s*${id}(?![}\\d])|(?<![{\\d])${id}\\s*}`); // 替换符部分匹配
  3632.  
  3633. if (textCopy === originalText) {
  3634. // 如果文本没有变化,说明没有找到,加入到 tempReplacements
  3635. this.tempReplacements.set(id, replacement);
  3636. return false;
  3637. } else {
  3638. // 如果文本变化了,说明找到并成功替换,则删除
  3639. this.replacements.delete(id);
  3640. this.tempReplacements.delete(id);
  3641. return true;
  3642. }
  3643. }
  3644.  
  3645. // 处理 replacements 中的项
  3646. this.replacements.forEach((replacement, id) => {
  3647. tryRecover(replacement, id);
  3648. });
  3649.  
  3650. // 处理 tempReplacements 中的项
  3651. while (this.tempReplacements.size > 0) {
  3652. let found = false;
  3653. this.tempReplacements.forEach((replacement, id) => {
  3654. found = tryRecover(replacement, id) || found;
  3655. });
  3656. if (!found) break; // 如果这一轮没有找到任何项,终止循环
  3657. }
  3658.  
  3659. // 如果 tempReplacements 还有未找到的项
  3660. if (this.tempReplacements.size > 0) {
  3661. console.warn("There are still some replacements not found:", this.tempReplacements);
  3662. }
  3663.  
  3664. return textCopy;
  3665. }
  3666. }
  3667.  
  3668. // ------------------------------
  3669. // 一些工具函数
  3670. // ------------------------------
  3671.  
  3672. /**
  3673. * 延迟函数
  3674. * @param {number} ms 延迟时间(毫秒)
  3675. * @returns {Promise<void>}
  3676. */
  3677. function OJB_delay(ms) {
  3678. return new Promise(resolve => setTimeout(resolve, ms));
  3679. }
  3680.  
  3681. /**
  3682. * 格式化链接格式
  3683. * @param {string} url 链接字符串
  3684. * @returns {string} 清理后的链接字符串
  3685. */
  3686. function OJB_cleanLink(url) {
  3687. // 替换'http://'为'https://'
  3688. let cleanUrl = url.replace(/^http:\/\//i, 'https://');
  3689.  
  3690. // 移除末尾的斜杠
  3691. cleanUrl = cleanUrl.replace(/\/$/, '');
  3692.  
  3693. return cleanUrl;
  3694. }
  3695.  
  3696. /**
  3697. * 深度比较两个对象或数组是否完全相等。
  3698. * @param {any} a - 第一个比较对象。
  3699. * @param {any} b - 第二个比较对象。
  3700. * @returns {boolean} - 如果两个对象或数组深度相等,则返回true,否则返回false。
  3701. */
  3702. function OJB_deepEquals(a, b) {
  3703. if (a === b) return true;
  3704. if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) return false;
  3705. const keysA = Object.keys(a);
  3706. const keysB = Object.keys(b);
  3707. if (keysA.length !== keysB.length) return false;
  3708. for (let key of keysA) {
  3709. if (!b.hasOwnProperty(key)) return false;
  3710. if (!OJB_deepEquals(a[key], b[key])) return false;
  3711. }
  3712. return true;
  3713. }
  3714.  
  3715. /**
  3716. * 用于封装需要重试的异步函数
  3717. * @param {Function} task 需要封装的异步函数
  3718. * @param {Object} options 配置项
  3719. * @param {Number} options.maxRetries 重试次数,默认为 5
  3720. * @param {Number} options.retryInterval 重试时间间隔,默认为 0 毫秒
  3721. * @param {Function} options.errorHandler 错误处理函数,默认为抛出错误
  3722. * @param {...any} args task 函数的参数
  3723. * @returns {Promise} 返回 Promise
  3724. */
  3725. async function OJB_promiseRetryWrapper(task, {
  3726. maxRetries = 5,
  3727. retryInterval = 0,
  3728. errorHandler = (err) => { throw err }
  3729. } = {}, ...args) {
  3730. let attemptsLeft = maxRetries;
  3731. while (attemptsLeft--) {
  3732. try {
  3733. return await task(...args);
  3734. } catch (err) {
  3735. if (attemptsLeft <= 0) {
  3736. return errorHandler(err, maxRetries, attemptsLeft);
  3737. }
  3738. if (retryInterval > 0) {
  3739. await OJB_delay(retryInterval);
  3740. }
  3741. }
  3742. }
  3743. }
  3744.  
  3745. /**
  3746. * GM_xmlhttpRequest 的 Promise 封装
  3747. * @param {Object} options GM_xmlhttpRequest 的参数
  3748. * @param {Boolean} isStream 是否为流式请求
  3749. * @returns {Promise<OJB_GMError>} 返回 Promise
  3750. */
  3751. function OJB_GMRequest(options, isStream = false) {
  3752. return new Promise((resolve, reject) => {
  3753. GM_xmlhttpRequest({
  3754. ...options,
  3755. ...(isStream ? {
  3756. onloadstart: resolve
  3757. } : {
  3758. onload: resolve
  3759. }),
  3760. onerror: (error) => reject(new OJB_GMError('error', 'An error occurred during the request.', error)),
  3761. ontimeout: (error) => reject(new OJB_GMError('timeout', 'The request timed out.', error)),
  3762. onabort: (error) => reject(new OJB_GMError('abort', 'The request was aborted.', error)),
  3763. });
  3764. });
  3765. }
  3766.  
  3767. /**
  3768. * 获取cookie
  3769. * @param {string} name cookie名称
  3770. * @returns {string} cookie值
  3771. */
  3772. function OJB_getCookie(name) {
  3773. const cookies = document.cookie.split(";");
  3774. for (let i = 0; i < cookies.length; i++) {
  3775. const cookie = cookies[i].trim();
  3776. const [cookieName, cookieValue] = cookie.split("=");
  3777.  
  3778. if (cookieName === name) {
  3779. return decodeURIComponent(cookieValue);
  3780. }
  3781. }
  3782. return "";
  3783. }
  3784.  
  3785. /**
  3786. * 检查是否仍在同一浏览器会话中
  3787. * @param {string} sessionKey - 会话键名,用于标识会话
  3788. * @returns {boolean} - 如果在当前会话中之前已经设置过这个键,则返回true,否则返回false
  3789. */
  3790. function OJB_isSameBrowserSession(sessionKey) {
  3791. const fullCookieName = `OJB_Session_${sessionKey}`;
  3792. const sessionValue = OJB_getCookie(fullCookieName);
  3793. if (sessionValue === "") {
  3794. document.cookie = `${fullCookieName}=true; path=/`;
  3795. return false;
  3796. }
  3797. return true;
  3798. }
  3799.  
  3800. /**
  3801. * 随机数生成
  3802. * @param {number} numDigits 位数
  3803. * @returns {number}
  3804. */
  3805. function OJB_getRandomNumber(numDigits) {
  3806. let min = Math.pow(10, numDigits - 1);
  3807. let max = Math.pow(10, numDigits) - 1;
  3808. return Math.floor(Math.random() * (max - min + 1)) + min;
  3809. }
  3810.  
  3811. /**
  3812. * 防抖函数
  3813. * @param {Function} callback 回调函数
  3814. * @returns {Function}
  3815. */
  3816. function OJB_debounce(callback) {
  3817. let timer;
  3818. let immediateExecuted = false;
  3819. const delay = 500;
  3820. return function () {
  3821. clearTimeout(timer);
  3822. if (!immediateExecuted) { callback.call(this); immediateExecuted = true; }
  3823. timer = setTimeout(() => { immediateExecuted = false; }, delay);
  3824. };
  3825. }
  3826.  
  3827. /**
  3828. * 为元素添加鼠标拖拽支持
  3829. * @param {JQuery<HTMLElement>} element 要添加拖拽支持的元素
  3830. * @returns {void}
  3831. */
  3832. function OJB_addDraggable(element) {
  3833. let isDragging = false;
  3834. let x, y, l, t, nl, nt;
  3835. let isSpecialMouseDown = false; // 选取某些元素时不拖动
  3836.  
  3837. element.on('mousedown', function (e) {
  3838. isSpecialMouseDown = $(e.target).is('label, p, input, textarea, span, select, details, summary');
  3839. if (isSpecialMouseDown) return;
  3840.  
  3841. isDragging = true;
  3842. x = e.clientX;
  3843. y = e.clientY;
  3844. l = element.offset().left - $(window).scrollLeft();
  3845. t = element.offset().top - $(window).scrollTop();
  3846.  
  3847. element.css({ left: l + 'px', top: t + 'px', transform: 'none' });
  3848.  
  3849. $(document).on("mousemove", drag);
  3850. $(document).on("mouseup", stopDrag);
  3851. element.css('cursor', 'all-scroll');
  3852. });
  3853.  
  3854. const drag = (e) => {
  3855. if (!isDragging) return;
  3856. // 不执行拖动操作
  3857. if ($(e.target).is('label, p, input, textarea, span') || isSpecialMouseDown && !$(e.target).is('input, textarea')) return;
  3858. e.preventDefault();
  3859.  
  3860. const nx = e.clientX;
  3861. const ny = e.clientY;
  3862. nl = nx - (x - l);
  3863. nt = ny - (y - t);
  3864. element.css({ transform: `translate(${nx - x}px, ${ny - y}px)` });
  3865. };
  3866.  
  3867. const stopDrag = () => {
  3868. isDragging = false;
  3869. isSpecialMouseDown = false;
  3870. element.css('cursor', 'default');
  3871.  
  3872. // 在停止拖拽后,设置元素的left和top,并还原transform
  3873. element.css({ left: nl + 'px', top: nt + 'px', transform: 'none' });
  3874. $(document).off("mousemove", drag);
  3875. $(document).off("mouseup", stopDrag);
  3876. };
  3877. }
  3878.  
  3879. /**
  3880. * 切换元素的折叠/展开过渡动画
  3881. * @param {HTMLElement} element
  3882. */
  3883. function OJB_toggleCollapseExpand(element) {
  3884. // 设置transitionend事件监听器的函数
  3885. const setTransitionListener = (listener) => {
  3886. const listenerName = `transitionEndListener${Date.now()}`;
  3887. window[listenerName] = listener;
  3888. element.addEventListener('transitionend', listener);
  3889. element.setAttribute('data-transition-end-listener', listenerName);
  3890. };
  3891.  
  3892. // 移除事件监听器的函数
  3893. const removeTransitionListener = () => {
  3894. const transitionEndListenerName = element.getAttribute('data-transition-end-listener');
  3895. if (transitionEndListenerName) {
  3896. element.removeEventListener('transitionend', window[transitionEndListenerName]);
  3897. element.removeAttribute('data-transition-end-listener');
  3898. }
  3899. };
  3900.  
  3901. const collapsed = element.getAttribute('data-collapsed') === 'true';
  3902. const sectionHeight = element.scrollHeight;
  3903.  
  3904. // 移除事件监听器
  3905. removeTransitionListener();
  3906.  
  3907. // 设置初始样式
  3908. element.style.overflow = 'hidden';
  3909. element.style.transition = 'height 0.3s ease-out 0s';
  3910. element.style.height = collapsed ? `0px` : `${sectionHeight}px`;
  3911. element.style.opacity = collapsed ? '' : '1';
  3912.  
  3913. // 需要立即开始动画
  3914. requestAnimationFrame(() => {
  3915. // 设置结束样式
  3916. element.style.height = collapsed ? `${sectionHeight}px` : `0px`;
  3917. });
  3918.  
  3919. const transitionEndListener = (event) => {
  3920. if (event.propertyName === 'height') {
  3921. if (collapsed) {
  3922. // 展开后的设置
  3923. element.style.height = '';
  3924. element.style.overflow = '';
  3925. } else {
  3926. // 折叠后的设置
  3927. element.style.opacity = '0';
  3928. }
  3929. removeTransitionListener();
  3930. }
  3931. };
  3932.  
  3933. setTransitionListener(transitionEndListener);
  3934.  
  3935. // 更新data-collapsed属性
  3936. element.setAttribute('data-collapsed', collapsed ? 'false' : 'true');
  3937. }
  3938.  
  3939. /**
  3940. * 获取外部JSON并转换为Object
  3941. * @param {string} url JSON Url
  3942. * @param {boolean} [nacache=true] 是否不使用缓存
  3943. * @returns {Promise<Object>} JSON Object
  3944. */
  3945. async function OJB_getExternalJSON(url, nacache = true) {
  3946. const response = await OJB_GMRequest({
  3947. method: "GET",
  3948. url: url,
  3949. nocache: nacache
  3950. });
  3951. try {
  3952. return JSON.parse(response.responseText);
  3953. } catch (e) {
  3954. throw new Error(`JSON parse error\n${e}`);
  3955. }
  3956. }
  3957.  
  3958. /**
  3959. * 创建确认对话框dialog
  3960. * @param {string} title 标题
  3961. * @param {string} content 内容
  3962. * @param {string[]} buttons 按钮 (取消 确定) 可以为null
  3963. * @param {boolean} renderMarkdown 是否使用markdown渲染文本
  3964. * @returns {Promise<boolean>} 用户点击了确定按钮返回true, 否则返回false
  3965. */
  3966. function OJB_createDialog(title, content, buttons, renderMarkdown = false) {
  3967. return new Promise(resolve => {
  3968. let contentHtml = content;
  3969.  
  3970. if (renderMarkdown) {
  3971. const md = window.markdownit();
  3972. contentHtml = md.render(content);
  3973. }
  3974.  
  3975. const dialog = OJB_safeCreateJQElement(`
  3976. <dialog class="OJBetter_modal">
  3977. <h2>${title}</h2>
  3978. <div class="content">${contentHtml}</div>
  3979. </dialog>
  3980. `);
  3981. const buttonbox = OJB_safeCreateJQElement(`<div class="buttons"></div>`);
  3982. const cancelButton = OJB_safeCreateJQElement(`<button class="cancelButton">${buttons[0]}</button>`)
  3983. .addClass("secondary");
  3984. const continueButton = OJB_safeCreateJQElement(`<button class="continueButton">${buttons[1]}</button>`);
  3985. if (buttons[0] !== null) buttonbox.append(cancelButton);
  3986. if (buttons[1] !== null) buttonbox.append(continueButton);
  3987. dialog.append(buttonbox);
  3988. $('body').append(dialog);
  3989.  
  3990. OJB_showModal(dialog);
  3991. OJB_addDraggable(dialog);
  3992.  
  3993. continueButton.click(function () {
  3994. OJB_closeAndRemoveModal(dialog);
  3995. resolve(true);
  3996. });
  3997.  
  3998. cancelButton.click(function () {
  3999. OJB_closeAndRemoveModal(dialog);
  4000. resolve(false);
  4001. });
  4002. });
  4003. }
  4004.  
  4005. /**
  4006. * 显示模态对话框并阻止页面滚动,同时考虑滚动条宽度变化和原始marginRight
  4007. * @param {JQuery<HTMLElement>} element
  4008. */
  4009. function OJB_showModal(element) {
  4010. const dialog = element.get(0);
  4011. dialog.showModal();
  4012. OJBetter.state.openDialogCount++;
  4013.  
  4014. if (OJBetter.state.openDialogCount === 1) {
  4015. const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
  4016. // 获取原始的html marginRight,考虑到可能的非数字值,比如auto
  4017. const originalMarginRight = window.getComputedStyle(document.documentElement).marginRight;
  4018. const marginRightValue = parseFloat(originalMarginRight) || 0; // 将非数字值转换为0
  4019.  
  4020. if (scrollbarWidth > 0) {
  4021. // 保存原始的marginRight,并设置新的值以补偿滚动条宽度
  4022. document.documentElement.style.setProperty('--original-margin-right', originalMarginRight);
  4023. document.documentElement.style.marginRight = `${marginRightValue + scrollbarWidth}px`;
  4024. }
  4025.  
  4026. // 保存原始的overflow样式
  4027. document.documentElement.setAttribute('data-original-overflow', document.documentElement.style.overflow);
  4028. document.documentElement.style.overflow = 'hidden';
  4029. }
  4030.  
  4031. const allowScrollIfNeeded = () => {
  4032. OJBetter.state.openDialogCount--;
  4033. if (OJBetter.state.openDialogCount === 0) {
  4034. // 恢复原始的html marginRight和overflow样式
  4035. const originalMarginRight = document.documentElement.style.getPropertyValue('--original-margin-right');
  4036. document.documentElement.style.marginRight = originalMarginRight;
  4037. document.documentElement.style.removeProperty('--original-margin-right');
  4038.  
  4039. const originalOverflow = document.documentElement.getAttribute('data-original-overflow');
  4040. document.documentElement.style.overflow = originalOverflow;
  4041. document.documentElement.removeAttribute('data-original-overflow');
  4042. }
  4043. };
  4044.  
  4045. dialog.addEventListener('close', allowScrollIfNeeded);
  4046. }
  4047.  
  4048. /**
  4049. * 关闭并移除模态对话框
  4050. * @param {JQuery<HTMLElement>} element
  4051. */
  4052. function OJB_closeAndRemoveModal(element) {
  4053. const dialog = element.get(0);
  4054. dialog.close();
  4055. dialog.remove();
  4056. }
  4057.  
  4058. /**
  4059. * 关闭并移除模态对话框
  4060. * @param {JQuery<HTMLElement>} element
  4061. */
  4062. function OJB_closeModal(element) {
  4063. const dialog = element.get(0);
  4064. dialog.close();
  4065. }
  4066.  
  4067. /**
  4068. * 清除i18next的缓存数据并刷新
  4069. */
  4070. function clearI18nextCache() {
  4071. Object.keys(localStorage)
  4072. .filter(key => key.startsWith('i18next_res_'))
  4073. .forEach(key => localStorage.removeItem(key));
  4074. window.location.reload();
  4075. }
  4076.  
  4077. /**
  4078. * 从Pre代码块中获取原始代码
  4079. * @param {HTMLElement} element pre代码块元素
  4080. * @returns {string|null} 代码文本
  4081. */
  4082. function OJB_getCodeFromPre(element) {
  4083. /**
  4084. * 从Ace格式化的代码块中获取原始代码
  4085. * @param {HTMLElement} element pre代码块元素
  4086. * @returns {string} 代码文本
  4087. */
  4088. const getCodeFromAcePre = function (element) {
  4089. const editor = ace.edit(element);
  4090. return editor.getValue();
  4091. }
  4092.  
  4093. /**
  4094. * 从Pretty格式化的代码块中获取原始代码-1
  4095. * 代码直接存放在 pre 元素中
  4096. * @param {HTMLElement} element pre代码块元素
  4097. * @returns {string} 代码文本
  4098. */
  4099. const getCodeFromPrettyPre = function (element) {
  4100. return Array.from(element.querySelectorAll('li')).map(function (li) {
  4101. return li.textContent;
  4102. }).join('\n');
  4103. }
  4104.  
  4105. /**
  4106. * 从Pretty格式化的代码块中获取原始代码-2
  4107. * 代码存放在子元素 code 中
  4108. * @param {HTMLElement} element pre代码块元素
  4109. * @returns {string} 代码文本
  4110. */
  4111. const getCodeFromPreChild = function (element) {
  4112. const code = element.querySelector("code.prettyprint");
  4113. if (code.classList.contains("linenums")) {
  4114. return getCodeFromPrettyPre(element);
  4115. } else {
  4116. return element.querySelector("code.prettyprint").textContent;
  4117. }
  4118. }
  4119.  
  4120. if (element.id === "submission-code") {
  4121. return getCodeFromAcePre(element);
  4122. } else if (element.classList.contains("prettyprint")) {
  4123. return getCodeFromPrettyPre(element);
  4124. } else if (element.querySelector("code.prettyprint")) {
  4125. return getCodeFromPreChild(element);
  4126. } else {
  4127. return null;
  4128. }
  4129. }
  4130.  
  4131. /**
  4132. * 判断代码的语言
  4133. * @param {string} code 代码文本
  4134. * @returns {string} 可能的语言
  4135. */
  4136. function OJB_codeLangDetect(code) {
  4137. result = hljs.highlightAuto(code);
  4138. return result.language;
  4139. }
  4140.  
  4141. /**
  4142. * 获取指定命名空间下的所有i18n翻译键值对。
  4143. *
  4144. * @param {string} namespace - 要获取键值对的i18next命名空间。
  4145. * @returns {Map<string, string>} 一个包含命名空间下所有键值对的Map对象。
  4146. */
  4147. function OJB_getAllI18nKeysForNamespace(namespace) {
  4148. const language = i18next.language; // 获取当前语言
  4149. const resources = i18next.store.data[language]; // 获取当前语言的所有资源
  4150. const nsResources = resources[namespace]; // 获取特定命名空间的资源
  4151. const resultMap = new Map();
  4152.  
  4153. if (nsResources) {
  4154. // 遍历命名空间下的所有键值对,并添加到Map中
  4155. Object.keys(nsResources).forEach(key => {
  4156. resultMap.set(key, nsResources[key]);
  4157. });
  4158. } else {
  4159. console.log(`No resources found for namespace "${namespace}"`);
  4160. }
  4161.  
  4162. return resultMap;
  4163. }
  4164.  
  4165. /**
  4166. * 更新检查
  4167. */
  4168. async function checkScriptVersion() {
  4169. try {
  4170. const versionResponse = await OJB_GMRequest({
  4171. method: "GET",
  4172. url: "https://aowuucdn.oss-accelerate.aliyuncs.com/script/versions.json",
  4173. timeout: 10 * 1e3,
  4174. nocache: true
  4175. });
  4176. const versionData = JSON.parse(versionResponse.responseText);
  4177. const { [OJBetter.state.formatName]: { dev: version_dev, release: version_release } } = versionData;
  4178. const baseUrls = {
  4179. // greasyfork: 'https://update.greatest.deepsurf.us/scripts/465777/Codeforces%20Better%21.user.js',
  4180. greasyfork: 'https://update.greatest.deepsurf.us/scripts/471106/Atcoder%20Better%21.user.js',
  4181. github: `https://github.com/beijixiaohu/OJBetter/raw/main/script/${OJBetter.about.updateChannel}/${OJBetter.state.formatName}.user.js`,
  4182. aliyunoss: `https://aowuucdn.oss-accelerate.aliyuncs.com/script/${OJBetter.about.updateChannel}/${OJBetter.state.formatName}.user.js`
  4183. };
  4184. /** @type {string} 更新跳转url */
  4185. const updateUrl = baseUrls[OJBetter.about.updateSource];
  4186. /** @type {string} 是否暂时跳过cookie */
  4187. const skipUpdate = OJB_getCookie("skipUpdate");
  4188. /** @type {string} 当前更新频道的最新版本 */
  4189. const version = OJBetter.about.updateChannel == "release" ? version_release : version_dev;
  4190. if (OJB_compareVersions(version, OJBetter.state.version) === 1 && skipUpdate !== "true") {
  4191. const updateConfirmed = await OJB_createDialog(
  4192. i18next.t('update.title', { ns: 'dialog', scriptName: OJBetter.state.name }),
  4193. i18next.t('update.content', { ns: 'dialog', oldVersion: OJBetter.state.version, newVersion: version }),
  4194. [
  4195. i18next.t('update.buttons.0', { ns: 'dialog' }),
  4196. i18next.t('update.buttons.1', { ns: 'dialog' })
  4197. ],
  4198. true
  4199. );
  4200.  
  4201. if (updateConfirmed) {
  4202. window.location.href = updateUrl;
  4203. } else {
  4204. document.cookie = "skipUpdate=true; path=/";
  4205. }
  4206. }
  4207. } catch (error) {
  4208. console.error("Update check failed: ", error);
  4209. }
  4210. }
  4211.  
  4212. /**
  4213. * 公告
  4214. */
  4215. async function showAnnounce() {
  4216. /** @type {string} 最新公告版本*/
  4217. const lastAnnounceVer = i18next.t('lastVersion', { ns: 'announce' });
  4218. if (OJB_compareVersions(OJBetter.state.version, OJBetter.state.lastAnnounceVer) === 1) {
  4219. const title = `🎉${i18next.t('announce.title', { ns: 'dialog' })} ${OJBetter.state.version}`;
  4220. /** @type {Boolean} 是否是新的公告 */
  4221. const isNewAnnounceVer = OJB_compareVersions(lastAnnounceVer, OJBetter.state.lastReadAnnounceVer) === 1;
  4222. /** @type {Boolean} 是否展示新的公告(高于当前版本的测试公告不展示) */
  4223. const showNewAnnounceVer = OJB_compareVersions(lastAnnounceVer, OJBetter.state.version) !== 1;
  4224. /**
  4225. * 获取公告的内容
  4226. * @returns {string} 公告内容
  4227. */
  4228. const getAnnounceContent = function () {
  4229. // 获取公告
  4230. const announceMap = OJB_getAllI18nKeysForNamespace('announce');
  4231. // 移除 'lastVersion' 键
  4232. announceMap.delete('lastVersion');
  4233. // 将 Map 转换为数组并根据版本号排序
  4234. const sortedVersions = [...announceMap.keys()].sort(OJB_compareVersions).reverse();
  4235. let content = "";
  4236. sortedVersions.forEach(version => {
  4237. content += `### ${version}\n\n`; // 使用版本号作为标题
  4238. content += announceMap.get(version); // 添加对应版本的公告内容
  4239. content += "\n\n";
  4240. });
  4241.  
  4242. return content;
  4243. };
  4244.  
  4245. const content = (() => {
  4246. if (isNewAnnounceVer && showNewAnnounceVer) {
  4247. return `${i18next.t('announce.prefix', { ns: 'dialog' })}\n\n${getAnnounceContent()}`;
  4248. } else {
  4249. return i18next.t('announce.divContent', { ns: 'dialog' });
  4250. }
  4251. })();
  4252. const ok = await OJB_createDialog(
  4253. title,
  4254. content,
  4255. [
  4256. null,
  4257. i18next.t('announce.buttons.0', { ns: 'dialog' })
  4258. ],
  4259. true
  4260. ); //跳过折叠块确认
  4261. if (ok) {
  4262. if (isNewAnnounceVer && showNewAnnounceVer) {
  4263. GM_setValue('lastReadAnnounceVer', lastAnnounceVer);
  4264. }
  4265. GM_setValue('lastAnnounceVer', OJBetter.state.version);
  4266. }
  4267. }
  4268. };
  4269.  
  4270. /**
  4271. * 页面顶部提示信息alert类
  4272. */
  4273. class LoadingMessage {
  4274. constructor() {
  4275. this._statusElement = null;
  4276. this._isDisplayed = false;
  4277. this.init();
  4278. }
  4279.  
  4280. /**
  4281. * 初始化加载提示信息
  4282. */
  4283. init() {
  4284. this._statusElement = this.createStatusElement();
  4285. this.insertStatusElement();
  4286. }
  4287.  
  4288. /**
  4289. * 创建提示信息元素
  4290. */
  4291. createStatusElement() {
  4292. const statusElement = $("<div></div>").addClass("alert OJBetter_alert")
  4293. .css({
  4294. "margin": "1em",
  4295. "text-align": "center",
  4296. "position": "relative"
  4297. }).hide();
  4298. return statusElement;
  4299. }
  4300.  
  4301. /**
  4302. * 插入提示信息
  4303. * @returns {void}
  4304. */
  4305. insertStatusElement() {
  4306. // (OJBetter.typeOfPage.is_mSite ? $("header") : $(".menu-box:first").next()).after(this._statusElement);
  4307. $("#main-container").prepend(this._statusElement);
  4308. }
  4309.  
  4310. /**
  4311. * 显示提示信息
  4312. */
  4313. showStatus() {
  4314. this._statusElement.show();
  4315. this._isDisplayed = true;
  4316. }
  4317.  
  4318. /**
  4319. * 隐藏提示信息
  4320. */
  4321. hideStatus() {
  4322. this._statusElement.fadeOut(500);
  4323. this._isDisplayed = false;
  4324. }
  4325.  
  4326. /**
  4327. * 移除提示信息
  4328. */
  4329. removeStatus() {
  4330. this._statusElement.remove();
  4331. this._isDisplayed = false;
  4332. }
  4333.  
  4334. /**
  4335. * 更新提示信息
  4336. * @param {string} text 提示信息文本
  4337. * @param {string} type 提示信息类型,可选值:info, success, warning, error
  4338. * @param {number} timeout 提示信息显示的持续时间(毫秒), 默认为无限长
  4339. */
  4340. updateStatus(text, type = 'info', timeout = Infinity, isMarkdown = false) {
  4341. if (isMarkdown) {
  4342. let md = window.markdownit({
  4343. html: !is_escapeHTML,
  4344. });
  4345. text = md.render(text);
  4346. }
  4347. this._statusElement.html(text).removeClass("alert-info alert-success alert-warning alert-error").addClass(`alert-${type}`);
  4348. if (!this._isDisplayed) {
  4349. this.showStatus();
  4350. }
  4351. if (timeout !== Infinity) {
  4352. setTimeout(() => {
  4353. this.hideStatus();
  4354. }, timeout);
  4355. }
  4356. }
  4357. }
  4358.  
  4359. /**
  4360. * 获取网站本地化的数据
  4361. * @param {*} localizationLanguage 本地化语言
  4362. * @returns {Promise<Object>} 本地化数据
  4363. */
  4364. async function getLocalizeWebsiteJson(localizationLanguage) {
  4365. let data = await OJBetter.common.database.localizeSubsData.get(localizationLanguage);
  4366. let url = localizationLanguage === "zh" ?
  4367. `https://aowuucdn.oss-accelerate.aliyuncs.com/resources/subs/${OJBetter.state.formatName}.json` :
  4368. `https://aowuucdn.oss-accelerate.aliyuncs.com/i18n/${localizationLanguage}/resources/subs/${OJBetter.state.formatName}.json`;
  4369. if (data) data = data.data;
  4370. if (!data) {
  4371. // 如果本地没有数据,从远端获取并保存
  4372. data = await OJB_getExternalJSON(url);
  4373. await OJBetter.common.database.localizeSubsData.put({ lang: localizationLanguage, data: data });
  4374. } else {
  4375. // 如果本地有数据,检查是否已经在当前会话中尝试过更新
  4376. const sessionKey = `ojb_updateL10nWebsiteJson_${localizationLanguage}`;
  4377. if (!OJB_isSameBrowserSession(sessionKey)) {
  4378. // 如果尚未更新,则在后台更新
  4379. (async () => {
  4380. try {
  4381. const newData = await OJB_getExternalJSON(url);
  4382. await OJBetter.common.database.localizeSubsData.put({ lang: localizationLanguage, data: newData });
  4383. console.log("Website local data has been refreshed!");
  4384. } catch (error) {
  4385. console.error('Failed to update localization data:', error);
  4386. }
  4387. })();
  4388. }
  4389. }
  4390. return data;
  4391. }
  4392.  
  4393. /**
  4394. * 网站本地化替换
  4395. * @returns
  4396. */
  4397. async function localizeWebsite() {
  4398. if (OJBetter.localization.websiteLang === "initial") return;
  4399.  
  4400. // 设置网页语言
  4401. var htmlTag = document.getElementsByTagName("html")[0];
  4402. htmlTag.setAttribute("lang", OJBetter.localization.websiteLang);
  4403.  
  4404. // 获取网站本地化的数据
  4405. var subs = await getLocalizeWebsiteJson(OJBetter.localization.websiteLang);
  4406.  
  4407. /**
  4408. * 文本节点遍历替换
  4409. * @param {JQuery} $nodes jQuery对象
  4410. * @param {Object} textReplaceRules 文本替换规则对象
  4411. */
  4412. function traverseTextNodes($nodes, textReplaceRules) {
  4413. if (!$nodes) return;
  4414.  
  4415. $nodes.each(function () {
  4416. let node = this;
  4417. if (node.nodeType === Node.TEXT_NODE) {
  4418. Object.keys(textReplaceRules).forEach(match => {
  4419. try {
  4420. const replace = textReplaceRules[match];
  4421. const regex = new RegExp(match, 'g');
  4422. node.textContent = node.textContent.replace(regex, replace);
  4423. } catch (error) {
  4424. console.error(`Error processing text replacement for match: ${match}`, error);
  4425. }
  4426. });
  4427. } else {
  4428. $(node).contents().each(function () {
  4429. traverseTextNodes($(this), textReplaceRules);
  4430. });
  4431. }
  4432. });
  4433. }
  4434.  
  4435. /**
  4436. * value替换
  4437. * @param {JQuery} $nodes jQuery对象
  4438. * @param {Object} valueReplaceRules 值替换规则对象
  4439. */
  4440. function traverseValueNodes($nodes, valueReplaceRules) {
  4441. if (!$nodes) return;
  4442.  
  4443. $nodes.each(function () {
  4444. let $node = $(this);
  4445. if ($node.is('[value]')) {
  4446. Object.keys(valueReplaceRules).forEach(match => {
  4447. const replace = valueReplaceRules[match];
  4448. const regex = new RegExp(match, 'g');
  4449. let currentValue = $node.val();
  4450. let newValue = currentValue.replace(regex, replace);
  4451. $node.val(newValue);
  4452. });
  4453. } else {
  4454. $node.children().each(function () {
  4455. traverseValueNodes($(this), valueReplaceRules);
  4456. });
  4457. }
  4458. });
  4459. }
  4460.  
  4461. /**
  4462. * 严格的文本节点遍历替换
  4463. * @param {JQuery} $node jQuery对象
  4464. * @param {Object} textReplaceRules 文本替换规则对象
  4465. */
  4466. function strictTraverseTextNodes($nodes, textReplaceRules) {
  4467. if (!$nodes) return;
  4468.  
  4469. $nodes.each(function () {
  4470. let $node = $(this);
  4471. if ($node.nodeType === Node.TEXT_NODE) {
  4472. const trimmedNodeText = $node.textContent.trim();
  4473. Object.keys(textReplaceRules).forEach(match => {
  4474. if (trimmedNodeText === match) {
  4475. $node.textContent = textReplaceRules[match];
  4476. }
  4477. });
  4478. } else {
  4479. $($node).contents().each(function () {
  4480. strictTraverseTextNodes($(this), textReplaceRules);
  4481. });
  4482. }
  4483. });
  4484. }
  4485.  
  4486. /**
  4487. * 应用文本替换
  4488. */
  4489. let commonReplacements = subs.commonReplacements;
  4490. Object.entries(commonReplacements).forEach(([key, value]) => {
  4491. const classSelectors = Array.isArray(value.class) ? value.class : [value.class]; // 兼容,class的值可以为数组或者字符串
  4492. classSelectors.forEach(classSelector => {
  4493. if (value.isStrict) {
  4494. strictTraverseTextNodes(OJB_safeCreateJQElement(`${classSelector}`), value.rules);
  4495. } else {
  4496. traverseTextNodes(OJB_safeCreateJQElement(`${classSelector}`), value.rules);
  4497. }
  4498. });
  4499. });
  4500.  
  4501. // 测试
  4502. {
  4503. // var translations = {
  4504. //
  4505. // };
  4506. // traverseTextNodes($('xxx'), translations);
  4507. };
  4508.  
  4509. /**
  4510. * 应用value替换
  4511. */
  4512. let InputValueReplacements = subs.InputValueReplacements;
  4513. Object.entries(InputValueReplacements).forEach(([key, value]) => {
  4514. const classSelectors = Array.isArray(value.class) ? value.class : [value.class];
  4515. classSelectors.forEach(classSelector => {
  4516. traverseValueNodes(OJB_safeCreateJQElement(`${classSelector}`), value.rules);
  4517. });
  4518. });
  4519.  
  4520. // // 杂项
  4521. // (function () {
  4522. // // 选项汉化input[type="radio"]
  4523. // var translations = {
  4524. // "as individual participant": "个人",
  4525. // "as a team member": "作为一个团队成员",
  4526. // };
  4527. // $('input[type="radio"]').each(function () {
  4528. // var tag = $(this).parent().contents().filter(function () {
  4529. // return this.nodeType === Node.TEXT_NODE;
  4530. // });
  4531. // for (var i = 0; i < tag.length; i++) {
  4532. // var text = tag[i].textContent.trim();
  4533. // if (translations.hasOwnProperty(text)) {
  4534. // $(this).addClass(text);
  4535. // tag[i].replaceWith(translations[text]);
  4536. // break;
  4537. // }
  4538. // }
  4539. // });
  4540. // })();
  4541. // (function () {
  4542. // var translations = {
  4543. // "(standard input\/output)": "标准输入/输出",
  4544. // };
  4545. // $("div.notice").each(function () {
  4546. // var tag = $(this).children().eq(0).text();
  4547. // for (var property in translations) {
  4548. // if (tag.match(property)) {
  4549. // $(this).children().eq(0).text(translations[property]);
  4550. // break;
  4551. // }
  4552. // }
  4553. // });
  4554. // })();
  4555.  
  4556. // // 轻量站特殊
  4557. // if (OJBetter.typeOfPage.is_mSite) {
  4558. // traverseTextNodes($('nav'), commonReplacements['.second-level-menu']['rules']);
  4559. // }
  4560. // if (OJBetter.typeOfPage.is_mSite) {
  4561. // (function () {
  4562. // var translations = {
  4563. // "Announcements": "公告",
  4564. // "Submissions": "提交记录",
  4565. // "Contests": "比赛",
  4566. // };
  4567. // $(".caption").each(function () {
  4568. // var optionValue = $(this).text();
  4569. // if (translations[optionValue]) {
  4570. // $(this).text(translations[optionValue]);
  4571. // }
  4572. // });
  4573. // })();
  4574. // }
  4575. };
  4576.  
  4577. /**
  4578. * i18next初始化
  4579. */
  4580. async function initI18next() {
  4581. return new Promise((resolve, reject) => {
  4582. i18next
  4583. .use(i18nextChainedBackend)
  4584. .init({
  4585. lng: OJBetter.localization.scriptLang,
  4586. ns: ['common', 'settings', 'config', 'dialog', 'alert', 'translator',
  4587. 'button', 'codeEditor', 'comments', 'announce', 'logMessage'], // 命名空间列表
  4588. defaultNS: 'settings',
  4589. fallbackLng: ['zh', OJBetter.translation.targetLang],
  4590. load: 'currentOnly',
  4591. debug: false,
  4592. backend: {
  4593. backends: [
  4594. i18nextLocalStorageBackend,
  4595. i18nextHttpBackend
  4596. ],
  4597. backendOptions: [{
  4598. prefix: 'i18next_res_',
  4599. expirationTime: 7 * 24 * 60 * 60 * 1000,
  4600. defaultVersion: `v${OJBetter.state.version}`,
  4601. store: typeof window !== 'undefined' ? window.localStorage : null
  4602. }, {
  4603. /* options for secondary backend */
  4604. loadPath: (lng, ns) => {
  4605. if (lng[0] === 'zh' || lng[0] === 'zh-Hans') {
  4606. return `https://aowuucdn.oss-accelerate.aliyuncs.com/resources/locales/${OJBetter.state.formatName}/${ns}.json`;
  4607. }
  4608. return `https://aowuucdn.oss-accelerate.aliyuncs.com/i18n/${lng}/resources/locales/${OJBetter.state.formatName}/${ns}.json`;
  4609. }
  4610. }]
  4611. }
  4612. }, (err, t) => {
  4613. if (err) {
  4614. reject(err);
  4615. } else {
  4616. jqueryI18next.init(i18next, $, {
  4617. useOptionsAttr: true
  4618. });
  4619. resolve(t);
  4620. }
  4621. });
  4622. });
  4623. };
  4624.  
  4625. /**
  4626. * 抽象命令类
  4627. */
  4628. class Command {
  4629. execute() { }
  4630. undo() { }
  4631. }
  4632.  
  4633. /**
  4634. * 命令调用者
  4635. */
  4636. class CommandInvoker {
  4637. constructor() {
  4638. this.history = [];
  4639. }
  4640.  
  4641. /**
  4642. * 执行命令
  4643. * @param {Command} command 命令对象
  4644. */
  4645. execute(command) {
  4646. this.history.push(command);
  4647. command.execute();
  4648. }
  4649.  
  4650. /**
  4651. * 撤销命令
  4652. */
  4653. undo() {
  4654. const command = this.history.pop();
  4655. if (command) {
  4656. command.undo();
  4657. }
  4658. }
  4659. }
  4660.  
  4661. /**
  4662. * 接收者
  4663. */
  4664. class DOMContainer {
  4665. /**
  4666. * @param {JQueryObject} element 容器对象
  4667. */
  4668. constructor(element) {
  4669. this.containerElement = element;
  4670. }
  4671.  
  4672. /**
  4673. * 添加元素
  4674. * @param {JQueryObject} element 元素对象
  4675. * @returns {JQueryObject} 添加的元素对象
  4676. */
  4677. add(element) {
  4678. this.containerElement.append(element);
  4679. return this.containerElement.children().last();
  4680. }
  4681.  
  4682. /**
  4683. * 删除元素
  4684. * @param {JQueryObject} element 元素对象
  4685. */
  4686. remove(element) {
  4687. $(element).remove();
  4688. }
  4689. }
  4690.  
  4691. /**
  4692. * 具体命令类:添加元素
  4693. */
  4694. class AddElementCommand extends Command {
  4695. /**
  4696. * @param {DOMContainer} receiver 接收者
  4697. * @param {JQueryObject} element 元素对象
  4698. */
  4699. constructor(receiver, element) {
  4700. super();
  4701. this.receiver = receiver;
  4702. this.element = element;
  4703. this.addedElement = null;
  4704. }
  4705.  
  4706. execute() {
  4707. this.addedElement = this.receiver.add(this.element);
  4708. }
  4709.  
  4710. undo() {
  4711. if (this.addedElement) {
  4712. this.receiver.remove(this.addedElement);
  4713. }
  4714. }
  4715. }
  4716.  
  4717. /**
  4718. * 具体命令类:删除元素
  4719. */
  4720. class RemoveElementCommand extends Command {
  4721. /**
  4722. * @param {DOMContainer} receiver 接收者
  4723. * @param {JQueryObject} element 元素对象
  4724. */
  4725. constructor(receiver, element) {
  4726. super();
  4727. this.receiver = receiver;
  4728. this.element = element;
  4729. this.parent = $(element).parent();
  4730. this.nextSibling = $(element).next();
  4731. }
  4732.  
  4733. execute() {
  4734. this.receiver.remove(this.element);
  4735. }
  4736.  
  4737. undo() {
  4738. if (this.nextSibling.length > 0) {
  4739. $(this.element).insertBefore(this.nextSibling);
  4740. } else {
  4741. this.parent.append(this.element);
  4742. }
  4743. }
  4744. }
  4745.  
  4746. /**
  4747. * 验证器
  4748. */
  4749. class Validator {
  4750. /**
  4751. * 表单必填项空值校验
  4752. */
  4753. static required(structure) {
  4754. let config = {};
  4755. let allFieldsValid = true;
  4756. for (const key in structure) {
  4757. let value = key.type == 'checkbox' ?
  4758. $(key).prop("checked") : $(key).val();
  4759.  
  4760. config[structure[key].value] = value;
  4761.  
  4762. if (value || structure[key].require === false) {
  4763. $(key).removeClass('is_null');
  4764. } else {
  4765. $(key).addClass('is_null');
  4766. allFieldsValid = false;
  4767. }
  4768. }
  4769. return {
  4770. valid: allFieldsValid,
  4771. config: config
  4772. };
  4773. }
  4774.  
  4775. /**
  4776. * 表单合法性校验
  4777. */
  4778. static checkKeyValuePairs(structure, config) {
  4779. let errorKeys = [];
  4780. let allFieldsValid = true;
  4781.  
  4782. for (const key in structure) {
  4783. const { check, value } = structure[key];
  4784. const fieldValue = config[value];
  4785.  
  4786. // 如果字段没有值或校验类型不匹配,则跳过当前迭代
  4787. if (!fieldValue) continue;
  4788.  
  4789. let isValid = true;
  4790. switch (check) {
  4791. case 'keyValuePairs':
  4792. isValid = Validator.keyValuePairs(fieldValue);
  4793. break;
  4794. case 'dotSeparatedPath':
  4795. isValid = Validator.validateDotSeparatedPath(fieldValue);
  4796. break;
  4797. default:
  4798. // 没有匹配的校验类型
  4799. continue;
  4800. }
  4801.  
  4802. Validator.toggleErrorDisplay(key, isValid);
  4803. if (!isValid) {
  4804. allFieldsValid = false;
  4805. errorKeys.push(key);
  4806. }
  4807. }
  4808.  
  4809. return {
  4810. valid: allFieldsValid,
  4811. errorKeys: errorKeys
  4812. };
  4813. }
  4814.  
  4815. /**
  4816. * 切换错误信息的显示和隐藏
  4817. * @param {string} key - 字段的键
  4818. * @param {boolean} isValid - 字段值是否有效
  4819. */
  4820. static toggleErrorDisplay(key, isValid) {
  4821. const errorMessage = i18next.t('common.unValid', { ns: 'settings' });
  4822. const $errorSpan = $(key).prev('span.text-error');
  4823. if (!isValid) {
  4824. if (!$errorSpan.length) {
  4825. $(key).before(`<span class="text-error" style="color: red;">${errorMessage}</span>`);
  4826. }
  4827. } else {
  4828. $errorSpan.remove();
  4829. }
  4830. }
  4831.  
  4832. /**
  4833. * 键值对合法性校验
  4834. * @param {string} value
  4835. * @returns {boolean}
  4836. */
  4837. static keyValuePairs(value) {
  4838. const keyValuePairs = value.split('\n');
  4839. // 允许值中包含空格和冒号
  4840. const regex = /^[a-zA-Z0-9_-]+\s*:\s*.+$/;
  4841. return keyValuePairs.every(pair => regex.test(pair));
  4842. }
  4843.  
  4844.  
  4845. /**
  4846. * 点分隔符路径格式校验,允许加减运算
  4847. * @param {string} path
  4848. * @returns {boolean}
  4849. */
  4850. static validateDotSeparatedPath(path) {
  4851. // 正则表达式允许标识符之间有点号,标识符可以包含加减运算
  4852. const regex = /^([a-zA-Z0-9_-]+(\s*[\+\-]\s*[a-zA-Z0-9_-]+)*\.)*([a-zA-Z0-9_-]+(\s*[\+\-]\s*[a-zA-Z0-9_-]+)*)$/;
  4853. return regex.test(path);
  4854. }
  4855. }
  4856.  
  4857. /**
  4858. * 配置管理
  4859. */
  4860. class ConfigManager {
  4861. /**
  4862. * @param {HTMLElement} element - 挂载容器
  4863. * @param {string} prefix - 前缀
  4864. * @param {object} tempConfig - 配置内容
  4865. * @param {object} structure - 配置结构
  4866. * @param {object} configHTML - 配置编辑页面HTML
  4867. * @param {boolean} allowChoice - 是否允许选择列表项
  4868. */
  4869. constructor(element, prefix, tempConfig, structure, configHTML, allowChoice = true) {
  4870. /** @param 设置面板DIV */
  4871. this.settingMenuDiv = $('#OJBetter_setting_menu');
  4872. this.element = $(element);
  4873. this.prefix = prefix;
  4874. this.tempConfig = tempConfig;
  4875. this.structure = structure;
  4876. this.configHTML = configHTML;
  4877. this.allowChoice = allowChoice;
  4878.  
  4879. this.controlTip = null;
  4880. this.config_bar_list = null;
  4881. this.config_bar_ul = null;
  4882. this.config_add_button = null;
  4883. this.menu = null;
  4884. this.editItem = null;
  4885. this.deleteItem = null;
  4886.  
  4887. // 绑定方法
  4888. this.onAdd = this.onAdd.bind(this);
  4889. this.onEdit = this.onEdit.bind(this);
  4890. this.onDelete = this.onDelete.bind(this);
  4891. this.createListItemElement = this.createListItemElement.bind(this);
  4892.  
  4893. this.lastItemId = 0; // 列表中当前最后一个元素的id号
  4894. this.init();
  4895. }
  4896.  
  4897. init() {
  4898. this.createControlBar();
  4899. this.createContextMenu();
  4900. this.renderList();
  4901. }
  4902.  
  4903. /**
  4904. * 创建控制栏
  4905. */
  4906. createControlBar() {
  4907. this.controlTip = OJB_safeCreateJQElement(`<div id='${this.prefix}configControlTip' style='color:red;'></div>`);
  4908. this.config_bar_list = OJB_safeCreateJQElement(`<div class='config_bar_list' id='${this.prefix}config_bar_list'></div>`);
  4909. this.config_bar_ul = OJB_safeCreateJQElement(`<ul class='config_bar_ul' id='${this.prefix}config_bar_ul'></ul>`);
  4910. this.element.append(this.controlTip);
  4911. this.element.append(this.config_bar_list);
  4912. this.config_bar_list.append(this.config_bar_ul);
  4913. }
  4914.  
  4915. /**
  4916. * 创建右键菜单
  4917. */
  4918. createContextMenu() {
  4919. const menu = OJB_safeCreateJQElement(`<div id='config_bar_menu' style='display: none;'></div>`);
  4920. const editItem = OJB_safeCreateJQElement(`
  4921. <div class='config_bar_menu_item' id='config_bar_menu_edit'>
  4922. ${i18next.t('contextMenu.edit', { ns: 'translator' })}
  4923. </div>`);
  4924. const deleteItem = OJB_safeCreateJQElement(`
  4925. <div class='config_bar_menu_item' id='config_bar_menu_delete'>
  4926. ${i18next.t('contextMenu.delete', { ns: 'translator' })}
  4927. </div>`);
  4928. menu.append(editItem);
  4929. menu.append(deleteItem);
  4930. this.editItem = editItem;
  4931. this.deleteItem = deleteItem;
  4932. this.menu = menu;
  4933. this.settingMenuDiv.append(menu);
  4934. }
  4935.  
  4936. /**
  4937. * 关闭右键菜单
  4938. */
  4939. closeContextMenu() {
  4940. this.menu.css({ display: "none" });
  4941. }
  4942.  
  4943. /**
  4944. * 创建列表项
  4945. * @param {string} text - 列表项文本
  4946. * @returns {HTMLElement} - 列表项
  4947. */
  4948. createListItemElement(text) {
  4949. const id = OJB_getRandomNumber(4);
  4950. const li = $("<li></li>");
  4951. const radio = OJB_safeCreateJQElement(`<input type='radio' name='${this.prefix}config_item'></input>`)
  4952. .attr("value", text)
  4953. .attr("id", id)
  4954. .attr("prev_id", this.lastItemId)
  4955. .appendTo(li);
  4956. if (!this.allowChoice) {
  4957. radio.prop("disabled", true);
  4958. }
  4959. const label = OJB_safeCreateJQElement(`<label for='${id}' class='config_bar_ul_li_text'>${text}</label>`).appendTo(li);
  4960.  
  4961.  
  4962. this.lastItemId = id;
  4963.  
  4964. // 添加右键菜单
  4965. li.on("contextmenu", (event) => {
  4966. event.preventDefault();
  4967. this.menu.css({
  4968. display: "block",
  4969. left: event.pageX, top: event.pageY
  4970. });
  4971.  
  4972. const deleteItem = this.deleteItem;
  4973. const editItem = this.editItem;
  4974.  
  4975. // 移除旧事件
  4976. deleteItem.off("click");
  4977. editItem.off("click");
  4978.  
  4979. // 获取 li 在 ul 中的索引
  4980. const index = li.index();
  4981.  
  4982. deleteItem.on("click", () => this.onDelete(index, li));
  4983. editItem.on("click", () => this.onEdit(index, li));
  4984.  
  4985. $(document).one("click", (event) => {
  4986. if (!this.menu.get(0).contains(event.target)) {
  4987. this.closeContextMenu();
  4988. deleteItem.off("click", () => this.onDelete);
  4989. editItem.off("click", () => this.onEdit);
  4990. }
  4991. });
  4992. });
  4993.  
  4994. return li;
  4995. }
  4996.  
  4997. /**
  4998. * 渲染配置列表
  4999. */
  5000. renderList() {
  5001. const list = this.config_bar_ul;
  5002. list.empty(); // 清空
  5003. this.tempConfig.configurations.forEach((item) => {
  5004. list.append(this.createListItemElement(item['name']));
  5005. });
  5006.  
  5007. // 添加按钮
  5008. let addButton = OJB_safeCreateJQElement(`<li id='${this.prefix}add_button' class="tempConfig_add_button">
  5009. <span>+ ${i18next.t('add', { ns: 'common' })}</span>
  5010. </li>`);
  5011. this.config_add_button = addButton;
  5012. list.append(addButton);
  5013. addButton.on("click", this.onAdd);
  5014. }
  5015.  
  5016. /**
  5017. * 添加配置项
  5018. */
  5019. onAdd() {
  5020. const configMenu = this.createConfigHTML();
  5021. const structure = this.structure;
  5022.  
  5023. configMenu.on("click", "#tempConfig_save", () => {
  5024.  
  5025. // 检查必填字段
  5026. const { valid, config } = Validator.required(structure);
  5027. if (!valid) return;
  5028.  
  5029. // 检查键值对
  5030. const { valid: checkOk, errorKey } = Validator.checkKeyValuePairs(structure, config);
  5031. if (!checkOk) return;
  5032.  
  5033. this.tempConfig.configurations.push(config);
  5034.  
  5035. this.createListItemElement(config.name).insertBefore(this.config_add_button);
  5036.  
  5037. configMenu.remove();
  5038. });
  5039.  
  5040. configMenu.on("click", ".btn-close", () => {
  5041. configMenu.remove();
  5042. });
  5043. }
  5044.  
  5045. /**
  5046. * 修改配置项
  5047. * @param {number} index - 配置项索引
  5048. * @param {HTMLElement} li - 配置项
  5049. * @returns {void}
  5050. */
  5051. onEdit(index, li) {
  5052. const configMenu = this.createConfigHTML();
  5053. const structure = this.structure;
  5054.  
  5055. this.closeContextMenu();
  5056.  
  5057. // 填充表单
  5058. for (const [key, { value, type }] of Object.entries(this.structure)) {
  5059. const configValue = this.tempConfig.configurations[index][value];
  5060. const $element = $(key);
  5061. if (type === 'checkbox') {
  5062. $element.prop("checked", configValue);
  5063. } else {
  5064. $element.val(configValue);
  5065. }
  5066. }
  5067.  
  5068. configMenu.on("click", "#tempConfig_save", () => {
  5069. // 检查必填字段
  5070. const { valid, config } = Validator.required(structure);
  5071. if (!valid) return;
  5072.  
  5073. // 检查键值对
  5074. const { valid: checkOk, errorKey } = Validator.checkKeyValuePairs(structure, config);
  5075. if (!checkOk) return;
  5076.  
  5077. // 更新配置
  5078. this.tempConfig.configurations[index] = config;
  5079. li.find('label').text(config.name);
  5080.  
  5081. OJB_closeAndRemoveModal(configMenu);
  5082. });
  5083.  
  5084. configMenu.on("click", ".btn-close", () => {
  5085. OJB_closeAndRemoveModal(configMenu);
  5086. });
  5087. }
  5088.  
  5089. /**
  5090. * 删除配置项
  5091. * @param {number} index - 配置项索引
  5092. * @param {HTMLElement} li - 配置项
  5093. * @returns {void}
  5094. */
  5095. onDelete(index, li) {
  5096. this.closeContextMenu();
  5097. this.tempConfig.configurations.splice(index, 1);
  5098. li.remove();
  5099. }
  5100.  
  5101. /**
  5102. * 创建配置编辑页面
  5103. * @returns {JQuery<HTMLElement>} 返回配置编辑页面
  5104. */
  5105. createConfigHTML() {
  5106. const configMenu = OJB_safeCreateJQElement(this.configHTML);
  5107. this.settingMenuDiv.after(configMenu);
  5108. OJB_showModal(configMenu);
  5109. OJB_addDraggable(configMenu);
  5110. elementLocalize(configMenu);
  5111. return configMenu;
  5112. }
  5113.  
  5114. /**
  5115. * 获取配置内容
  5116. * @returns {object} - 配置内容
  5117. */
  5118. getTempConfig() {
  5119. return this.tempConfig;
  5120. }
  5121.  
  5122. /**
  5123. * 注册列表项选中改变监听
  5124. */
  5125. registerChoiceChange() {
  5126. this.config_bar_ul.on("change", "input[type='radio']", (event) => {
  5127. const value = event.target.value;
  5128. this.tempConfig.choice = value;
  5129. });
  5130. }
  5131. }
  5132.  
  5133. const OJBetter_setting_sidebar_HTML = `
  5134. <div class="OJBetter_setting_sidebar">
  5135. <ul>
  5136. <li><a href="#basic-settings" id="sidebar-basic-settings" class="active" data-i18n="settings:sidebar.basic"></a></li>
  5137. <li><a href="#l10n_settings" id="sidebar-l10n_settings" data-i18n="settings:sidebar.localization"></a></li>
  5138. <li><a href="#translation-settings" id="sidebar-translation-settings" data-i18n="settings:sidebar.translation"></a></li>
  5139. <li><a href="#clist_rating-settings" id="sidebar-clist_rating-settings" data-i18n="settings:sidebar.clist"></a></li>
  5140. <li><a href="#code_editor-settings" id="sidebar-code_editor-settings" data-i18n="settings:sidebar.monaco"></a></li>
  5141. <li><a href="#preference-settings" id="sidebar-preference-settings" data-i18n="settings:sidebar.preference"></a></li>
  5142. <li><a href="#dev-settings" id="sidebar-dev-settings" data-i18n="settings:sidebar.dev"></a></li>
  5143. <li><a href="#about-settings" id="sidebar-about-settings" data-i18n="settings:sidebar.about"></a></li>
  5144. </ul>
  5145. </div>
  5146. `;
  5147.  
  5148. const basic_settings_HTML = `
  5149. <div id="basic-settings" class="settings-page active">
  5150. <h3 data-i18n="settings:basic.title"></h3>
  5151. <hr>
  5152. <div class='OJBetter_setting_list' style="padding: 0px 10px;">
  5153. <span id="darkMode_span" data-i18n="settings:basic.darkMode.name"></span>
  5154. <div class="dark-mode-selection">
  5155. <label>
  5156. <input class="radio-input" type="radio" name="darkMode" value="dark" />
  5157. <span class="OJBetter_setting_menu_label_text"
  5158. data-i18n="settings:basic.darkMode.options.dark"></span>
  5159. <span class="radio-icon"> </span>
  5160. </label>
  5161. <label>
  5162. <input checked="" class="radio-input" type="radio" name="darkMode" value="light" />
  5163. <span class="OJBetter_setting_menu_label_text"
  5164. data-i18n="settings:basic.darkMode.options.light"></span>
  5165. <span class="radio-icon"> </span>
  5166. </label>
  5167. <label>
  5168. <input class="radio-input" type="radio" name="darkMode" value="follow" />
  5169. <span class="OJBetter_setting_menu_label_text"
  5170. data-i18n="settings:basic.darkMode.options.system"></span>
  5171. <span class="radio-icon"> </span>
  5172. </label>
  5173. </div>
  5174. </div>
  5175. <div class='OJBetter_setting_list' style="display:none;">
  5176. <label for="expandFoldingblocks" data-i18n="settings:basic.expandBlocks"></label>
  5177. <input type="checkbox" id="expandFoldingblocks" name="expandFoldingblocks">
  5178. </div>
  5179. <div class='OJBetter_setting_list' style="display:none;">
  5180. <label for="renderPerfOpt" data-i18n="settings:basic.renderOptimization.label"></label>
  5181. <div class="help_tip">
  5182. ${helpCircleHTML}
  5183. <div class="tip_text" data-i18n="[html]settings:basic.renderOptimization.helpText"></div>
  5184. </div>
  5185. <input type="checkbox" id="renderPerfOpt" name="renderPerfOpt">
  5186. </div>
  5187. <div class='OJBetter_setting_list' style="display:none;">
  5188. <label for="commentPaging" data-i18n="settings:basic.paging.label"></label>
  5189. <div class="help_tip">
  5190. ${helpCircleHTML}
  5191. <div class="tip_text" data-i18n="[html]settings:basic.paging.helpText"></div>
  5192. </div>
  5193. <input type="checkbox" id="commentPaging" name="commentPaging">
  5194. </div>
  5195. <div class='OJBetter_setting_list'>
  5196. <label for="showJumpToLuogu" data-i18n="settings:basic.luoguJump.label"></label>
  5197. <div class="help_tip">
  5198. ${helpCircleHTML}
  5199. <div class="tip_text" data-i18n="[html]settings:basic.luoguJump.helpText"></div>
  5200. </div>
  5201. <input type="checkbox" id="showJumpToLuogu" name="showJumpToLuogu">
  5202. </div>
  5203. <div class='OJBetter_setting_list'>
  5204. <label for="showCF2vjudge" data-i18n="settings:basic.vjudgeJump.label"></label>
  5205. <div class="help_tip">
  5206. ${helpCircleHTML}
  5207. <div class="tip_text" data-i18n="[html]settings:basic.vjudgeJump.helpText"></div>
  5208. </div>
  5209. <input type="checkbox" id="showCF2vjudge" name="showCF2vjudge">
  5210. </div>
  5211. <div class='OJBetter_setting_list' style="display:none;">
  5212. <label for="standingsRecolor" data-i18n="settings:basic.recolor.label"></label>
  5213. <div class="help_tip">
  5214. ${helpCircleHTML}
  5215. <div class="tip_text" data-i18n="[html]settings:basic.recolor.helpText"></div>
  5216. </div>
  5217. <input type="checkbox" id="standingsRecolor" name="standingsRecolor">
  5218. </div>
  5219. </div>
  5220. `;
  5221.  
  5222. const l10n_settings_HTML = `
  5223. <div id="l10n_settings" class="settings-page">
  5224. <h3 data-i18n="settings:localization.title"></h3>
  5225. <hr>
  5226. <div class='OJBetter_setting_list'>
  5227. <label for="scriptL10nLanguage" style="display: flex;" data-i18n="settings:localization.scriptLanguageLabel"></label>
  5228. <select id="scriptL10nLanguage" name="scriptL10nLanguage">
  5229. <option value="zh">简体中文</option>
  5230. <option value="zh-Hant">繁體中文</option>
  5231. <option value="en">English</option>
  5232. <option value="de">Deutsch</option>
  5233. <option value="fr">Français</option>
  5234. <option value="ko">한국어</option>
  5235. <option value="pt">Português</option>
  5236. <option value="ja">日本語</option>
  5237. <option value="es">Español</option>
  5238. <option value="it">Italiano</option>
  5239. <option value="hi">हिन्दी</option>
  5240. </select>
  5241. </div>
  5242. <div class='OJBetter_setting_list'>
  5243. <label for="localizationLanguage" style="display: flex;" data-i18n="settings:localization.websiteLanguageLabel"></label>
  5244. <select id="localizationLanguage" name="localizationLanguage">
  5245. <option value="initial">——</option>
  5246. <option value="zh">简体中文</option>
  5247. <option value="zh-Hant">繁體中文</option>
  5248. <option value="de">Deutsch</option>
  5249. <option value="fr">Français</option>
  5250. <option value="ko">한국어</option>
  5251. <option value="pt">Português</option>
  5252. <option value="ja">日本語</option>
  5253. <option value="es">Español</option>
  5254. <option value="it">Italiano</option>
  5255. <option value="hi">हिन्दी</option>
  5256. </select>
  5257. </div>
  5258. <div class='OJBetter_setting_list alert_tip'>
  5259. <div data-i18n="[html]settings:localization.notice.1"></div>
  5260. </div>
  5261. <div class='OJBetter_setting_list alert_tip'>
  5262. <div data-i18n="[html]settings:localization.notice.2"></div>
  5263. </div>
  5264. </div>
  5265. `;
  5266.  
  5267. const translation_settings_HTML = `
  5268. <div id="translation-settings" class="settings-page">
  5269. <h3 data-i18n="settings:translation.title"></h3>
  5270. <hr>
  5271. <h4 data-i18n="settings:translation.options.title"></h4>
  5272. <div class='OJBetter_setting_list'>
  5273. <label for="transTargetLang" style="display: flex;" data-i18n="settings:translation.preference.target.title"></label>
  5274. <div class="help_tip">
  5275. ${helpCircleHTML}
  5276. <div class="tip_text" data-i18n="[html]settings:translation.preference.target.helpText"></div>
  5277. </div>
  5278. <select id="transTargetLang" name="transTargetLang">
  5279. <option value="zh">简体中文</option>
  5280. <option value="zh-Hant">繁體中文</option>
  5281. <option value="de">Deutsch</option>
  5282. <option value="fr">Français</option>
  5283. <option value="ko">한국어</option>
  5284. <option value="pt">Português</option>
  5285. <option value="ja">日本語</option>
  5286. <option value="es">Español</option>
  5287. <option value="it">Italiano</option>
  5288. <option value="hi">हिन्दी</option>
  5289. </select>
  5290. </div>
  5291. <div id="translationServices">
  5292. <label>
  5293. <input type='radio' name='translation' value='deepl'>
  5294. <span class='OJBetter_setting_menu_label_text'
  5295. data-i18n="settings:translation.options.services.deepl"></span>
  5296. </label>
  5297. <label>
  5298. <input type='radio' name='translation' value='iflyrec'>
  5299. <span class='OJBetter_setting_menu_label_text'
  5300. data-i18n="settings:translation.options.services.iflyrec"></span>
  5301. </label>
  5302. <label>
  5303. <input type='radio' name='translation' value='youdao'>
  5304. <span class='OJBetter_setting_menu_label_text'
  5305. data-i18n="settings:translation.options.services.youdao"></span>
  5306. </label>
  5307. <label>
  5308. <input type='radio' name='translation' value='google'>
  5309. <span class='OJBetter_setting_menu_label_text'
  5310. data-i18n="settings:translation.options.services.google"></span>
  5311. </label>
  5312. <label>
  5313. <input type='radio' name='translation' value='caiyun'>
  5314. <span class='OJBetter_setting_menu_label_text'
  5315. data-i18n="settings:translation.options.services.caiyun"></span>
  5316. </label>
  5317. <label>
  5318. <input type='radio' name='translation' value='openai'>
  5319. <span class='OJBetter_setting_menu_label_text'
  5320. data-i18n="settings:translation.options.services.openai.name">
  5321. <div class="help_tip">
  5322. ${helpCircleHTML}
  5323. <div class="tip_text"
  5324. data-i18n="[html]settings:translation.options.services.openai.helpText"></div>
  5325. </div>
  5326. </span>
  5327. </label>
  5328. </div>
  5329. <hr>
  5330. <h4>DeepL</h4>
  5331. <div class='OJBetter_setting_list'>
  5332. <label for="deepl_type" style="display: flex;" data-i18n="settings:translation.deepl.mode.title"></label>
  5333. <div class="help_tip">
  5334. ${helpCircleHTML}
  5335. <div class="tip_text" data-i18n="[html]settings:translation.deepl.mode.helpText"></div>
  5336. </div>
  5337. <select id="deepl_type" name="deepl_type">
  5338. <option value="free" data-i18n="settings:translation.deepl.mode.select.free"></option>
  5339. <option value="api" data-i18n="settings:translation.deepl.mode.select.api"></option>
  5340. </select>
  5341. </div>
  5342. <div id="deepl_config" class="config"></div>
  5343. <div class='OJBetter_setting_list'>
  5344. <label for="enableEmphasisProtection" data-i18n="settings:translation.deepl.enableEmphasisProtection.title"></label>
  5345. <div class="help_tip" style="margin-right: initial;">
  5346. ${helpCircleHTML}
  5347. <div class="tip_text" data-i18n="[html]settings:translation.deepl.enableEmphasisProtection.helpText"></div>
  5348. </div>
  5349. <div class="badge">Official API Only</div>
  5350. <input type="checkbox" id="enableEmphasisProtection" name="enableEmphasisProtection">
  5351. </div>
  5352. <div class='OJBetter_setting_list'>
  5353. <label for="enableLinkProtection" data-i18n="settings:translation.deepl.enableLinkProtection.title"></label>
  5354. <div class="help_tip" style="margin-right: initial;">
  5355. ${helpCircleHTML}
  5356. <div class="tip_text" data-i18n="[html]settings:translation.deepl.enableLinkProtection.helpText"></div>
  5357. </div>
  5358. <div class="badge">Official API Only</div>
  5359. <input type="checkbox" id="enableLinkProtection" name="enableLinkProtection">
  5360. </div>
  5361. <hr>
  5362. <h4>ChatGPT</h4>
  5363. <div id="chatgpt_config" class="config"></div>
  5364. <div class='OJBetter_setting_list'>
  5365. <label for="openai_isStream" data-i18n="settings:translation.chatgpt.isStream.name"></label>
  5366. <div class="help_tip">
  5367. ${helpCircleHTML}
  5368. <div class="tip_text" data-i18n="[html]settings:translation.chatgpt.isStream.helpText"></div>
  5369. </div>
  5370. <input type="checkbox" id="openai_isStream" name="openai_isStream">
  5371. </div>
  5372. <hr>
  5373. <h4 data-i18n="settings:translation.preference.title"></h4>
  5374. <div class='OJBetter_setting_list'>
  5375. <label for="comment_translation_choice" style="display: flex;"
  5376. data-i18n="settings:translation.preference.comment_translation_choice.title">
  5377. </label>
  5378. <select id="comment_translation_choice" name="comment_translation_choice">
  5379. <option value="0" data-i18n="settings:translation.preference.comment_translation_choice.services.follow"></option>
  5380. <option value="deepl" data-i18n="settings:translation.preference.comment_translation_choice.services.deepl"></option>
  5381. <option value="iflyrec" data-i18n="settings:translation.preference.comment_translation_choice.services.iflyrec"></option>
  5382. <option value="youdao" data-i18n="settings:translation.preference.comment_translation_choice.services.youdao"></option>
  5383. <option value="google" data-i18n="settings:translation.preference.comment_translation_choice.services.google"></option>
  5384. <option value="caiyun" data-i18n="settings:translation.preference.comment_translation_choice.services.caiyun"></option>
  5385. <option value="openai" data-i18n="settings:translation.preference.comment_translation_choice.services.openai"></option>
  5386. </select>
  5387. </div>
  5388. <hr>
  5389.  
  5390. <div style="display:none;">
  5391. <h4 data-i18n="settings:translation.autoTranslation.title"></h4>
  5392. <div class='OJBetter_setting_list'>
  5393. <label for="autoTranslation" data-i18n="settings:translation.autoTranslation.enable"></label>
  5394. <div class="help_tip">
  5395. ${helpCircleHTML}
  5396. <div class="tip_text" data-i18n="[html]settings:translation.autoTranslation.helpText"></div>
  5397. </div>
  5398. <input type="checkbox" id="autoTranslation" name="autoTranslation">
  5399. </div>
  5400. <div class='OJBetter_setting_list'>
  5401. <label for='shortTextLength'>
  5402. <div style="display: flex;align-items: center;"
  5403. data-i18n="settings:translation.autoTranslation.shortTextLength.name"></div>
  5404. </label>
  5405. <div class="help_tip">
  5406. ${helpCircleHTML}
  5407. <div class="tip_text" data-i18n="[html]settings:translation.autoTranslation.shortTextLength.helpText">
  5408. </div>
  5409. </div>
  5410. <input type='number' id='shortTextLength' class='no_default' require=true data-i18n="[placeholder]settings:translation.autoTranslation.shortTextLength.placeholder">
  5411. <span data-i18n="settings:translation.autoTranslation.shortTextLength.end"></span>
  5412. </div>
  5413. <div class='OJBetter_setting_list'>
  5414. <label for="allowMixTrans" data-i18n="settings:translation.autoTranslation.allowMixTrans.name"></label>
  5415. <div class="help_tip">
  5416. ${helpCircleHTML}
  5417. <div class="tip_text" data-i18n="[html]settings:translation.autoTranslation.allowMixTrans.helpText">
  5418. </div>
  5419. </div>
  5420. <input type="checkbox" id="allowMixTrans" name="allowMixTrans">
  5421. <div class='OJBetter_checkboxs'>
  5422. <input type="checkbox" id="deepl" name="mixedTranslation" value="deepl">
  5423. <label for="deepl" data-i18n="settings:translation.autoTranslation.allowMixTrans.checkboxs.deepl"></label>
  5424. <input type="checkbox" id="iflyrec" name="mixedTranslation" value="iflyrec">
  5425. <label for="iflyrec" data-i18n="settings:translation.autoTranslation.allowMixTrans.checkboxs.iflyrec"></label>
  5426. <input type="checkbox" id="youdao" name="mixedTranslation" value="youdao">
  5427. <label for="youdao" data-i18n="settings:translation.autoTranslation.allowMixTrans.checkboxs.youdao"></label>
  5428. <input type="checkbox" id="google" name="mixedTranslation" value="google">
  5429. <label for="google" data-i18n="settings:translation.autoTranslation.allowMixTrans.checkboxs.google">Google</label>
  5430. <input type="checkbox" id="caiyun" name="mixedTranslation" value="caiyun">
  5431. <label for="caiyun" data-i18n="settings:translation.autoTranslation.allowMixTrans.checkboxs.caiyun"></label>
  5432. </div>
  5433. </div>
  5434. <hr>
  5435. </div>
  5436.  
  5437. <h4 data-i18n="settings:translation.advanced.name"></h4>
  5438. <div class='OJBetter_setting_list'>
  5439. <label for="comment_translation_mode" style="display: flex;" data-i18n="settings:translation.advanced.mode.name"></label>
  5440. <div class="help_tip">
  5441. ${helpCircleHTML}
  5442. <div class="tip_text" data-i18n="[html]settings:translation.advanced.mode.helpText"></div>
  5443. </div>
  5444. <select id="comment_translation_mode" name="comment_translation_mode">
  5445. <option value="0" data-i18n="settings:translation.advanced.mode.options.0"></option>
  5446. <option value="1" data-i18n="settings:translation.advanced.mode.options.1"></option>
  5447. <option value="2" data-i18n="settings:translation.advanced.mode.options.2"></option>
  5448. </select>
  5449. </div>
  5450. <div class='OJBetter_setting_list'>
  5451. <label for="memoryTranslateHistory" data-i18n="settings:translation.advanced.memory.name"></label>
  5452. <div class="help_tip">
  5453. ${helpCircleHTML}
  5454. <div class="tip_text" data-i18n="[html]settings:translation.advanced.memory.helpText"></div>
  5455. </div>
  5456. <input type="checkbox" id="memoryTranslateHistory" name="memoryTranslateHistory">
  5457. </div>
  5458. <div class='OJBetter_setting_list'>
  5459. <label for="translation_retransAction" style="display: flex;" data-i18n="settings:translation.advanced.retrans.name"></label>
  5460. <div class="help_tip">
  5461. ${helpCircleHTML}
  5462. <div class="tip_text" data-i18n="[html]settings:translation.advanced.retrans.helpText"></div>
  5463. </div>
  5464. <select id="translation_retransAction" name="translation_retransAction">
  5465. <option value=0 data-i18n="settings:translation.advanced.retrans.options.0"></option>
  5466. <option value=1 data-i18n="settings:translation.advanced.retrans.options.1"></option>
  5467. </select>
  5468. </div>
  5469. <div class='OJBetter_setting_list'>
  5470. <label for='transWaitTime'>
  5471. <div style="display: flex;align-items: center;" data-i18n="settings:translation.advanced.transWaitTime.name"></div>
  5472. </label>
  5473. <div class="help_tip">
  5474. ${helpCircleHTML}
  5475. <div class="tip_text" data-i18n="[html]settings:translation.advanced.transWaitTime.helpText"></div>
  5476. </div>
  5477. <input type='number' id='transWaitTime' class='no_default' require=true data-i18n="[placeholder]settings:translation.advanced.transWaitTime.placeholder">
  5478. <span data-i18n="settings:translation.advanced.transWaitTime.end"></span>
  5479. </div>
  5480. <div class='OJBetter_setting_list'>
  5481. <label for="translation_replaceSymbol" style="display: flex;" data-i18n="settings:translation.advanced.replaceSymbol.name"></label>
  5482. <div class="help_tip">
  5483. ${helpCircleHTML}
  5484. <div class="tip_text" data-i18n="[html]settings:translation.advanced.replaceSymbol.helpText"></div>
  5485. </div>
  5486. <select id="translation_replaceSymbol" name="translation_replaceSymbol">
  5487. <option value=2 data-i18n="settings:translation.advanced.replaceSymbol.options.2"></option>
  5488. <option value=1 data-i18n="settings:translation.advanced.replaceSymbol.options.1"></option>
  5489. <option value=3 data-i18n="settings:translation.advanced.replaceSymbol.options.3"></option>
  5490. </select>
  5491. </div>
  5492. <div class='OJBetter_setting_list'>
  5493. <label for="filterTextWithoutEmphasis" data-i18n="settings:translation.advanced.filterTextWithoutEmphasis.name"></label>
  5494. <div class="help_tip">
  5495. ${helpCircleHTML}
  5496. <div class="tip_text" data-i18n="[html]settings:translation.advanced.filterTextWithoutEmphasis.helpText"></div>
  5497. </div>
  5498. <input type="checkbox" id="filterTextWithoutEmphasis" name="filterTextWithoutEmphasis">
  5499. </div>
  5500. </div>
  5501. `;
  5502.  
  5503. const clist_rating_settings_HTML = `
  5504. <div id="clist_rating-settings" class="settings-page">
  5505. <h3 data-i18n="settings:clist.title"></h3>
  5506. <hr>
  5507. <h4 data-i18n="settings:clist.basics.name"></h4>
  5508. <div class='OJBetter_setting_list alert_tip'>
  5509. <div>
  5510. <p data-i18n="[html]settings:clist.basics.notice"></p>
  5511. </div>
  5512. </div>
  5513. <div class='OJBetter_setting_list'>
  5514. <label for='clist_Authorization'>
  5515. <div style="display: flex;align-items: center;">
  5516. <span class="input_label" data-i18n="settings:clist.basics.key.title"></span>
  5517. </div>
  5518. </label>
  5519. <div class="help_tip">
  5520. ${helpCircleHTML}
  5521. <div class="tip_text" data-i18n="[html]settings:clist.basics.key.helpText"></div>
  5522. </div>
  5523. <input type='text' id='clist_Authorization' class='no_default' required="true"
  5524. data-i18n="[placeholder]settings:clist.basics.key.keyPlaceholder">
  5525. </div>
  5526. <hr>
  5527. <h4 data-i18n="settings:clist.displayRating.title"></h4>
  5528. <div class='OJBetter_setting_list'>
  5529. <label for="showClistRating_contest"><span data-i18n="settings:clist.displayRating.contest.name"></span></label>
  5530. <input type="checkbox" id="showClistRating_contest" name="showClistRating_contest">
  5531. </div>
  5532. <div class='OJBetter_setting_list'>
  5533. <label for="showClistRating_problem"><span data-i18n="settings:clist.displayRating.problem.name"></span></label>
  5534. <input type="checkbox" id="showClistRating_problem" name="showClistRating_problem">
  5535. </div>
  5536. <div class='OJBetter_setting_list' style='display:none;'>
  5537. <label for="showClistRating_problemset"><span data-i18n="settings:clist.displayRating.problemset.name"></span></label>
  5538. <input type="checkbox" id="showClistRating_problemset" name="showClistRating_problemset">
  5539. </div>
  5540. <hr>
  5541. <div class='OJBetter_setting_list'>
  5542. <label for="RatingHidden"><span data-i18n="settings:clist.spoilerProtection.title"></span></label>
  5543. <div class="help_tip">
  5544. ${helpCircleHTML}
  5545. <div class="tip_text" data-i18n="[html]settings:clist.spoilerProtection.helpText"></div>
  5546. </div>
  5547. <input type="checkbox" id="RatingHidden" name="RatingHidden">
  5548. </div>
  5549. </div>
  5550. `;
  5551.  
  5552. const code_editor_settings_HTML = `
  5553. <div id="code_editor-settings" class="settings-page">
  5554. <h3 data-i18n="settings:codeEditor.title"></h3>
  5555. <hr>
  5556. <h4 data-i18n="settings:codeEditor.basics"></h4>
  5557. <div class='OJBetter_setting_list'>
  5558. <label for="problemPageCodeEditor"><span
  5559. data-i18n="settings:codeEditor.problemPageCodeEditor.label"></span></label>
  5560. <div class="help_tip">
  5561. ${helpCircleHTML}
  5562. <div class="tip_text" data-i18n="settings:codeEditor.problemPageCodeEditor.helpText"></div>
  5563. </div>
  5564. <input type="checkbox" id="problemPageCodeEditor" name="problemPageCodeEditor">
  5565. </div>
  5566. <div class='OJBetter_setting_list'>
  5567. <label for="beautifyPreBlocks"><span
  5568. data-i18n="settings:codeEditor.beautifyPreBlocks.label"></span></label>
  5569. <div class="help_tip">
  5570. ${helpCircleHTML}
  5571. <div class="tip_text" data-i18n="settings:codeEditor.beautifyPreBlocks.helpText"></div>
  5572. </div>
  5573. <input type="checkbox" id="beautifyPreBlocks" name="beautifyPreBlocks">
  5574. </div>
  5575. <hr>
  5576. <h4 data-i18n="settings:codeEditor.preferences.title"></h4>
  5577. <div class='OJBetter_setting_list'>
  5578. <label for="isCodeSubmitConfirm"><span
  5579. data-i18n="settings:codeEditor.preferences.isCodeSubmitConfirm.label"></span></label>
  5580. <div class="help_tip">
  5581. ${helpCircleHTML}
  5582. <div class="tip_text" data-i18n="settings:codeEditor.preferences.isCodeSubmitConfirm.helpText"></div>
  5583. </div>
  5584. <input type="checkbox" id="isCodeSubmitConfirm" name="isCodeSubmitConfirm">
  5585. </div>
  5586. <div class='OJBetter_setting_list'>
  5587. <label for="alwaysConsumeMouseWheel"><span
  5588. data-i18n="settings:codeEditor.preferences.alwaysConsumeMouseWheel.label"></span></label>
  5589. <div class="help_tip">
  5590. ${helpCircleHTML}
  5591. <div class="tip_text" data-i18n="settings:codeEditor.preferences.alwaysConsumeMouseWheel.helpText"></div>
  5592. </div>
  5593. <input type="checkbox" id="alwaysConsumeMouseWheel" name="alwaysConsumeMouseWheel">
  5594. </div>
  5595. <div class='OJBetter_setting_list'>
  5596. <label for="submitButtonPosition"><span
  5597. data-i18n="settings:codeEditor.preferences.submitButtonPosition.label"></span></label>
  5598. <div class="help_tip">
  5599. ${helpCircleHTML}
  5600. <div class="tip_text" data-i18n="settings:codeEditor.preferences.submitButtonPosition.helpText"></div>
  5601. </div>
  5602. <select id="submitButtonPosition" name="submitButtonPosition">
  5603. <option value="bottom" data-i18n="settings:codeEditor.preferences.submitButtonPosition.options.bottom"></option>
  5604. <option value="top" data-i18n="settings:codeEditor.preferences.submitButtonPosition.options.top"></option>
  5605. </select>
  5606. </div>
  5607. <hr>
  5608. <h4 data-i18n="settings:codeEditor.onlineCodeExecution.title"></h4>
  5609. <label>
  5610. <input type='radio' name='compiler' value='official'>
  5611. <span class='OJBetter_setting_menu_label_text'
  5612. data-i18n="settings:codeEditor.onlineCodeExecution.compilerOptions.codeforces"></span>
  5613. </label>
  5614. <label>
  5615. <input type='radio' name='compiler' value='wandbox'>
  5616. <span class='OJBetter_setting_menu_label_text'
  5617. data-i18n="settings:codeEditor.onlineCodeExecution.compilerOptions.wandbox"></span>
  5618. </label>
  5619. <label>
  5620. <input type='radio' name='compiler' value='rextester'>
  5621. <span class='OJBetter_setting_menu_label_text'
  5622. data-i18n="settings:codeEditor.onlineCodeExecution.compilerOptions.rextester"></span>
  5623. </label>
  5624. <hr>
  5625. <h4 data-i18n="settings:codeEditor.lsp.title"></h4>
  5626. <div class='OJBetter_setting_list'>
  5627. <label for="useLSP"><span data-i18n="settings:codeEditor.lsp.useLSP.label"></span></label>
  5628. <div class="help_tip">
  5629. ${helpCircleHTML}
  5630. <div class="tip_text" data-i18n="[html]settings:codeEditor.lsp.useLSP.helpText"></div>
  5631. </div>
  5632. <input type="checkbox" id="useLSP" name="useLSP">
  5633. </div>
  5634. <div class='OJBetter_setting_list'>
  5635. <label for='OJBetter_Bridge_WorkUri'>
  5636. <div style="display: flex;align-items: center;">
  5637. <span class="input_label" data-i18n="settings:codeEditor.lsp.OJBetter_Bridge_WorkUri.label"></span>
  5638. </div>
  5639. </label>
  5640. <div class="help_tip">
  5641. ${helpCircleHTML}
  5642. <div class="tip_text" data-i18n="[html]settings:codeEditor.lsp.OJBetter_Bridge_WorkUri.helpText"></div>
  5643. </div>
  5644. <input type='text' id='OJBetter_Bridge_WorkUri' class='no_default'
  5645. require=true data-i18n="[placeholder]settings:codeEditor.lsp.OJBetter_Bridge_WorkUri.placeholder">
  5646. </div>
  5647. <div class='OJBetter_setting_list'>
  5648. <label for='OJBetter_Bridge_SocketUrl'>
  5649. <div style="display: flex;align-items: center;">
  5650. <span class="input_label"
  5651. data-i18n="settings:codeEditor.lsp.OJBetter_Bridge_SocketUrl.label"></span>
  5652. </div>
  5653. </label>
  5654. <div class="help_tip">
  5655. ${helpCircleHTML}
  5656. <div class="tip_text" data-i18n="[html]settings:codeEditor.lsp.OJBetter_Bridge_SocketUrl.helpText"></div>
  5657. </div>
  5658. <input type='text' id='OJBetter_Bridge_SocketUrl' class='no_default'
  5659. require=true data-i18n="[placeholder]settings:codeEditor.lsp.OJBetter_Bridge_SocketUrl.placeholder">
  5660. </div>
  5661. <hr>
  5662. <h4 data-i18n="settings:codeEditor.staticCompletionEnhancement.title"></h4>
  5663. <div class='OJBetter_setting_list'>
  5664. <label for="cppCodeTemplateComplete"><span
  5665. data-i18n="settings:codeEditor.staticCompletionEnhancement.cppCodeTemplateComplete.label"></span></label>
  5666. <div class="help_tip">
  5667. ${helpCircleHTML}
  5668. <div class="tip_text" data-i18n="[html]settings:codeEditor.staticCompletionEnhancement.cppCodeTemplateComplete.helpText"></div>
  5669. </div>
  5670. <input type="checkbox" id="cppCodeTemplateComplete" name="cppCodeTemplateComplete">
  5671. </div>
  5672. <hr>
  5673. <h5 data-i18n="settings:codeEditor.staticCompletionEnhancement.customization"></h5>
  5674. <div class='OJBetter_setting_list alert_warn'>
  5675. <div>
  5676. <p data-i18n="settings:codeEditor.staticCompletionEnhancement.performanceWarning"></p>
  5677. </div>
  5678. </div>
  5679. <div id="Complet_config" class="config"></div>
  5680. </div>
  5681. `;
  5682.  
  5683. const preference_settings_HTML = `
  5684. <div id="preference-settings" class="settings-page">
  5685. <h3 data-i18n="settings:preference.title"></h3>
  5686. <hr>
  5687. <div class='OJBetter_setting_list'>
  5688. <label for="showLoading" data-i18n="settings:preference.loadingInfo.label"></label>
  5689. <div class="help_tip">
  5690. ${helpCircleHTML}
  5691. <div class="tip_text" data-i18n="[html]settings:preference.loadingInfo.helpText" data-i18n-options='{ "scriptName": "${OJBetter.state.name}" }'></div>
  5692. </div>
  5693. <input type="checkbox" id="showLoading" name="showLoading">
  5694. </div>
  5695. <div class='OJBetter_setting_list'>
  5696. <label for="hoverTargetAreaDisplay" data-i18n="settings:preference.targetArea.label"></label>
  5697. <div class="help_tip">
  5698. ${helpCircleHTML}
  5699. <div class="tip_text" data-i18n="[html]settings:preference.targetArea.helpText"></div>
  5700. </div>
  5701. <input type="checkbox" id="hoverTargetAreaDisplay" name="hoverTargetAreaDisplay">
  5702. </div>
  5703. <div class='OJBetter_setting_list'>
  5704. <label for='iconButtonSize'>
  5705. <div style="display: flex;align-items: center;" data-i18n="settings:preference.iconButtonSize.title"></div>
  5706. </label>
  5707. <div class="help_tip">
  5708. ${helpCircleHTML}
  5709. <div class="tip_text" data-i18n="[html]settings:preference.iconButtonSize.helpText"></div>
  5710. </div>
  5711. <input type='number' id='iconButtonSize' class='no_default' require=true data-i18n="[placeholder]settings:preference.iconButtonSize.placeholder">
  5712. <span>px</span>
  5713. </div>
  5714. </div>
  5715. `;
  5716.  
  5717. const dev_settings_HTML = `
  5718. <div id="dev-settings" class="settings-page">
  5719. <h3 data-i18n="settings:dev.title"></h3>
  5720. <hr>
  5721. <div class='OJBetter_setting_list alert_danger'>
  5722. <div>
  5723. <p data-i18n="[html]settings:dev.notice"></p>
  5724. </div>
  5725. </div>
  5726. <hr>
  5727. <h5 data-i18n="settings:dev.load.title"></h5>
  5728. <div class='OJBetter_setting_list'>
  5729. <label for="notWaiteLoaded"><span data-i18n="settings:dev.load.notWaiteLoaded.label"></span></label>
  5730. <div class="help_tip">
  5731. ${helpCircleHTML}
  5732. <div class="tip_text" data-i18n="[html]settings:dev.load.notWaiteLoaded.helpText"></div>
  5733. </div>
  5734. <input type="checkbox" id="notWaiteLoaded" name="notWaiteLoaded">
  5735. </div>
  5736. <hr>
  5737. <h5 data-i18n="settings:dev.l10n.title"></h5>
  5738. <div class='OJBetter_setting_list'>
  5739. <label><span data-i18n="settings:dev.l10n.refreshScrpitCache.label"></span></label>
  5740. <div class="help_tip">
  5741. ${helpCircleHTML}
  5742. <div class="tip_text" data-i18n="[html]settings:dev.l10n.refreshScrpitCache.helpText"></div>
  5743. </div>
  5744. <button type="button" id="l10n_refreshScrpitCacheButton" name="l10n_refreshScrpitCacheButton" data-i18n="settings:dev.l10n.refreshScrpitCache.button"></button>
  5745. </div>
  5746. <hr>
  5747. <h5 data-i18n="settings:dev.indexedDB.title"></h5>
  5748. <div class='OJBetter_setting_list'>
  5749. <label><span data-i18n="settings:dev.indexedDB.clear.label"></span></label>
  5750. <div class="help_tip">
  5751. ${helpCircleHTML}
  5752. <div class="tip_text" data-i18n="[html]settings:dev.indexedDB.clear.helpText"></div>
  5753. </div>
  5754. <button type="button" id="indexedDB_clearButton" name="indexedDB_clearButton" data-i18n="settings:dev.indexedDB.clear.button"></button>
  5755. </div>
  5756. <div class='OJBetter_setting_list'>
  5757. <label><span data-i18n="settings:dev.indexedDB.inputOrExport.label"></span></label>
  5758. <div class="help_tip">
  5759. ${helpCircleHTML}
  5760. <div class="tip_text" data-i18n="[html]settings:dev.indexedDB.inputOrExport.helpText"></div>
  5761. </div>
  5762. <button type="button" id="indexedDB_exportButton" name="indexedDB_exportButton" data-i18n="settings:dev.indexedDB.inputOrExport.export"></button>
  5763. <button type="button" id="indexedDB_importButton" name="indexedDB_importButton" data-i18n="settings:dev.indexedDB.inputOrExport.import"></button>
  5764. </div>
  5765. <hr>
  5766. <h5 data-i18n="settings:dev.configuration.title"></h5>
  5767. <div class='OJBetter_setting_list'>
  5768. <label><span data-i18n="settings:dev.configuration.clear.label"></span></label>
  5769. <div class="help_tip">
  5770. ${helpCircleHTML}
  5771. <div class="tip_text" data-i18n="[html]settings:dev.configuration.clear.helpText"></div>
  5772. </div>
  5773. <button type="button" id="configuration_clearButton" name="configuration_clearButton" data-i18n="settings:dev.configuration.clear.button"></button>
  5774. </div>
  5775. <div class='OJBetter_setting_list'>
  5776. <label><span data-i18n="settings:dev.configuration.inputOrExport.label"></span></label>
  5777. <div class="help_tip">
  5778. ${helpCircleHTML}
  5779. <div class="tip_text" data-i18n="[html]settings:dev.configuration.inputOrExport.helpText"></div>
  5780. </div>
  5781. <button type="button" id="configuration_exportButton" name="configuration_exportButton" data-i18n="settings:dev.configuration.inputOrExport.export"></button>
  5782. <button type="button" id="configuration_importButton" name="configuration_importButton" data-i18n="settings:dev.configuration.inputOrExport.import"></button>
  5783. </div>
  5784. </div>
  5785. `;
  5786.  
  5787. const about_settings_HTML = `
  5788. <div id="about-settings" class="settings-page">
  5789. <h3 data-i18n="settings:about.title"></h3>
  5790. <hr>
  5791. <div class='versionInfo'>
  5792. <p>${OJBetter.state.name}</p>
  5793. <p><span data-i18n="settings:about.version"></span><span id="nowVersion">${OJBetter.state.version}</span></p>
  5794. <p> @北极小狐 <a target="_blank" href="https://github.com/beijixiaohu/OJBetter">Github</a>
  5795. <a target="_blank" href="https://greatest.deepsurf.us/zh-CN/scripts/465777">GreasyFork</a></p>
  5796. </div>
  5797. <hr>
  5798. <h5 data-i18n="settings:about.update.title"></h5>
  5799. <div id="thanksforDevChannelNotice" class='OJBetter_setting_list alert_info'>
  5800. <div data-i18n="[html]settings:about.update.thanksforDevChannelNotice"} data-i18n-options='{ "scriptName": "${OJBetter.state.name}" }' ></div>
  5801. </div>
  5802. <div class='OJBetter_setting_list'>
  5803. <label for="updateChannel"><span data-i18n="settings:about.update.channel.label"></span></label>
  5804. <div class="help_tip">
  5805. ${helpCircleHTML}
  5806. <div class="tip_text" data-i18n="[html]settings:about.update.channel.helpText"></div>
  5807. </div>
  5808. <select id="updateChannel" name="updateChannel">
  5809. <option value="release" data-i18n="settings:about.update.channel.options.release"></option>
  5810. <option value="dev" data-i18n="settings:about.update.channel.options.dev"></option>
  5811. </select>
  5812. </div>
  5813. <div class='OJBetter_setting_list'>
  5814. <label for="updateSource"><span data-i18n="settings:about.update.source.label"></span></label>
  5815. <div class="help_tip">
  5816. ${helpCircleHTML}
  5817. <div class="tip_text" data-i18n="[html]settings:about.update.source.helpText"></div>
  5818. </div>
  5819. <select id="updateSource" name="updateSource">
  5820. <option value="greasyfork" data-i18n="settings:about.update.source.options.greasyfork"></option>
  5821. <option value="github" data-i18n="settings:about.update.source.options.github"></option>
  5822. <option value="aliyunoss" data-i18n="settings:about.update.source.options.aliyunoss"></option>
  5823. </select>
  5824. </div>
  5825. </div>
  5826. `;
  5827.  
  5828. const OJBetter_setting_content_HTML = `
  5829. <div class="OJBetter_setting_content">
  5830. ${basic_settings_HTML}
  5831. ${l10n_settings_HTML}
  5832. ${translation_settings_HTML}
  5833. ${clist_rating_settings_HTML}
  5834. ${code_editor_settings_HTML}
  5835. ${preference_settings_HTML}
  5836. ${dev_settings_HTML}
  5837. ${about_settings_HTML}
  5838. </div>
  5839. `;
  5840.  
  5841. // 设置界面HTML
  5842. const OJBetterSettingMenu_HTML = `
  5843. <dialog class='OJBetter_setting_menu' id='OJBetter_setting_menu'>
  5844. <div class="tool-box">
  5845. <button class='ojb_btn ojb_btn_popover top btn-close'>
  5846. <i class="iconfont">&#xe614;</i>
  5847. </button>
  5848. </div>
  5849. <div class="OJBetter_setting_container">
  5850. ${OJBetter_setting_sidebar_HTML}
  5851. ${OJBetter_setting_content_HTML}
  5852. </div>
  5853. </dialog>
  5854. `;
  5855.  
  5856. const apiCustomConfigHTML = (prefix) => {
  5857. return `
  5858. <div class="OJBetter_setting_list">
  5859. <label for='${prefix}_header'>
  5860. <div style="display: flex;align-items: center;">
  5861. <span class="input_label" data-i18n="config:common.advanced.header.label"></span>
  5862. <div class="help_tip">
  5863. ${helpCircleHTML}
  5864. <div class="tip_text" data-i18n="[html]config:common.advanced.header.tipText"></div>
  5865. </div>
  5866. </div>
  5867. </label>
  5868. <textarea id="${prefix}_header" placeholder='' require = false data-i18n="[placeholder]config:common.advanced.header.placeholder"></textarea>
  5869. </div>
  5870. <div class="OJBetter_setting_list">
  5871. <label for='${prefix}_data'>
  5872. <div style="display: flex;align-items: center;">
  5873. <span class="input_label" data-i18n="config:common.advanced.data.label"></span>
  5874. <div class="help_tip">
  5875. ${helpCircleHTML}
  5876. <div class="tip_text" data-i18n="[html]config:common.advanced.data.tipText"></div>
  5877. </div>
  5878. </div>
  5879. </label>
  5880. <textarea id="${prefix}_data" placeholder='' require = false data-i18n="[placeholder]config:common.advanced.data.placeholder"></textarea>
  5881. </div>
  5882. `;
  5883. };
  5884.  
  5885. const apiQuotaConfigHTML = (prefix) => {
  5886. return `
  5887. <div class="OJBetter_setting_list">
  5888. <label for='${prefix}_quota_url'>
  5889. <div style="display: flex;align-items: center;">
  5890. <span class="input_label" data-i18n="config:common.quota.url.label"></span>
  5891. <div class="help_tip">
  5892. ${helpCircleHTML}
  5893. <div class="tip_text" data-i18n="[html]config:common.quota.url.tipText"></div>
  5894. </div>
  5895. </div>
  5896. </label>
  5897. <input type='text' id='${prefix}_quota_url' class='no_default' placeholder='' require = true data-i18n="[placeholder]config:common.quota.url.placeholder">
  5898. </div>
  5899. <div class="OJBetter_setting_list">
  5900. <label for="${prefix}_quota_method" style="display: flex;" data-i18n="config:common.quota.method.label"></label>
  5901. <div class="help_tip">
  5902. ${helpCircleHTML}
  5903. <div class="tip_text" data-i18n="[html]config:common.quota.method.tipText"></div>
  5904. </div>
  5905. <select id="${prefix}_quota_method" name="${prefix}_quota_method">
  5906. <option value="get">GET</option>
  5907. <option value="post">POST</option>
  5908. </select>
  5909. </div>
  5910. <div class="OJBetter_setting_list">
  5911. <label for='${prefix}_quota_header'>
  5912. <div style="display: flex;align-items: center;">
  5913. <span class="input_label" data-i18n="config:common.quota.header.label"></span>
  5914. <div class="help_tip">
  5915. ${helpCircleHTML}
  5916. <div class="tip_text" data-i18n="[html]config:common.quota.header.tipText"></div>
  5917. </div>
  5918. </div>
  5919. </label>
  5920. <textarea id="${prefix}_quota_header" placeholder='' require = false data-i18n="[placeholder]config:common.quota.header.placeholder"></textarea>
  5921. </div>
  5922. <div class="OJBetter_setting_list">
  5923. <label for='${prefix}_quota_data'>
  5924. <div style="display: flex;align-items: center;">
  5925. <span class="input_label" data-i18n="config:common.quota.data.label"></span>
  5926. <div class="help_tip">
  5927. ${helpCircleHTML}
  5928. <div class="tip_text" data-i18n="[html]config:common.quota.data.tipText"></div>
  5929. </div>
  5930. </div>
  5931. </label>
  5932. <textarea id="${prefix}_quota_data" placeholder='' require = false data-i18n="[placeholder]config:common.quota.data.placeholder"></textarea>
  5933. </div>
  5934. <div class="OJBetter_setting_list">
  5935. <div style="display: flex;align-items: center;">
  5936. <span class="input_label" data-i18n="config:common.quota.surplus.label"></span>
  5937. <div class="help_tip">
  5938. ${helpCircleHTML}
  5939. <div class="tip_text" data-i18n="[html]config:common.quota.surplus.tipText"></div>
  5940. </div>
  5941. </div>
  5942. </label>
  5943. <input type='text' id='${prefix}_quota_surplus' class='no_default' placeholder='' require = true data-i18n="[placeholder]config:common.quota.surplus.placeholder">
  5944. </div>
  5945. `;
  5946. }
  5947.  
  5948. const deeplConfigEditHTML = `
  5949. <dialog class='OJBetter_setting_menu' id='config_edit_menu'>
  5950. <div class='OJBetter_setting_content'>
  5951. <div class="tool-box">
  5952. <button class='ojb_btn ojb_btn_popover top btn-close'>
  5953. <i class="iconfont">&#xe614;</i>
  5954. </button>
  5955. </div>
  5956. <h4 data-i18n="config:deepl.title"></h4>
  5957. <h5 data-i18n="config:deepl.basic.title"></h5>
  5958. <hr>
  5959. <div class="OJBetter_setting_list">
  5960. <label for='name'>
  5961. <span class="input_label" data-i18n="config:deepl.basic.name.label"></span>
  5962. </label>
  5963. <input type='text' id='name' class='no_default' placeholder='' require = true data-i18n="[placeholder]config:deepl.basic.name.placeholder">
  5964. </div>
  5965. <div class='OJBetter_setting_list'>
  5966. <label for="deepl_apiGenre" style="display: flex;" data-i18n="config:deepl.genre.label"></label>
  5967. <div class="help_tip">
  5968. ${helpCircleHTML}
  5969. <div class="tip_text" data-i18n="[html]config:deepl.genre.tipText"></div>
  5970. </div>
  5971. <select id="deepl_apiGenre" name="deepl_apiGenre">
  5972. <option value="api-free">api-free</option>
  5973. <option value="api-pro">api-pro</option>
  5974. <option value="deeplx">deeplx</option>
  5975. </select>
  5976. </div>
  5977. <div class="OJBetter_setting_list">
  5978. <label for='deepl_key'>
  5979. <div style="display: flex;align-items: center;">
  5980. <span class="input_label" data-i18n="config:deepl.basic.key.label"></span>
  5981. <div class="help_tip">
  5982. ${helpCircleHTML}
  5983. <div class="tip_text" data-i18n="[html]config:deepl.basic.key.tipText"></div>
  5984. </div>
  5985. </div>
  5986. </label>
  5987. <input type='text' id='deepl_key' class='no_default' placeholder='' require = true data-i18n="[placeholder]config:deepl.basic.key.placeholder">
  5988. </div>
  5989. <div class="OJBetter_setting_list">
  5990. <label for='deepl_proxy'>
  5991. <div style="display: flex;align-items: center;">
  5992. <span class="input_label" data-i18n="config:deepl.basic.proxy.label">Proxy API:</span>
  5993. <div class="help_tip">
  5994. ${helpCircleHTML}
  5995. <div class="tip_text" data-i18n="[html]config:deepl.basic.proxy.tipText"></div>
  5996. </div>
  5997. </div>
  5998. </label>
  5999. <input type='text' id='deepl_proxy' placeholder='' require = false>
  6000. </div>
  6001. <hr>
  6002. <details>
  6003. <summary data-i18n="config:common.advanced.title"></summary>
  6004. ${apiCustomConfigHTML('deepl')}
  6005. </details>
  6006. <details>
  6007. <summary data-i18n="config:common.quota.title"></summary>
  6008. ${apiQuotaConfigHTML('deepl')}
  6009. </details>
  6010. <button id='tempConfig_save' data-i18n="common:save"></button>
  6011. </div>
  6012. </dialog>
  6013. `;
  6014.  
  6015. const chatgptConfigEditHTML = `
  6016. <dialog class='OJBetter_setting_menu' id='config_edit_menu'>
  6017. <div class='OJBetter_setting_content'>
  6018. <div class="tool-box">
  6019. <button class='ojb_btn ojb_btn_popover top btn-close'>
  6020. <i class="iconfont">&#xe614;</i>
  6021. </button>
  6022. </div>
  6023. <h4 data-i18n="config:chatgpt.title"></h4>
  6024. <h5 data-i18n="config:chatgpt.basic.title"></h5>
  6025. <hr>
  6026. <div class="OJBetter_setting_list">
  6027. <label for='name'>
  6028. <span class="input_label" data-i18n="config:chatgpt.basic.name.label"></span>
  6029. </label>
  6030. <input type='text' id='name' class='no_default' placeholder='' require = true data-i18n="[placeholder]config:chatgpt.basic.name.placeholder">
  6031. </div>
  6032. <div class="OJBetter_setting_list">
  6033. <label for='chatgpt_model'>
  6034. <div style="display: flex;align-items: center;">
  6035. <span class="input_label" data-i18n="[html]config:chatgpt.basic.model.label"></span>
  6036. <div class="help_tip">
  6037. ${helpCircleHTML}
  6038. <div class="tip_text" data-i18n="[html]config:chatgpt.basic.model.tipText"></div>
  6039. </div>
  6040. </div>
  6041. </label>
  6042. <input type='text' id='chatgpt_model' placeholder='gpt-3.5-turbo' require = false>
  6043. </div>
  6044. <div class="OJBetter_setting_list">
  6045. <label for='chatgpt_key'>
  6046. <div style="display: flex;align-items: center;">
  6047. <span class="input_label" data-i18n="config:chatgpt.basic.key.label"></span>
  6048. <div class="help_tip">
  6049. ${helpCircleHTML}
  6050. <div class="tip_text" data-i18n="[html]config:chatgpt.basic.key.tipText"></div>
  6051. </div>
  6052. </div>
  6053. </label>
  6054. <input type='text' id='chatgpt_key' class='no_default' placeholder='' require = true data-i18n="[placeholder]config:chatgpt.basic.key.placeholder">
  6055. </div>
  6056. <div class="OJBetter_setting_list">
  6057. <label for='chatgpt_proxy'>
  6058. <div style="display: flex;align-items: center;">
  6059. <span class="input_label" data-i18n="config:chatgpt.basic.proxy.label">Proxy API:</span>
  6060. <div class="help_tip">
  6061. ${helpCircleHTML}
  6062. <div class="tip_text" data-i18n="[html]config:chatgpt.basic.proxy.tipText"></div>
  6063. </div>
  6064. </div>
  6065. </label>
  6066. <input type='text' id='chatgpt_proxy' placeholder='https://api.openai.com/v1/chat/completions' require = false>
  6067. </div>
  6068. <hr>
  6069. <details>
  6070. <summary data-i18n="config:common.advanced.title"></summary>
  6071. ${apiCustomConfigHTML('chatgpt')}
  6072. </details>
  6073. <details>
  6074. <summary data-i18n="config:common.quota.title"></summary>
  6075. ${apiQuotaConfigHTML('chatgpt')}
  6076. </details>
  6077. <button id='tempConfig_save' data-i18n="common:save"></button>
  6078. </div>
  6079. </dialog>
  6080. `;
  6081.  
  6082. const CompletConfigEditHTML = `
  6083. <dialog class='OJBetter_setting_menu' id='config_edit_menu'>
  6084. <div class='OJBetter_setting_content'>
  6085. <div class="tool-box">
  6086. <button class='ojb_btn ojb_btn_popover top btn-close'>
  6087. <i class="iconfont">&#xe614;</i>
  6088. </button>
  6089. </div>
  6090. <h4 data-i18n="config:complet.title"></h4>
  6091. <hr>
  6092. <div class="OJBetter_setting_list">
  6093. <label for='name'>
  6094. <span class="input_label" data-i18n="config:complet.name.label"></span>
  6095. </label>
  6096. <input type='text' id='name' class='no_default' placeholder='' require = true data-i18n="[placeholder]config:complet.name.placeholder">
  6097. </div>
  6098. <div class='OJBetter_setting_list'>
  6099. <label for="complet_isChoose"><span id="loaded_span" data-i18n="config:complet.choose.label"></span></label>
  6100. <input type="checkbox" id="complet_isChoose" name="complet_isChoose" require = false>
  6101. </div>
  6102. <div class='OJBetter_setting_list'>
  6103. <label for="complet_genre" style="display: flex;" data-i18n="config:complet.genre.label"></label>
  6104. <div class="help_tip">
  6105. ${helpCircleHTML}
  6106. <div class="tip_text" data-i18n="[html]config:complet.genre.tipText"></div>
  6107. </div>
  6108. <select id="complet_genre" name="complet_genre">
  6109. <option value="monaco">monaco</option>
  6110. <option value="ace">ace</option>
  6111. </select>
  6112. </div>
  6113. <div class='OJBetter_setting_list'>
  6114. <label for="complet_language" style="display: flex;" data-i18n="config:complet.language.label"></label>
  6115. <select id="complet_language" name="complet_language">
  6116. <option value="cpp">cpp</option>
  6117. <option value="python">python</option>
  6118. <option value="java">java</option>
  6119. <option value="c">c</option>
  6120. </select>
  6121. </div>
  6122. <div class="OJBetter_setting_list">
  6123. <label for='complet_jsonUrl'>
  6124. <div style="display: flex;align-items: center;">
  6125. <span class="input_label">JSON URL:</span>
  6126. <div class="help_tip">
  6127. ${helpCircleHTML}
  6128. <div class="tip_text" data-i18n="[html]config:complet.jsonurl.tipText"></div>
  6129. </div>
  6130. </div>
  6131. </label>
  6132. <div class='OJBetter_setting_list alert_warn' data-i18n="[html]config:complet.jsonurl.alert"></div>
  6133. <input type='text' id='complet_jsonUrl' class='no_default' placeholder='' require = true data-i18n="[placeholder]config:complet.jsonurl.placeholder">
  6134. </div>
  6135. <button id='tempConfig_save' data-i18n="common:save"></button>
  6136. </div>
  6137. </dialog>
  6138. `;
  6139.  
  6140. /**
  6141. * 加载设置按钮面板
  6142. */
  6143. async function initSettingsPanel() {
  6144. /**
  6145. * 添加右上角设置按钮
  6146. * @param {string} location 位置选择器
  6147. * @param {string} method 插入方法
  6148. */
  6149. function insertOJBetterSettingButton(location, method) {
  6150. $(location)[method](`<button class='ojb_btn OJBetter_setting'>
  6151. ${OJBetter.state.name} ${i18next.t('settings', { ns: 'common' })}</button>`);
  6152. }
  6153.  
  6154. /**
  6155. * ============================================
  6156. * 该网站插入设置按钮的位置和方式
  6157. */
  6158. if (OJBetter.typeOfPage.isEnglishLanguage) {
  6159. insertOJBetterSettingButton("#navbar-collapse > ul:nth-child(2) > li:last-child", "after");
  6160. } else {
  6161. if ($('.header-mypage').length > 0) insertOJBetterSettingButton(".header-mypage", "after");
  6162. else insertOJBetterSettingButton("#navbar-collapse > ul:nth-child(2) > li:last-child", "after");
  6163. }
  6164. /**
  6165. * ============================================
  6166. */
  6167.  
  6168. const $settingBtns = $(".OJBetter_setting");
  6169. $settingBtns.click(() => {
  6170. $settingBtns.prop("disabled", true).addClass("open");
  6171.  
  6172. // 设置面板div
  6173. const settingMenu = OJB_safeCreateJQElement(OJBetterSettingMenu_HTML);
  6174. $("body").append(settingMenu);
  6175.  
  6176. elementLocalize(settingMenu); // 加载i18n
  6177. OJB_showModal(settingMenu);
  6178. OJB_addDraggable($('#OJBetter_setting_menu')); // 窗口支持拖拽
  6179.  
  6180. // help帮助悬浮窗位置更新
  6181. $(document).on('mouseenter', '.help-icon', function (event) {
  6182. var menuOffset = $('.OJBetter_setting_menu:last').offset();
  6183. var mouseX = event.pageX - menuOffset.left;
  6184. var mouseY = event.pageY - menuOffset.top;
  6185.  
  6186. $('.tip_text').css({
  6187. 'top': mouseY + 'px',
  6188. 'left': mouseX + 'px'
  6189. });
  6190. });
  6191.  
  6192. // 选项卡切换
  6193. $('.OJBetter_setting_sidebar a').click(function (event) {
  6194. event.preventDefault();
  6195. $('.OJBetter_setting_sidebar a').removeClass('active');
  6196. $('.settings-page').removeClass('active');
  6197. $(this).addClass('active');
  6198. const targetPageId = $(this).attr('href').substring(1);
  6199. $('#' + targetPageId).addClass('active');
  6200. });
  6201.  
  6202. /**
  6203. * 更新单选按钮组的可用状态
  6204. * @param {string} selector 单选按钮组的选择器
  6205. * @param {string} targetLanguage 目标语言
  6206. * @param {Object} translationSupport 翻译支持的语言对应表
  6207. */
  6208. const updateRadioButtonsAvailability = (selector, targetLanguage) => {
  6209. Object.entries(OJBetter.supportList.translationSupport).forEach(([service, languages]) => {
  6210. const radioButton = $(selector).find(`input[value="${service}"]`);
  6211. const isEnabled = languages[targetLanguage];
  6212. $(radioButton).prop('disabled', !isEnabled);
  6213. if (!isEnabled) {
  6214. $(radioButton).prop('checked', false);
  6215. }
  6216. });
  6217. };
  6218.  
  6219. /**
  6220. * 检查下拉框选中项是否有效,若无效则清空
  6221. * @param {string} selector 下拉框的选择器
  6222. */
  6223. const validateSelectOption = (selector) => {
  6224. const selectedValue = $(selector).val();
  6225. if (!selectedValue) {
  6226. $(selector).val('');
  6227. }
  6228. };
  6229.  
  6230. /**
  6231. * 更新翻译目标语言下拉框的可用状态
  6232. * @param {string} selector 下拉框的选择器
  6233. * @param {string} targetLanguage 目标语言
  6234. * @param {Object} translationSupport 翻译支持的语言对应表
  6235. */
  6236. const updateSelectOptionsAvailability = (selector, targetLanguage) => {
  6237. $(selector).children('option').each(function () {
  6238. const optionValue = $(this).val();
  6239. const isEnabled = OJBetter.supportList.translationSupport[optionValue] ? OJBetter.supportList.translationSupport[optionValue][targetLanguage] : true;
  6240. $(this).prop('disabled', !isEnabled);
  6241. });
  6242. validateSelectOption(selector);
  6243. };
  6244.  
  6245. /**
  6246. * 更新翻译服务复选框的可用状态
  6247. * @param {string} selector 复选框的选择器
  6248. * @param {string} targetLanguage 目标语言
  6249. * @param {Object} translationSupport 翻译支持的语言对应表
  6250. */
  6251. const updateCheckboxesAvailability = (selector, targetLanguage) => {
  6252. $(selector).children('input').each(function () {
  6253. const checkboxValue = $(this).val();
  6254. const isEnabled = OJBetter.supportList.translationSupport[checkboxValue][targetLanguage];
  6255. $(this).prop('disabled', !isEnabled);
  6256. if (!isEnabled) {
  6257. $(this).prop('checked', false);
  6258. }
  6259. });
  6260. };
  6261.  
  6262. /**
  6263. * 更新更新源下拉框的可用状态
  6264. * @param {string} selector 下拉框的选择器
  6265. * @param {string} targetLanguage 目标语言
  6266. * @param {Object} translationSupport 翻译支持的语言对应表
  6267. */
  6268. const updateUpdateSourceSelectOptionsAvailability = (selector, updateChannel) => {
  6269. $(selector).children('option').each(function () {
  6270. const optionValue = $(this).val();
  6271. const isEnabled = OJBetter.supportList.updateSourceSupportList[optionValue][updateChannel];
  6272. $(this).prop('disabled', !isEnabled);
  6273. });
  6274. validateSelectOption(selector);
  6275. };
  6276.  
  6277. /**
  6278. * 创建配置结构
  6279. * @param {string} type - 该字段的在表单中的类型
  6280. * @param {string} value - 在配置中的键值
  6281. * @param {boolean} require - 是否是表单的必填项
  6282. * @param {string} [check=""] check - 调用的合法性检查
  6283. */
  6284. function createStructure(type, value, require, check = "") {
  6285. return { type, value, require, check };
  6286. }
  6287.  
  6288. // deepl配置
  6289. const deeplStructure = {
  6290. '#name': createStructure('text', 'name', true),
  6291. '#deepl_apiGenre': createStructure('text', 'apiGenre', true),
  6292. '#deepl_key': createStructure('text', 'key', false),
  6293. '#deepl_proxy': createStructure('text', 'proxy', false),
  6294. '#deepl_header': createStructure('text', '_header', false, 'keyValuePairs'),
  6295. '#deepl_data': createStructure('text', '_data', false, 'keyValuePairs'),
  6296. '#deepl_quota_url': createStructure('text', 'quota_url', false),
  6297. '#deepl_quota_method': createStructure('text', 'quota_method', false),
  6298. '#deepl_quota_header': createStructure('text', 'quota_header', false, 'keyValuePairs'),
  6299. '#deepl_quota_data': createStructure('text', 'quota_data', false, 'keyValuePairs'),
  6300. '#deepl_quota_surplus': createStructure('text', 'quota_surplus', false, 'dotSeparatedPath'),
  6301. };
  6302. let tempConfig_deepl = GM_getValue('deepl_config'); // 获取配置信息
  6303. const configManager_deepl = new ConfigManager('#deepl_config', 'deepl_config_', tempConfig_deepl, deeplStructure, deeplConfigEditHTML);
  6304. configManager_deepl.registerChoiceChange();
  6305.  
  6306. // chatgpt配置
  6307. const chatgptStructure = {
  6308. '#name': createStructure('text', 'name', true),
  6309. '#chatgpt_model': createStructure('text', 'model', false),
  6310. '#chatgpt_key': createStructure('text', 'key', true),
  6311. '#chatgpt_proxy': createStructure('text', 'proxy', false),
  6312. '#chatgpt_header': createStructure('text', '_header', false, 'keyValuePairs'),
  6313. '#chatgpt_data': createStructure('text', '_data', false, 'keyValuePairs'),
  6314. '#chatgpt_quota_url': createStructure('text', 'quota_url', false),
  6315. '#chatgpt_quota_header': createStructure('text', 'quota_header', false, 'keyValuePairs'),
  6316. '#chatgpt_quota_data': createStructure('text', 'quota_data', false, 'keyValuePairs'),
  6317. '#chatgpt_quota_surplus': createStructure('text', 'quota_surplus', false, 'dotSeparatedPath'),
  6318. '#chatgpt_quota_method': createStructure('text', 'quota_method', false),
  6319. };
  6320. let tempConfig_chatgpt = GM_getValue('chatgpt_config'); // 获取配置信息
  6321. const configManager_chatgpt = new ConfigManager('#chatgpt_config', 'chatgpt_config_', tempConfig_chatgpt, chatgptStructure, chatgptConfigEditHTML);
  6322. configManager_chatgpt.registerChoiceChange();
  6323.  
  6324. // Complet配置
  6325. const CompletStructure = {
  6326. '#name': createStructure('text', 'name', true),
  6327. '#complet_isChoose': createStructure('checkbox', 'isChoose', true),
  6328. '#complet_genre': createStructure('text', 'genre', true),
  6329. '#complet_language': createStructure('text', 'language', true),
  6330. '#complet_jsonUrl': createStructure('text', 'jsonUrl', true)
  6331. };
  6332. let tempConfig_Complet = GM_getValue('Complet_config'); // 获取配置信息
  6333. const configManager_complet = new ConfigManager('#Complet_config', 'complet_config_', tempConfig_Complet, CompletStructure, CompletConfigEditHTML, false);
  6334.  
  6335. // 状态更新
  6336. $("input[name='darkMode'][value='" + OJBetter.basic.darkMode + "']").prop("checked", true);
  6337. $("#showLoading").prop("checked", GM_getValue("showLoading") === true);
  6338. $("#expandFoldingblocks").prop("checked", GM_getValue("expandFoldingblocks") === true);
  6339. $("#renderPerfOpt").prop("checked", GM_getValue("renderPerfOpt") === true);
  6340. $("#commentPaging").prop("checked", GM_getValue("commentPaging") === true);
  6341. $("#standingsRecolor").prop("checked", GM_getValue("standingsRecolor") === true);
  6342. $("#showJumpToLuogu").prop("checked", GM_getValue("showJumpToLuogu") === true);
  6343. $("#showCF2vjudge").prop("checked", GM_getValue("showCF2vjudge") === true);
  6344. $("#hoverTargetAreaDisplay").prop("checked", GM_getValue("hoverTargetAreaDisplay") === true);
  6345. $("#showClistRating_contest").prop("checked", GM_getValue("showClistRating_contest") === true);
  6346. $("#showClistRating_problemset").prop("checked", GM_getValue("showClistRating_problemset") === true);
  6347. $("#showClistRating_problem").prop("checked", GM_getValue("showClistRating_problem") === true);
  6348. $("#RatingHidden").prop("checked", GM_getValue("RatingHidden") === true);
  6349. $('#scriptL10nLanguage').val(GM_getValue("scriptL10nLanguage"));
  6350. $('#localizationLanguage').val(GM_getValue("localizationLanguage"));
  6351. $("input[name='translation'][value='" + OJBetter.translation.choice + "']").prop("checked", true);
  6352. $("input[name='translation']").css("color", "gray");
  6353. $('#deepl_type').val(GM_getValue("deepl_type"));
  6354. $("#deepl_config_config_bar_ul").find(`input[name='deepl_config_config_item'][value='${tempConfig_deepl.choice}']`).prop("checked", true);
  6355. $('#enableEmphasisProtection').prop("checked", GM_getValue("enableEmphasisProtection") === true);
  6356. $('#enableLinkProtection').prop("checked", GM_getValue("enableLinkProtection") === true);
  6357. $("#chatgpt_config_config_bar_ul").find(`input[name='chatgpt_config_config_item'][value='${tempConfig_chatgpt.choice}']`).prop("checked", true);
  6358. $("#openai_isStream").prop("checked", GM_getValue("openai_isStream") === true);
  6359. $('#comment_translation_choice').val(GM_getValue("commentTranslationChoice"));
  6360. $('#iconButtonSize').val(GM_getValue("iconButtonSize"));
  6361. $("#autoTranslation").prop("checked", GM_getValue("autoTranslation") === true);
  6362. $('#shortTextLength').val(GM_getValue("shortTextLength"));
  6363. $("#allowMixTrans").prop("checked", GM_getValue("allowMixTrans") === true);
  6364. $('.OJBetter_checkboxs').find('input[type="checkbox"][name="mixedTranslation"]').each(function () {
  6365. if (OJBetter.translation.auto.mixTrans.servers.indexOf($(this).val()) > -1) {
  6366. $(this).prop('checked', true);
  6367. }
  6368. });
  6369. // 翻译目标语言下拉框
  6370. $('#transTargetLang').change(function () {
  6371. var selectedLang = $(this).val();
  6372. updateRadioButtonsAvailability('#translationServices', selectedLang);
  6373. updateSelectOptionsAvailability('#comment_translation_choice', selectedLang);
  6374. updateCheckboxesAvailability('.OJBetter_checkboxs', selectedLang);
  6375. });
  6376. $('#transTargetLang').val(GM_getValue("transTargetLang"));
  6377. $('#transTargetLang').change();
  6378. //
  6379. $('#comment_translation_mode').val(GM_getValue("commentTranslationMode"));
  6380. $("#memoryTranslateHistory").prop("checked", GM_getValue("memoryTranslateHistory") === true);
  6381. $('#transWaitTime').val(GM_getValue("transWaitTime"));
  6382. $('#translation_replaceSymbol').val(GM_getValue("replaceSymbol"));
  6383. $("#filterTextWithoutEmphasis").prop("checked", GM_getValue("filterTextWithoutEmphasis") === true);
  6384. $('#translation_retransAction').val(GM_getValue("retransAction"));
  6385. $("#clist_Authorization").val(GM_getValue("clist_Authorization"));
  6386. $("#problemPageCodeEditor").prop("checked", GM_getValue("problemPageCodeEditor") === true);
  6387. $("#beautifyPreBlocks").prop("checked", GM_getValue("beautifyPreBlocks") === true);
  6388. $("#isCodeSubmitConfirm").prop("checked", GM_getValue("isCodeSubmitConfirm") === true);
  6389. $("#alwaysConsumeMouseWheel").prop("checked", GM_getValue("alwaysConsumeMouseWheel") === true);
  6390. $("#submitButtonPosition").val(GM_getValue("submitButtonPosition"));
  6391. $("#cppCodeTemplateComplete").prop("checked", GM_getValue("cppCodeTemplateComplete") === true);
  6392. $("#useLSP").prop("checked", GM_getValue("useLSP") === true);
  6393. $("#OJBetter_Bridge_WorkUri").val(GM_getValue("OJBetter_Bridge_WorkUri"));
  6394. $("#OJBetter_Bridge_SocketUrl").val(GM_getValue("OJBetter_Bridge_SocketUrl"));
  6395. $("input[name='compiler'][value='" + OJBetter.monaco.onlineCompilerChoice + "']").prop("checked", true);
  6396. $("input[name='compiler']").css("color", "gray");
  6397. // 调试
  6398. $("#notWaiteLoaded").prop("checked", GM_getValue("notWaiteLoaded") === true);
  6399. $('#l10n_refreshScrpitCacheButton').click(clearI18nextCache);
  6400. $('#indexedDB_clearButton').click(async () => { await clearDatabase(); });
  6401. $('#indexedDB_exportButton').click(async () => { downloadDataAsFile(await exportDatabase(), 'database_export.json') });
  6402. $('#indexedDB_importButton').click(() => { readFileInput(async (fileContent) => { await importDatabase(fileContent); }); });
  6403. $('#configuration_clearButton').click(deleteAllConfigSettings);
  6404. $('#configuration_exportButton').click(() => { downloadDataAsFile(exportSettingsToJSON(), 'configuration_export.json') });
  6405. $('#configuration_importButton').click(() => { readFileInput((fileContent) => { importSettingsFromJSON(fileContent); }) });
  6406. // 关于
  6407. $('#updateChannel').val(GM_getValue("updateChannel"));
  6408. $('#updateSource').val(GM_getValue("updateSource"));
  6409. $('#updateChannel').change(function () {
  6410. var selectedLang = $(this).val();
  6411. updateUpdateSourceSelectOptionsAvailability('#updateSource', selectedLang);
  6412. if (selectedLang == "dev") $('#thanksforDevChannelNotice').show();
  6413. else $('#thanksforDevChannelNotice').hide();
  6414. });
  6415. $('#updateChannel').change();
  6416.  
  6417. // 关闭
  6418. const $settingMenu = $(".OJBetter_setting_menu");
  6419. $settingMenu.on("click", ".btn-close", async () => {
  6420. // 设置的数据
  6421. const settings = {
  6422. darkMode: $("input[name='darkMode']:checked").val(),
  6423. showLoading: $("#showLoading").prop("checked"),
  6424. hoverTargetAreaDisplay: $("#hoverTargetAreaDisplay").prop("checked"),
  6425. expandFoldingblocks: $("#expandFoldingblocks").prop("checked"),
  6426. renderPerfOpt: $("#renderPerfOpt").prop("checked"),
  6427. commentPaging: $("#commentPaging").prop("checked"),
  6428. standingsRecolor: $("#standingsRecolor").prop("checked"),
  6429. showJumpToLuogu: $("#showJumpToLuogu").prop("checked"),
  6430. showCF2vjudge: $("#showCF2vjudge").prop("checked"),
  6431. scriptL10nLanguage: $('#scriptL10nLanguage').val(),
  6432. localizationLanguage: $('#localizationLanguage').val(),
  6433. transTargetLang: $('#transTargetLang').val(),
  6434. translation: $("input[name='translation']:checked").val(),
  6435. deepl_type: $('#deepl_type').val(),
  6436. enableEmphasisProtection: $("#enableEmphasisProtection").prop("checked"),
  6437. enableLinkProtection: $("#enableLinkProtection").prop("checked"),
  6438. openai_isStream: $("#openai_isStream").prop("checked"),
  6439. commentTranslationChoice: $('#comment_translation_choice').val(),
  6440. iconButtonSize: $('#iconButtonSize').val(),
  6441. autoTranslation: $("#autoTranslation").prop("checked"),
  6442. shortTextLength: $('#shortTextLength').val(),
  6443. allowMixTrans: $("#allowMixTrans").prop("checked"),
  6444. mixedTranslation: (() => {
  6445. let mixedTranslation = [];
  6446. $('.OJBetter_checkboxs').find('input[type="checkbox"][name="mixedTranslation"]').each(function () {
  6447. if ($(this).is(":checked")) {
  6448. mixedTranslation.push($(this).val());
  6449. }
  6450. });
  6451. return mixedTranslation;
  6452. })(),
  6453. commentTranslationMode: $('#comment_translation_mode').val(),
  6454. memoryTranslateHistory: $('#memoryTranslateHistory').prop("checked"),
  6455. transWaitTime: $('#transWaitTime').val(),
  6456. replaceSymbol: $('#translation_replaceSymbol').val(),
  6457. filterTextWithoutEmphasis: $('#filterTextWithoutEmphasis').prop("checked"),
  6458. retransAction: $('#translation_retransAction').val(),
  6459. showClistRating_contest: $('#showClistRating_contest').prop("checked"),
  6460. showClistRating_problemset: $('#showClistRating_problemset').prop("checked"),
  6461. showClistRating_problem: $('#showClistRating_problem').prop("checked"),
  6462. RatingHidden: $('#RatingHidden').prop("checked"),
  6463. clist_Authorization: $('#clist_Authorization').val(),
  6464. problemPageCodeEditor: $("#problemPageCodeEditor").prop("checked"),
  6465. beautifyPreBlocks: $("#beautifyPreBlocks").prop("checked"),
  6466. isCodeSubmitConfirm: $("#isCodeSubmitConfirm").prop("checked"),
  6467. alwaysConsumeMouseWheel: $("#alwaysConsumeMouseWheel").prop("checked"),
  6468. submitButtonPosition: $('#submitButtonPosition').val(),
  6469. cppCodeTemplateComplete: $("#cppCodeTemplateComplete").prop("checked"),
  6470. useLSP: $("#useLSP").prop("checked"),
  6471. OJBetter_Bridge_WorkUri: $('#OJBetter_Bridge_WorkUri').val().replace(/\\/g, '/').replace(/\/$/, ''),
  6472. OJBetter_Bridge_SocketUrl: $('#OJBetter_Bridge_SocketUrl').val(),
  6473. onlineCompilerChoice: $("input[name='compiler']:checked").val(),
  6474. notWaiteLoaded: $("#notWaiteLoaded").prop("checked"),
  6475. updateChannel: $('#updateChannel').val(),
  6476. updateSource: $('#updateSource').val()
  6477. };
  6478. // tempConfigs的数据
  6479. const tempConfigs = {
  6480. 'deepl_config': configManager_deepl.getTempConfig(),
  6481. 'chatgpt_config': configManager_chatgpt.getTempConfig(),
  6482. 'Complet_config': configManager_complet.getTempConfig()
  6483. }
  6484.  
  6485. // 判断是否改变
  6486. let changes = {};
  6487. const combinedConfigs = Object.assign({}, settings, tempConfigs); // 合并settings和tempConfigs对象
  6488. for (const [key, value] of Object.entries(combinedConfigs)) {
  6489. const storedValue = GM_getValue(key);
  6490. if (!OJB_deepEquals(value, storedValue)) {
  6491. changes[key] = { oldValue: storedValue, newValue: value };
  6492. }
  6493. }
  6494.  
  6495. // 如果changes对象不为空,则有变化
  6496. if (Object.keys(changes).length > 0) {
  6497. console.log("Changes detected:", changes);
  6498. const shouldSave = await OJB_createDialog(
  6499. i18next.t('saveSetting.title', { ns: 'dialog' }),
  6500. i18next.t('saveSetting.content', { ns: 'dialog' }),
  6501. [
  6502. i18next.t('saveSetting.buttons.0', { ns: 'dialog' }),
  6503. i18next.t('saveSetting.buttons.1', { ns: 'dialog' })
  6504. ]
  6505. ); // 配置改变保存确认
  6506. if (shouldSave) {
  6507. // 数据校验
  6508. // TODO
  6509. if (settings.deepl_type !== 'free') {
  6510. let selectedIndex = $('input[name="deepl_config_config_item"]:checked').length > 0;
  6511. if (!selectedIndex) {
  6512. $('.deepl_config a').removeClass('active');
  6513. $('.settings-page').removeClass('active');
  6514. $('#sidebar-translation-settings').addClass('active');
  6515. $('#translation-settings').addClass('active');
  6516.  
  6517. $('#deepl_config').addClass('missing');
  6518. return;
  6519. } else {
  6520. $('#deepl_config').removeClass('missing');
  6521. }
  6522. }
  6523. if (settings.translation === "openai") {
  6524. let selectedIndex = $('input[name="chatgpt_config_config_item"]:checked').length > 0;
  6525. if (!selectedIndex) {
  6526. $('.chatgpt_config a').removeClass('active');
  6527. $('.settings-page').removeClass('active');
  6528. $('#sidebar-translation-settings').addClass('active');
  6529. $('#translation-settings').addClass('active');
  6530.  
  6531. $('#chatgpt_config').addClass('missing');
  6532. return;
  6533. } else {
  6534. $('#chatgpt_config').removeClass('missing');
  6535. }
  6536. }
  6537. {
  6538. let selectedIndex = $('input[name="translation"]:checked').length > 0;
  6539. if (!selectedIndex) {
  6540. $('.OJBetter_setting_sidebar a').removeClass('active');
  6541. $('.settings-page').removeClass('active');
  6542. $('#sidebar-translation-settings').addClass('active');
  6543. $('#translation-settings').addClass('active');
  6544.  
  6545. $('#translationServices').addClass('missing');
  6546. return;
  6547. } else {
  6548. $('#translationServices').removeClass('missing');
  6549. }
  6550. }
  6551.  
  6552. // 保存数据
  6553. let refreshPage = false; // 是否需要刷新页面
  6554. for (const [key, value] of Object.entries(settings)) {
  6555. if (!refreshPage && !(key == 'translation' || key == 'darkMode' || key == 'commentTranslationChoice')) {
  6556. if (GM_getValue(key) != value) refreshPage = true;
  6557. }
  6558. GM_setValue(key, value);
  6559. }
  6560. for (const [key, value] of Object.entries(tempConfigs)) {
  6561. if (!refreshPage && (JSON.stringify(GM_getValue(key)) != JSON.stringify(value))) refreshPage = true;
  6562. GM_setValue(key, value);
  6563. }
  6564.  
  6565. if (refreshPage) location.reload();
  6566. else {
  6567. // 切换黑暗模式
  6568. if (OJBetter.basic.darkMode != settings.darkMode) {
  6569. OJBetter.basic.darkMode = settings.darkMode;
  6570. // 移除旧的事件监听器
  6571. changeEventListeners.forEach(listener => {
  6572. mediaQueryList.removeEventListener('change', listener);
  6573. });
  6574.  
  6575. if (OJBetter.basic.darkMode == "follow") {
  6576. changeEventListeners.push(handleColorSchemeChange);
  6577. mediaQueryList.addEventListener('change', handleColorSchemeChange);
  6578. $('html').removeAttr('data-theme');
  6579. } else if (OJBetter.basic.darkMode == "dark") {
  6580. $('html').attr('data-theme', 'dark');
  6581. if (OJBetter.monaco.editor) {
  6582. monaco.editor.setTheme('vs-dark');
  6583. }
  6584. } else {
  6585. $('html').attr('data-theme', 'light');
  6586. if (OJBetter.monaco.editor) {
  6587. monaco.editor.setTheme('vs');
  6588. }
  6589. // 移除旧的事件监听器
  6590. const mediaQueryList = window.matchMedia('(prefers-color-scheme: dark)');
  6591. window.matchMedia('(prefers-color-scheme: dark)');
  6592. }
  6593. }
  6594. // 更新配置信息
  6595. OJBetter.translation.choice = settings.translation;
  6596. OJBetter.translation.comment.choice = settings.commentTranslationChoice;
  6597. }
  6598. }
  6599. }
  6600. OJB_closeAndRemoveModal(settingMenu);
  6601. $settingBtns.prop("disabled", false).removeClass("open");
  6602. });
  6603. });
  6604. };
  6605.  
  6606. // html2markdown转换/处理规则
  6607. const turndownService = new TurndownService({ bulletListMarker: '-' });
  6608.  
  6609. // 保留原始
  6610. turndownService.keep(['del']);
  6611.  
  6612. turndownService.addRule('removeByClass', {
  6613. filter: function (node) {
  6614. return node.classList.contains('html2md-panel') ||
  6615. node.classList.contains('div-btn-copy') ||
  6616. node.classList.contains('btn-copy') ||
  6617. node.classList.contains('overlay')
  6618. },
  6619. replacement: function () {
  6620. return '';
  6621. }
  6622. });
  6623.  
  6624. // inline math
  6625. turndownService.addRule('inline-math', {
  6626. filter: function (node, options) {
  6627. return node.tagName.toLowerCase() == "span" && node.className == "katex";
  6628. },
  6629. replacement: function (content, node) {
  6630. var latex = $(node).find('annotation').text();
  6631. latex = latex.replace(/</g, "&lt;").replace(/>/g, "&gt;");
  6632. return "$" + latex + "$";
  6633. }
  6634. });
  6635.  
  6636. // block math
  6637. turndownService.addRule('block-math', {
  6638. filter: function (node, options) {
  6639. return node.tagName.toLowerCase() == "span" && node.className == "katex-display";
  6640. },
  6641. replacement: function (content, node) {
  6642. var latex = $(node).find('annotation').text();
  6643. latex = latex.replace(/</g, "&lt;").replace(/>/g, "&gt;");
  6644. return "\n$$\n" + latex + "\n$$\n";
  6645. }
  6646. });
  6647.  
  6648. // pre
  6649. turndownService.addRule('pre', {
  6650. filter: function (node, options) {
  6651. return node.tagName.toLowerCase() == "pre";
  6652. },
  6653. replacement: function (content, node) {
  6654. return "```\n" + content + "```\n";
  6655. }
  6656. });
  6657.  
  6658. // bordertable
  6659. turndownService.addRule('bordertable', {
  6660. filter: 'table',
  6661. replacement: function (content, node) {
  6662. if (node.classList.contains('table')) {
  6663. var output = [],
  6664. thead = '',
  6665. trs = node.querySelectorAll('tr');
  6666. if (trs.length > 0) {
  6667. var ths = trs[0].querySelectorAll('th, td');
  6668. if (ths.length > 0) {
  6669. thead = '| ' + Array.from(ths).map(th => turndownService.turndown(th.innerHTML.trim())).join(' | ') + ' |\n'
  6670. thead += '| ' + Array.from(ths).map(() => ' --- ').join('|') + ' |\n';
  6671. }
  6672. }
  6673. var rows = node.querySelectorAll('tr');
  6674. Array.from(rows).forEach(function (row, i) {
  6675. if (i > 0) {
  6676. var cells = row.querySelectorAll('td,th');
  6677. var trow = '| ' + Array.from(cells).map(cell => turndownService.turndown(cell.innerHTML.trim())).join(' | ') + ' |';
  6678. output.push(trow);
  6679. }
  6680. });
  6681. return thead + output.join('\n');
  6682. } else {
  6683. return content;
  6684. }
  6685. }
  6686. });
  6687.  
  6688. /**
  6689. * 任务队列
  6690. */
  6691. class TaskQueue {
  6692. constructor() {
  6693. this.taskQueues = {};
  6694. this.isProcessing = {}; // 处理状态
  6695. this.delays = {}; // 等待时间(毫秒)
  6696. }
  6697.  
  6698. getDelay(type) {
  6699. if (type === 'openai') {
  6700. return 0;
  6701. } else {
  6702. return OJBetter.translation.waitTime;
  6703. }
  6704. }
  6705.  
  6706. /**
  6707. * 添加任务
  6708. * @param {string} type 任务类型
  6709. * @param {function} fn 任务函数
  6710. * @param {boolean} isNonQueueTask 是否为非队列任务
  6711. */
  6712. addTask(type, fn, isNonQueueTask = false) {
  6713. if (!this.taskQueues[type]) {
  6714. this.taskQueues[type] = [];
  6715. }
  6716.  
  6717. if (isNonQueueTask) {
  6718. fn();
  6719. } else {
  6720. this.taskQueues[type].push(fn);
  6721.  
  6722. if (!this.isProcessing[type]) {
  6723. this.processQueue(type);
  6724. }
  6725. }
  6726. }
  6727.  
  6728. async processQueue(type) {
  6729. this.isProcessing[type] = true;
  6730.  
  6731. while (this.taskQueues[type].length > 0) {
  6732. const task = this.taskQueues[type].shift();
  6733. await task();
  6734.  
  6735. if (this.taskQueues[type].length > 0) {
  6736. await this.wait(this.getDelay(type));
  6737. }
  6738. }
  6739.  
  6740. this.isProcessing[type] = false;
  6741. }
  6742.  
  6743. wait(delay) {
  6744. return new Promise(resolve => {
  6745. setTimeout(resolve, delay);
  6746. });
  6747. }
  6748. }
  6749.  
  6750. /**
  6751. * 检测文本是否可能为代码片段
  6752. * @param {string} text 待检测的文本
  6753. * @returns {boolean} 是否可能为代码片段
  6754. */
  6755. function isLikelyCodeSnippet(text) {
  6756. // 过滤文本中可能的HTML标签
  6757. text = OJB_removeHTMLTags(text);
  6758.  
  6759. // 移除LaTeX公式部分
  6760. const cleanedText = text.replace(/(\$\$?[\s\S]*?\$\$?)/g, '');
  6761.  
  6762. // 代码的关键字
  6763. const keywords = [
  6764. 'int', 'float', 'return', 'if', 'else', 'while', 'for', 'switch', 'case', 'break', 'continue',
  6765. 'class', 'public', 'private', 'protected', 'void', 'static', 'const', 'enum', 'struct',
  6766. 'char', 'double', 'long', 'include', 'def', 'import', 'from', 'as', 'elif', 'try', 'except',
  6767. 'raise', 'with', 'lambda', 'print'
  6768. ];
  6769. // 代码的特殊字符
  6770. const codeChars = [';', '{', '}', '>', '<', '<<', '>>', '=', '+', '-',
  6771. '&', '|', ':', '\'\'\'', '\"\"\"', '->'];
  6772.  
  6773. // 普通文本的标点符号
  6774. const textChars = ['.', ',', '?', '!', ':', '"', "'"];
  6775.  
  6776. // 关键字的数量
  6777. const keywordCount = keywords.reduce((count, keyword) => {
  6778. const regex = new RegExp("\\b" + keyword + "\\b", 'gi');
  6779. return count + (cleanedText.match(regex) || []).length;
  6780. }, 0);
  6781.  
  6782. // 代码的特殊字符的数量
  6783. const codeCharCount = codeChars.reduce((count, char) => {
  6784. const regex = new RegExp("\\" + char, 'g');
  6785. return count + (cleanedText.match(regex) || []).length;
  6786. }, 0);
  6787.  
  6788. // 普通文本字符的数量
  6789. const textCharCount = textChars.reduce((count, char) => {
  6790. const regex = new RegExp("\\" + char, 'g');
  6791. return count + (cleanedText.match(regex) || []).length;
  6792. }, 0);
  6793.  
  6794. // 如果代码关键字数量或者代码的特殊字符数量显著高于普通文本标点符号数量,或者存在Python缩进,则可能是代码
  6795. if (keywordCount > textCharCount * 2 || codeCharCount > textCharCount * 2) {
  6796. console.log("keywordCount:", keywordCount, "codeCharCount:", codeCharCount, "textCharCount:", textCharCount);
  6797. return true;
  6798. }
  6799.  
  6800. return false;
  6801. }
  6802.  
  6803. /**
  6804. * 加载按钮相关函数
  6805. */
  6806. async function initButtonFunc() {
  6807. // 鼠标悬浮时为目标元素区域添加一个覆盖层
  6808. $.fn.addHoverOverlay = function (target) {
  6809. let position = $(target).css('position');
  6810. let display = $(target).css('display');
  6811.  
  6812. this.hover(() => {
  6813. $(target)
  6814. .addClass('overlay')
  6815. .css('position', 'relative');
  6816. if (display == "inline" || display == "contents") {
  6817. $(target).css('display', 'block');
  6818. }
  6819. }, () => {
  6820. $(target)
  6821. .removeClass('overlay')
  6822. .css('position', position);
  6823. if (display == "inline" || display == "contents") {
  6824. $(target).css('display', display);
  6825. }
  6826. })
  6827. }
  6828.  
  6829. /**
  6830. * 为按钮设置图标
  6831. * @param {string} icon 图标
  6832. * @returns {JQuery<HTMLElement>} 按钮
  6833. */
  6834. $.fn.setButtonIcon = function (icon) {
  6835. let i = this.find("i");
  6836. if (i.length != 0 && i.hasClass("iconfont")) {
  6837. i.html(icon);
  6838. } else {
  6839. i = OJB_safeCreateJQElement(`<i>${icon}</i>`);
  6840. this.prepend(i);
  6841. }
  6842. return this;
  6843. }
  6844.  
  6845. /**
  6846. * 设置按钮为加载等待状态
  6847. */
  6848. $.fn.setButtonLoading = function () {
  6849. this.addClass("loading");
  6850. this.prop("disabled", true);
  6851. return this;
  6852. }
  6853.  
  6854. /**
  6855. * 解除按钮的加载等待状态
  6856. */
  6857. $.fn.setButtonLoaded = function () {
  6858. this.removeClass("loading");
  6859. this.prop("disabled", false);
  6860. return this;
  6861. }
  6862.  
  6863. /**
  6864. * 为按钮设置popover提示文本
  6865. * @param {string} text 文本
  6866. * @returns {JQuery<HTMLElement>} 按钮
  6867. */
  6868. $.fn.setButtonPopover = function (text) {
  6869. // find if has popover_content class element
  6870. let popover_content = this.find(".popover_content");
  6871. if (popover_content.length != 0) {
  6872. popover_content.text(text);
  6873. } else {
  6874. popover_content = OJB_safeCreateJQElement(`<span class="popover_content">${text}</span>`);
  6875. this.append(popover_content);
  6876. }
  6877. return this;
  6878. }
  6879.  
  6880. /**
  6881. * 获取MarkDown
  6882. * @returns {string} MarkDown
  6883. */
  6884. $.fn.getMarkdown = function () {
  6885. const markdown = this.data('markdown');
  6886. if (markdown === undefined) {
  6887. const htmlContent = this.html();
  6888. const newMarkdown = turndownService.turndown(htmlContent);
  6889. this.data('markdown', newMarkdown);
  6890. return newMarkdown;
  6891. }
  6892. return markdown;
  6893. }
  6894.  
  6895. // 设置按钮状态
  6896. $.fn.setButtonState = function (state, popoverText = null, disabled = false) {
  6897. this.data('buttonState', state)
  6898. .prop('disabled', disabled)
  6899. .css('cursor', disabled ? 'not-allowed' : 'pointer')
  6900. .removeClass('running success enabled error loading redo');
  6901. if (popoverText) this.setButtonPopover(popoverText);
  6902.  
  6903. if (state !== 'initial') this.addClass(state);
  6904. return this;
  6905. };
  6906.  
  6907. // 为按钮添加鼠标悬浮重试
  6908. $.fn.setHoverRedo = function () {
  6909. this.hover(() => {
  6910. prevState = this.getButtonState();
  6911. if (prevState !== "normal" && prevState !== "running") {
  6912. this.setButtonState('redo');
  6913. }
  6914. }, () => {
  6915. const currentState = this.getButtonState();
  6916. if (prevState !== "normal" && ["normal", "redo"].includes(currentState)) {
  6917. this.setButtonState(prevState);
  6918. prevState = null;
  6919. }
  6920. });
  6921. };
  6922.  
  6923. // 获取按钮状态
  6924. $.fn.getButtonState = function () {
  6925. return this.data('buttonState') || 'normal';
  6926. };
  6927.  
  6928. // 设置翻译按钮状态
  6929. $.fn.setTransButtonState = function (state, text = null) {
  6930. const popoverText = text || i18next.t(`trans.${state}`, { ns: 'button' });
  6931. const disabled = state === 'running' || state === 'loading';
  6932. this.setButtonState(state, popoverText, disabled);
  6933. return this;
  6934. };
  6935.  
  6936. // 存翻译结果
  6937. $.fn.pushResultToTransButton = function (result) {
  6938. let resultStack = this.data('resultStack');
  6939. if (!resultStack) resultStack = [];
  6940. resultStack.push(result);
  6941. this.data('resultStack', resultStack);
  6942. }
  6943.  
  6944. // 获取翻译结果
  6945. $.fn.getResultFromTransButton = function () {
  6946. return this.data('resultStack');
  6947. }
  6948.  
  6949. // 标记为不自动翻译
  6950. $.fn.setNotAutoTranslate = function () {
  6951. this.data('notAutoTranslate', true);
  6952. }
  6953.  
  6954. // 获取是否为不自动翻译
  6955. $.fn.getNotAutoTranslate = function () {
  6956. return this.data('notAutoTranslate');
  6957. }
  6958.  
  6959. // 判断是否已经翻译
  6960. $.fn.IsTranslated = function () {
  6961. if (this.hasAttr('translated')) {
  6962. return true;
  6963. } else {
  6964. return false;
  6965. }
  6966. }
  6967.  
  6968. // 判断是否为评论区按钮
  6969. $.fn.IsCommentButton = function () {
  6970. let isCommentButton = this.data('isCommentButton');
  6971. if (isCommentButton == undefined) {
  6972. this.parents('.comments').length > 0 ? isCommentButton = true : isCommentButton = false;
  6973. this.data('isCommentButton', isCommentButton);
  6974. }
  6975. return isCommentButton;
  6976. }
  6977.  
  6978. // 按钮点击效果
  6979. $(document).on('mousedown', '.ojb_btn', function () {
  6980. $(this).addClass('active').on('animationend', () => $(this).removeClass('active'));
  6981. });
  6982. }
  6983.  
  6984. /**
  6985. * 添加题目markdown转换/复制/翻译按钮面板
  6986. * @param {HTMLElement} element 需要添加按钮面板的元素
  6987. * @param {string} suffix 按钮面板id后缀
  6988. * @param {string} type 按钮面板添加位置
  6989. * @param {boolean} is_simple 是否是简单模式
  6990. * @returns {object} 返回按钮面板元素
  6991. */
  6992. function addButtonPanel(element, suffix, type, is_simple = false) {
  6993. let text;
  6994. if (OJBetter.translation.comment.transMode == "1") text = i18next.t('trans.segment', { ns: 'button' });
  6995. else if (OJBetter.translation.comment.transMode == "2") text = i18next.t('trans.select', { ns: 'button' });
  6996. else text = i18next.t('trans.normal', { ns: 'button' });
  6997.  
  6998. let panel = OJB_safeCreateJQElement(`<div class='html2md-panel input-output-copier ${is_simple ? 'is_simple' : ''}'></div>`);
  6999. let viewButton = OJB_safeCreateJQElement(`
  7000. <button class='ojb_btn ojb_btn_popover top' id='html2md-view${suffix}'>
  7001. <i class="iconfont">&#xe7e5;</i>
  7002. <span class="popover_content">${i18next.t('md.normal', { ns: 'button' })}</span>
  7003. </button>`);
  7004. let copyButton = OJB_safeCreateJQElement(`
  7005. <button class='ojb_btn ojb_btn_popover top' id='html2md-cb${suffix}'>
  7006. <i class="iconfont">&#xe608;</i>
  7007. <span class="popover_content">${i18next.t('copy.normal', { ns: 'button' })}</span>
  7008. </button>`);
  7009. let translateButton = OJB_safeCreateJQElement(`
  7010. <button class='ojb_btn translateButton ojb_btn_popover top' id='translateButton${suffix}'>
  7011. <i class="iconfont">&#xe6be;</i>
  7012. <span class="popover_content">${text}</span>
  7013. </button>`);
  7014. if (!is_simple) panel.append(viewButton);
  7015. if (!is_simple) panel.append(copyButton);
  7016. panel.append(translateButton);
  7017. if (type === "this_level") {
  7018. $(element).before(panel);
  7019. } else if (type === "child_level") {
  7020. $(element).prepend(panel);
  7021. }
  7022.  
  7023. return {
  7024. panel: panel,
  7025. viewButton: viewButton,
  7026. copyButton: copyButton,
  7027. translateButton: translateButton
  7028. }
  7029. }
  7030.  
  7031. /**
  7032. * 添加MD视图按钮
  7033. * @param {JQuery<HTMLElement>} button 按钮
  7034. * @param {JQuery<HTMLElement>} element 目标元素
  7035. * @param {string} suffix id后缀
  7036. * @param {string} type 类型
  7037. * @returns {void}
  7038. */
  7039. async function addButtonWithHTML2MD(button, element, suffix, type) {
  7040. /**
  7041. * 改变按钮状态
  7042. * @param {string} state 状态
  7043. */
  7044. function changeButtonState(state) {
  7045. if (state == "loading") {
  7046. button.setButtonLoading();
  7047. button.setButtonPopover(i18next.t('state.waitMathJax', { ns: 'button' }));
  7048. } else if (state == "loaded") {
  7049. button.setButtonLoaded();
  7050. button.setButtonPopover(i18next.t('md.normal', { ns: 'button' }));
  7051. } else if (state == "normal") {
  7052. button.removeClass("enabled");
  7053. button.setButtonPopover(i18next.t('md.normal', { ns: 'button' }));
  7054. } else if (state == "mdView") {
  7055. button.addClass("enabled");
  7056. button.setButtonPopover(i18next.t('md.reduction', { ns: 'button' }));
  7057. } else if (state == "disabled") {
  7058. button.prop("disabled", true);
  7059. button.setButtonPopover(i18next.t('md.disabled', { ns: 'button' }));
  7060. }
  7061. }
  7062.  
  7063. if (OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru) {
  7064. changeButtonState("disabled");
  7065. return;
  7066. } else {
  7067. changeButtonState("loading");
  7068. await waitForMathJaxIdle();
  7069. changeButtonState("loaded");
  7070. }
  7071.  
  7072. button.click(OJB_debounce(function () {
  7073. var target = $(element).get(0);
  7074.  
  7075. /**
  7076. * 检查是否是MarkDown视图
  7077. * @returns {boolean} 是否是MarkDown视图
  7078. */
  7079. function checkViewmd() {
  7080. if ($(element).attr("viewmd") === "true") {
  7081. return true;
  7082. } else {
  7083. return false;
  7084. }
  7085. }
  7086.  
  7087. /**
  7088. * 设置是否是MarkDown视图
  7089. * @param {boolean} value 是否是MarkDown视图
  7090. * @returns {void}
  7091. */
  7092. function setViewmd(value) {
  7093. $(element).attr("viewmd", value);
  7094. if (value) {
  7095. changeButtonState("mdView");
  7096. } else {
  7097. changeButtonState("normal");
  7098. }
  7099. }
  7100.  
  7101. if (checkViewmd()) {
  7102. setViewmd(false);
  7103. $(element).next(".mdViewContent").remove();
  7104. $(element).show();
  7105. } else {
  7106. setViewmd(true);
  7107. var markdown = $(element).getMarkdown();
  7108. var mdViewContent = OJB_safeCreateJQElement(`<span class="mdViewContent" style="width:auto; height:auto;">${markdown}</span>`);
  7109. $(element).after(mdViewContent);
  7110. $(element).hide();
  7111. }
  7112. }));
  7113.  
  7114. if (OJBetter.preference.hoverTargetAreaDisplay && !OJBetter.typeOfPage.is_oldLatex && !OJBetter.typeOfPage.is_acmsguru) {
  7115. button.addHoverOverlay($(element));
  7116. }
  7117. }
  7118.  
  7119. /**
  7120. * 添加复制按钮
  7121. * @param {JQuery<HTMLElement>} button 按钮
  7122. * @param {JQuery<HTMLElement>} element 目标元素
  7123. * @param {string} suffix 后缀
  7124. * @param {string} type 类型
  7125. */
  7126. async function addButtonWithCopy(button, element, suffix, type) {
  7127. /**
  7128. * 改变按钮状态
  7129. * @param {string} state 状态
  7130. */
  7131. function changeButtonState(state) {
  7132. if (state == "loading") {
  7133. button.setButtonLoading();
  7134. button.setButtonPopover(i18next.t('state.waitMathJax', { ns: 'button' }));
  7135. } else if (state == "loaded") {
  7136. button.setButtonLoaded();
  7137. button.setButtonPopover(i18next.t('copy.normal', { ns: 'button' }));
  7138. } else if (state == "normal") {
  7139. button.setButtonPopover(i18next.t('copy.normal', { ns: 'button' }));
  7140. } else if (state == "copied") {
  7141. button.setButtonPopover(i18next.t('copy.copied', { ns: 'button' }));
  7142. } else if (state == "disabled") {
  7143. button.prop("disabled", true);
  7144. button.setButtonPopover(i18next.t('copy.disabled', { ns: 'button' }));
  7145. }
  7146. }
  7147.  
  7148. // 等待MathJax队列完成
  7149. if (OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru) {
  7150. changeButtonState("disabled");
  7151. return;
  7152. } else {
  7153. changeButtonState("loading");
  7154. await waitForMathJaxIdle();
  7155. changeButtonState("loaded");
  7156. }
  7157.  
  7158. button.click(OJB_debounce(function () {
  7159. var target = $(element).get(0);
  7160.  
  7161. var markdown = $(element).getMarkdown();
  7162.  
  7163. GM_setClipboard(markdown);
  7164.  
  7165. $(this).addClass("success");
  7166. changeButtonState("copied");
  7167.  
  7168.  
  7169. // 更新复制按钮文本
  7170. setTimeout(() => {
  7171. $(this).removeClass("success");
  7172. changeButtonState("normal")
  7173. }, 2000);
  7174. }));
  7175.  
  7176. if (OJBetter.preference.hoverTargetAreaDisplay && !OJBetter.typeOfPage.is_oldLatex && !OJBetter.typeOfPage.is_acmsguru) {
  7177. button.addHoverOverlay($(element));
  7178. }
  7179. }
  7180.  
  7181. /**
  7182. * 添加翻译按钮
  7183. * @param {JQuery<HTMLElement>} button 按钮
  7184. * @param {JQuery<HTMLElement>} element 目标元素
  7185. * @param {string} suffix 后缀
  7186. * @param {string} type 类型
  7187. * @param {boolean} is_comment 是否是评论
  7188. */
  7189. async function addButtonWithTranslation(button, element, suffix, type, is_comment = false) {
  7190. // 添加可指定翻译服务的方法调用
  7191. button.data("translatedItBy", function (translation) {
  7192. button.setTransButtonState('running', i18next.t('trans.wait', { ns: 'button' }));
  7193. OJBetter.common.taskQueue.addTask(translation, () => transTask(button, element, type, is_comment, translation), translation == 'openai');
  7194. });
  7195.  
  7196. // 等待MathJax队列完成
  7197. button.setButtonLoading();
  7198. await waitForMathJaxIdle();
  7199. button.setButtonLoaded();
  7200.  
  7201. // 标记目标文本区域不自动翻译
  7202. {
  7203. let text;
  7204. if (OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru) {
  7205. text = $(element).html();
  7206. } else {
  7207. text = $(element).getMarkdown();
  7208. }
  7209. let length = text.length;
  7210. if (length > OJBetter.translation.auto.shortTextLength || isLikelyCodeSnippet(text)) {
  7211. button.setNotAutoTranslate();
  7212. }
  7213. // button.after(`<span>${length}</span>`); // 显示字符数
  7214. }
  7215.  
  7216. button.click(OJB_debounce(async function () {
  7217. // 重新翻译
  7218. let resultStack = $(this).getResultFromTransButton();
  7219. if (resultStack) {
  7220. let pElements = $(element).find("p.block_selected:not(li p), li.block_selected");
  7221. for (let item of resultStack) {
  7222. if (OJBetter.translation.retransAction == "0") {
  7223. // 选段翻译不直接移除旧结果
  7224. if (OJBetter.translation.comment.transMode == "2") {
  7225. // 只移除即将要翻译的段的结果
  7226. if (pElements.is(item.translateDiv.getDiv().prev())) {
  7227. item.translateDiv.close();
  7228. }
  7229. } else {
  7230. item.translateDiv.close();
  7231. $($(element)).find(".translate-problem-statement, .translate-problem-statement-panel").remove();
  7232. }
  7233. } else {
  7234. item.translateDiv.foldMainDiv();
  7235. }
  7236. }
  7237. }
  7238.  
  7239. // 翻译
  7240. button.setTransButtonState('running', i18next.t('trans.wait', { ns: 'button' }));
  7241. OJBetter.common.taskQueue.addTask(OJBetter.translation.choice, () => transTask(button, element, type, is_comment), OJBetter.translation.choice == 'openai');
  7242. }));
  7243.  
  7244. // 重新翻译提示
  7245. let prevState;
  7246. button.hover(() => {
  7247. prevState = button.getButtonState();
  7248. if (prevState !== "normal" && prevState !== "running") {
  7249. button.setTransButtonState('redo');
  7250. }
  7251. }, () => {
  7252. const currentState = button.getButtonState();
  7253. if (prevState !== "normal" && ["normal", "redo"].includes(currentState)) {
  7254. button.setTransButtonState(prevState);
  7255. prevState = null;
  7256. }
  7257. });
  7258.  
  7259. // 目标区域指示
  7260. if (OJBetter.preference.hoverTargetAreaDisplay) {
  7261. button.addHoverOverlay($(element));
  7262. }
  7263.  
  7264. // 翻译右键切换菜单
  7265. $(document).on('contextmenu', '#translateButton' + suffix, function (e) {
  7266. e.preventDefault();
  7267.  
  7268. // 是否为评论的翻译
  7269. let is_comment = button.IsCommentButton();
  7270.  
  7271. // 移除旧的
  7272. if (!$(e.target).closest('.OJBetter_contextmenu').length) {
  7273. $('.OJBetter_contextmenu').remove();
  7274. }
  7275.  
  7276. var menu = $('<div class="OJBetter_contextmenu"></div>');
  7277. var translations = [
  7278. { value: 'deepl', name: i18next.t('translation.options.services.deepl', { ns: 'settings' }) },
  7279. { value: 'iflyrec', name: i18next.t('translation.options.services.iflyrec', { ns: 'settings' }) },
  7280. { value: 'youdao', name: i18next.t('translation.options.services.youdao', { ns: 'settings' }) },
  7281. { value: 'google', name: i18next.t('translation.options.services.google', { ns: 'settings' }) },
  7282. { value: 'caiyun', name: i18next.t('translation.options.services.caiyun', { ns: 'settings' }) },
  7283. { value: 'openai', name: i18next.t('translation.options.services.openai.name', { ns: 'settings' }) }
  7284. ];
  7285.  
  7286. // Function to check if the service supports the target language
  7287. function supportsTargetLanguage(service, targetLang) {
  7288. return OJBetter.supportList.translationSupport[service] && OJBetter.supportList.translationSupport[service][targetLang] !== undefined;
  7289. }
  7290.  
  7291. if (is_comment) {
  7292. var label = OJB_safeCreateJQElement(`<label><input type="radio" name="translation" value="0">
  7293. <span class="OJBetter_contextmenu_label_text">
  7294. ${i18next.t('translation.preference.comment_translation_choice.services.follow', { ns: 'settings' })}
  7295. </span></label>`);
  7296. menu.append(label);
  7297. }
  7298. translations.forEach(function (translation) {
  7299. if (supportsTargetLanguage(translation.value, OJBetter.translation.targetLang)) {
  7300. var label = OJB_safeCreateJQElement(`<label><input type="radio" name="translation" value="${translation.value}">
  7301. <span class="OJBetter_contextmenu_label_text">${translation.name}</span></label>`);
  7302. menu.append(label);
  7303. }
  7304. });
  7305.  
  7306. // 初始化
  7307. if (is_comment) {
  7308. menu.find(`input[name="translation"][value="${OJBetter.translation.comment.choice}"]`).prop('checked', true);
  7309. } else {
  7310. menu.find(`input[name="translation"][value="${OJBetter.translation.choice}"]`).prop('checked', true);
  7311. }
  7312. menu.css({
  7313. top: e.pageY + 'px',
  7314. left: e.pageX + 'px'
  7315. }).appendTo('body');
  7316.  
  7317. $(document).one('change', 'input[name="translation"]', function () {
  7318. if (is_comment) {
  7319. OJBetter.translation.comment.choice = $('input[name="translation"]:checked').val();
  7320. GM_setValue("commentTranslationChoice", OJBetter.translation.comment.choice);
  7321. } else {
  7322. OJBetter.translation.choice = $('input[name="translation"]:checked').val();
  7323. GM_setValue("translation", OJBetter.translation.choice);
  7324. }
  7325. $('.OJBetter_contextmenu').remove();
  7326. });
  7327.  
  7328. // 点击区域外关闭菜单
  7329. function handleClick(event) {
  7330. if (!$(event.target).closest('.OJBetter_contextmenu').length) {
  7331. $('.OJBetter_contextmenu').remove();
  7332. $(document).off('change', 'input[name="translation"]');
  7333. } else {
  7334. $(document).one('click', handleClick);
  7335. }
  7336. }
  7337. $(document).one('click', handleClick);
  7338. });
  7339. }
  7340.  
  7341. /**
  7342. * 创建翻译任务
  7343. * @param {JQuery<HTMLElement>} button 按钮
  7344. * @param {HTMLElement} element 目标元素
  7345. * @param {string} type 类型
  7346. * @param {boolean} is_comment 是否是评论
  7347. * @param {string} overrideTrans 覆盖全局翻译服务设定
  7348. */
  7349. async function transTask(button, element, type, is_comment, overrideTrans) {
  7350. /** @type {HTMLElement} 目标元素 */
  7351. let target;
  7352. /**
  7353. * 错误计数数据结构
  7354. * @typedef {Object} count
  7355. * @property {number} errerNum 错误数量
  7356. * @property {number} skipNum 跳过数量
  7357. */
  7358. const count = {
  7359. errerNum: 0,
  7360. skipNum: 0
  7361. };
  7362. if (OJBetter.translation.comment.transMode == "1") {
  7363. // 分段翻译
  7364. let pElements = $(element).find("p:not(li p), li, .OJBetter_acmsguru");
  7365. for (let i = 0; i < pElements.length; i++) {
  7366. target = $(pElements[i]).eq(0).clone();
  7367. element_node = pElements[i];
  7368. await process(button, target, element_node, type, is_comment, count, overrideTrans);
  7369. }
  7370. } else if (OJBetter.translation.comment.transMode == "2") {
  7371. // 选段翻译
  7372. let pElements = $(element).find("p.block_selected:not(li p), li.block_selected, .OJBetter_acmsguru");
  7373. for (let i = 0; i < pElements.length; i++) {
  7374. target = $(pElements[i]).eq(0).clone();
  7375. element_node = pElements[i];
  7376. await process(button, target, element_node, type, is_comment, count, overrideTrans);
  7377. }
  7378. $(element).find("p.block_selected:not(li p), li.block_selected").removeClass('block_selected');
  7379. } else {
  7380. // 普通翻译
  7381. target = $(element).eq(0).clone();
  7382. if (type === "child_level") $(target).children(':first').remove();
  7383. element_node = $($(element)).get(0);
  7384. await process(button, target, element_node, type, is_comment, count, overrideTrans);
  7385. }
  7386.  
  7387. // 翻译完成
  7388. if (!count.errerNum && !count.skipNum) {
  7389. button.setTransButtonState('success');
  7390. }
  7391. }
  7392.  
  7393. /**
  7394. * 翻译处理
  7395. * @param {JQuery<HTMLElement>} button 按钮
  7396. * @param {HTMLElement} target 目标元素
  7397. * @param {HTMLElement} element_node 目标节点
  7398. * @param {string} type 类型
  7399. * @param {boolean} is_comment 是否是评论
  7400. * @param {string} overrideTrans 覆盖全局翻译服务设定
  7401. */
  7402. async function process(button, target, element_node, type, is_comment, count, overrideTrans) {
  7403. if (type === "child_level") {
  7404. let div = $("<div>");
  7405. $(element_node).append(div);
  7406. element_node = div.get(0);
  7407. }
  7408.  
  7409. //是否跳过折叠块
  7410. if ($(target).find('.spoiler').length > 0) {
  7411. const shouldSkip = await OJB_createDialog(
  7412. i18next.t('skipFold.title', { ns: 'dialog' }),
  7413. i18next.t('skipFold.content', { ns: 'dialog' }),
  7414. [
  7415. i18next.t('skipFold.buttons.0', { ns: 'dialog' }),
  7416. i18next.t('skipFold.buttons.1', { ns: 'dialog' })
  7417. ],
  7418. true
  7419. ); //跳过折叠块确认
  7420. if (shouldSkip) {
  7421. $(target).find('.spoiler').remove();
  7422. } else {
  7423. $(target).find('.html2md-panel').remove();
  7424. }
  7425. }
  7426.  
  7427. // 等待并获取结果
  7428. button.setTransButtonState('running');
  7429. const result = await blockProcessing(button, target, element_node, is_comment, overrideTrans);
  7430. button.pushResultToTransButton(result);
  7431.  
  7432. if (result.status == "error") count.errerNum += 1;
  7433. else if (result.status == "skip") count.skipNum += 1;
  7434. $(target).remove();
  7435. }
  7436.  
  7437. /**
  7438. * 块处理
  7439. * @param {JQuery<HTMLElement>} button
  7440. * @param {HTMLElement} target 目标元素
  7441. * @param {HTMLElement} element_node 目标节点
  7442. * @param {boolean} is_comment 是否是评论
  7443. * @param {string} overrideTrans 覆盖全局翻译服务设定
  7444. * @returns {TranslateResult} 翻译结果对象
  7445. */
  7446. async function blockProcessing(button, target, element_node, is_comment, overrideTrans) {
  7447. if (OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru) {
  7448. target.markdown = $(target).html();
  7449. } else if (!target.markdown) {
  7450. target.markdown = turndownService.turndown($(target).html());
  7451. }
  7452.  
  7453. const result = await translateProblemStatement(target.markdown, element_node, is_comment, overrideTrans);
  7454. if (result.status == "skip") {
  7455. button.setTransButtonState('error', i18next.t('trans.tooLong', { ns: 'button' }));
  7456. result.translateDiv.close();
  7457. } else if (result.status == "error" || !result.rawData.done) {
  7458. result.translateDiv.setError();
  7459. result.translateDiv.setRawData(result.rawData);
  7460. result.translateDiv.showDebugButton();
  7461. button.setTransButtonState('error', i18next.t('trans.error', { ns: 'button' }));
  7462. $(target).remove();
  7463. }
  7464. return result;
  7465. }
  7466.  
  7467. /**
  7468. * 选段翻译支持
  7469. */
  7470. async function multiChoiceTranslation() {
  7471. GM_addStyle(`
  7472. .topic .content #task-statement {
  7473. overflow: initial;
  7474. }
  7475. `);
  7476.  
  7477. $(document).on('click', 'p, li:not(:has(.comment)), .OJBetter_acmsguru', function (e) {
  7478. let $this = $(this);
  7479. e.stopPropagation();
  7480. if ($this.hasClass('block_selected')) {
  7481. $this.removeClass('block_selected');
  7482. // 移除对应的按钮
  7483. $('.OJBetter_MiniTranslateButton').remove("#translateButton_selected_" + $this.attr('OJBetter_p_id'));
  7484. } else {
  7485. let id = OJB_getRandomNumber(8);
  7486. $this.attr('OJBetter_p_id', id);
  7487. $this.addClass('block_selected');
  7488. // 添加按钮
  7489. let menu = OJB_safeCreateJQElement(`<div class="OJBetter_MiniTranslateButton" id='translateButton_selected_${id}'>${translateIcon}</div>`)
  7490. .css({
  7491. left: $($this).outerWidth(true) + $($this).position().left + 10 + 'px',
  7492. });
  7493. $this.before(menu);
  7494.  
  7495. $("#translateButton_selected_" + id).click(async function () {
  7496. // 处理旧的结果
  7497. if ($this.attr('translated')) {
  7498. let result = $this.data("resultData");
  7499. if (OJBetter.translation.retransAction == "0") {
  7500. result.translateDiv.close();
  7501. } else {
  7502. result.translateDiv.foldMainDiv();
  7503. }
  7504. }
  7505. // 翻译
  7506. let target = $this.eq(0).clone();
  7507. let result = await blockProcessing(OJBetter.translation.choice, target, $this.eq(0), $("#translateButton_selected_" + id), false);
  7508. $this.data("resultData", result);
  7509. $this.removeClass('block_selected');
  7510. // 移除对应的按钮
  7511. $('.OJBetter_MiniTranslateButton').remove("#translateButton_selected_" + id);
  7512. $this.attr('translated', '1'); // 标记已翻译
  7513. });
  7514. }
  7515. });
  7516. }
  7517.  
  7518. /**
  7519. * 添加MD/复制/翻译按钮
  7520. */
  7521. async function addConversionButton() {
  7522. // 基本添加
  7523. if (!OJBetter.typeOfPage.is_homepage) {
  7524. $('section').each(function () {
  7525. let id = "_" + OJB_getRandomNumber(8);
  7526. let panel = addButtonPanel(this, id, "this_level");
  7527. addButtonWithHTML2MD(panel.viewButton, this, id, "this_level");
  7528. addButtonWithCopy(panel.copyButton, this, id, "this_level");
  7529. addButtonWithTranslation(panel.translateButton, this, id, "this_level");
  7530. });
  7531. }
  7532.  
  7533. // 添加按钮到题解部分
  7534. if (window.location.href.includes("editorial")) {
  7535. let contestNavTabs = $("#contest-nav-tabs");
  7536. let nextElement = contestNavTabs.next();
  7537. let id = "_editorial_" + OJB_getRandomNumber(8);
  7538. let panel = addButtonPanel(nextElement, id, "child_level");
  7539. addButtonWithHTML2MD(panel.viewButton, nextElement, id, "child_level");
  7540. addButtonWithCopy(panel.copyButton, nextElement, id, "child_level");
  7541. addButtonWithTranslation(panel.translateButton, nextElement, id, "child_level");
  7542. }
  7543. if (window.location.href.includes("editorial")) {
  7544. let contestNavTabs = $("#contest-nav-tabs");
  7545. let nextElement = contestNavTabs.next().children().eq(-2);
  7546. let id = "_editorial_" + OJB_getRandomNumber(8);
  7547. let panel = addButtonPanel(nextElement, id, "child_level");
  7548. addButtonWithHTML2MD(panel.viewButton, nextElement, id, "child_level");
  7549. addButtonWithCopy(panel.copyButton, nextElement, id, "child_level");
  7550. addButtonWithTranslation(panel.translateButton, nextElement, id, "child_level");
  7551. }
  7552.  
  7553. // 添加按钮到折叠块部分
  7554. $('details').each(function () {
  7555. // 自定义测试样例折叠块不添加
  7556. if ($(this).attr('id') !== "customTestBlock") {
  7557. let id = "_details_" + OJB_getRandomNumber(8);
  7558. let panel = addButtonPanel(this, id, "child_level");
  7559. addButtonWithHTML2MD(panel.viewButton, this, id, "child_level");
  7560. addButtonWithCopy(panel.copyButton, this, id, "child_level");
  7561. addButtonWithTranslation(panel.translateButton, this, id, "child_level");
  7562. }
  7563. });
  7564.  
  7565. // 添加到contest-statement部分
  7566. $('#contest-statement').each(function () {
  7567. let id = "_contest-statement_" + OJB_getRandomNumber(8);
  7568. let panel = addButtonPanel(this, id, "this_level");
  7569. addButtonWithHTML2MD(panel.viewButton, this, id, "this_level");
  7570. addButtonWithCopy(panel.copyButton, this, id, "this_level");
  7571. addButtonWithTranslation(panel.translateButton, this, id, "this_level");
  7572. });
  7573.  
  7574. // 添加到blog-post部分
  7575. $('.blog-post').each(function () {
  7576. let id = "_blog-post_" + OJB_getRandomNumber(8);
  7577. let panel = addButtonPanel(this, id, "this_level");
  7578. addButtonWithHTML2MD(panel.viewButton, this, id, "this_level");
  7579. addButtonWithCopy(panel.copyButton, this, id, "this_level");
  7580. addButtonWithTranslation(panel.translateButton, this, id, "this_level");
  7581. });
  7582. };
  7583.  
  7584. /**
  7585. * 等待LaTeX渲染队列全部完成
  7586. * @returns {Promise} 完成渲染
  7587. */
  7588. function waitForMathJaxIdle() {
  7589. return true;
  7590. // return new Promise((resolve, reject) => {
  7591. // // 检查MathJax对象是否存在
  7592. // const checkMathJaxExists = () => {
  7593. // if (typeof MathJax === 'undefined') {
  7594. // // 如果MathJax不存在,稍后再次检查
  7595. // OJB_delay(100).then(checkMathJaxExists);
  7596. // } else {
  7597. // // MathJax存在,开始监视渲染队列
  7598. // startMonitoringQueue();
  7599. // }
  7600. // };
  7601.  
  7602. // // 开始监视MathJax渲染队列
  7603. // const startMonitoringQueue = () => {
  7604. // const intervalId = setInterval(() => {
  7605. // const queue = MathJax.Hub.queue;
  7606. // if (queue.pending === 0 && queue.running === 0) {
  7607. // clearInterval(intervalId);
  7608. // resolve();
  7609. // }
  7610. // }, 100);
  7611. // };
  7612.  
  7613. // // 开始检查MathJax对象
  7614. // checkMathJaxExists();
  7615. // });
  7616. }
  7617.  
  7618. /**
  7619. * 翻译结果面板
  7620. */
  7621. class TranslateDiv {
  7622. /**
  7623. * 构造函数
  7624. * @param {string} id 指定翻译框的id
  7625. */
  7626. constructor(id) {
  7627. this.id = id;
  7628. this.div = $('<div>').attr('id', id).addClass('translateDiv bounce-in');
  7629. if (!OJBetter.typeOfPage.is_completeProblemset) {
  7630. this.div.addClass('input-output-copier');
  7631. }
  7632. this.panelDiv = $('<div>').addClass('translate-problem-statement-panel');
  7633. this.div.append(this.panelDiv);
  7634.  
  7635. // 主要信息
  7636. this.mainDiv = $('<div>').addClass('translate-problem-statement');
  7637. this.span = $('<span>');
  7638. this.mainDiv.append(this.span);
  7639. this.div.append(this.mainDiv);
  7640. this.mainDivState = {
  7641. current: 'transHTML',
  7642. transHTML: '',
  7643. rawDataHTML: ''
  7644. };
  7645.  
  7646. // 顶栏信息
  7647. this.topText = $('<div>').addClass('topText');
  7648. this.panelDiv.append(this.topText);
  7649.  
  7650. // 右侧
  7651. this.rightDiv = $('<div>').css('display', 'flex');
  7652. this.panelDiv.append(this.rightDiv);
  7653. this.debugButton = OJB_safeCreateJQElement(`
  7654. <button class='ojb_btn ojb_btn_popover top'>
  7655. <i class="iconfont">&#xe641;</i>
  7656. <span class="popover_content">${i18next.t('rawData.normal', { ns: 'button' })}</span>
  7657. </button>`).hide();
  7658. this.rightDiv.append(this.debugButton);
  7659. this.queryBalanceButton = OJB_safeCreateJQElement(`
  7660. <button class='ojb_btn ojb_btn_popover top'>
  7661. <i class="iconfont">&#xe6ae;</i>
  7662. <span class="popover_content">${i18next.t('queryBalance.normal', { ns: 'button' })}</span>
  7663. </button>`).hide();
  7664. this.rightDiv.append(this.queryBalanceButton);
  7665. this.copyButton = OJB_safeCreateJQElement(`
  7666. <button class='ojb_btn ojb_btn_popover top'>
  7667. <i class="iconfont">&#xe608;</i>
  7668. <span class="popover_content">${i18next.t('copy.normal', { ns: 'button' })}</span>
  7669. </button>`);
  7670. this.rightDiv.append(this.copyButton);
  7671. this.upButton = OJB_safeCreateJQElement(`
  7672. <button class='ojb_btn ojb_btn_popover top'>
  7673. <i class="iconfont">&#xe601;</i>
  7674. <span class="popover_content">${i18next.t('fold.normal', { ns: 'button' })}</span>
  7675. </button>`);
  7676. this.rightDiv.append(this.upButton);
  7677. this.closeButton = OJB_safeCreateJQElement(`
  7678. <button class='ojb_btn ojb_btn_popover top'>
  7679. <i class="iconfont">&#xe614;</i>
  7680. <span class="popover_content">${i18next.t('close.normal', { ns: 'button' })}</span>
  7681. </button>`);
  7682. this.rightDiv.append(this.closeButton);
  7683. }
  7684.  
  7685. /**
  7686. * 获取翻译框
  7687. * @returns {JQuery<HTMLElement>} 返回翻译框
  7688. */
  7689. getDiv() {
  7690. return this.div;
  7691. }
  7692.  
  7693. /**
  7694. * 设置翻译框顶部的文本
  7695. * @param {string} text 翻译框顶部的文本
  7696. */
  7697. setTopText(text) {
  7698. this.div.attr("data-topText", text);
  7699. this.topText.text(text);
  7700. }
  7701.  
  7702. /**
  7703. * 获取翻译框顶部的文本
  7704. * @returns {string} 返回翻译框顶部的文本
  7705. */
  7706. getTopText() {
  7707. return this.topText.text();
  7708. }
  7709.  
  7710. /**
  7711. * 渲染一个元素内的LaTeX公式
  7712. * @param {*} element
  7713. */
  7714. renderLaTeX(element) {
  7715. const latexRenderOptions = {
  7716. delimiters: [
  7717. { left: "$$", right: "$$", display: true },
  7718. { left: "\$$", right: "\\$$", display: true },
  7719. { left: "$", right: "$", display: false },
  7720. { left: "\$$", right: "\\$$", display: false }
  7721. ]
  7722. };
  7723.  
  7724. if (typeof renderMathInElement === 'function') {
  7725. renderMathInElement(element, latexRenderOptions);
  7726. }
  7727. }
  7728.  
  7729. /**
  7730. * 更新翻译框内容
  7731. * @param {string} text 文本内容
  7732. * @param {boolean} is_escapeHTML 是否转义HTML标签,为true则HTML标签将作为普通文本处理,默认为true
  7733. * @param {boolean} is_renderLaTeX 是否渲染LaTeX,为true则会渲染LaTeX,默认为true
  7734. */
  7735. updateTranslateDiv(text, is_escapeHTML = true, is_renderLaTeX = true,) {
  7736. // 渲染MarkDown
  7737. let md = window.markdownit({
  7738. html: !is_escapeHTML,
  7739. });
  7740. if (!text) text = "";
  7741. let html = md.render(text);
  7742. this.mainDiv.html(html);
  7743.  
  7744. // 渲染Latex
  7745. if (is_renderLaTeX) {
  7746. // MathJax.Hub.Queue(["Typeset", MathJax.Hub, this.mainDiv.get(0)]);
  7747. this.renderLaTeX(this.mainDiv.get(0));
  7748. }
  7749. // 渲染代码块中的公式 (AtCoder)
  7750. this.mainDiv.find('pre code').each((index, element) => {
  7751. const codeText = $(element).text();
  7752. const latexPattern = /\$\$(\\.|[^\$])*?\$\$|\$(\\.|[^\$])*?\$/;
  7753. if (latexPattern.test(codeText)) {
  7754. this.renderLaTeX(element);
  7755. }
  7756. });
  7757. }
  7758.  
  7759. /**
  7760. * 关闭元素
  7761. */
  7762. close() {
  7763. this.closeButton.click();
  7764. }
  7765.  
  7766. /**
  7767. * 注册收起按钮事件
  7768. */
  7769. registerUpButtonEvent() {
  7770. this.upButton.on("click", () => {
  7771. // 如果没有reverse类,说明是展开状态
  7772. if (!this.upButton.hasClass("reverse")) {
  7773. // 执行收起操作
  7774. this.upButton.addClass("reverse");
  7775. this.upButton.setButtonState('initial', i18next.t('fold.unfold', { ns: 'button' }));
  7776. OJB_toggleCollapseExpand(this.mainDiv.get(0));
  7777. } else {
  7778. // 执行展开操作
  7779. this.upButton.removeClass("reverse");
  7780. this.upButton.setButtonState('initial', i18next.t('fold.normal', { ns: 'button' }));
  7781. OJB_toggleCollapseExpand(this.mainDiv.get(0));
  7782. }
  7783. });
  7784. }
  7785.  
  7786. /**
  7787. * 注册关闭按钮事件
  7788. */
  7789. registerCloseButtonEvent() {
  7790. this.closeButton.on("click", () => {
  7791. $(this.div).remove();
  7792. $(this.panelDiv).remove();
  7793. if (OJBetter.typeOfPage.is_problem && OJBetter.translation.memory.enabled) {
  7794. OJBetter.translation.memory.ttTree.rmTransResultMap(this.id); // 移除ttTree中的数据
  7795. OJBetter.translation.memory.ttTree.refreshNode("#task-statement");
  7796. updateTransDBData(OJBetter.translation.memory.ttTree.getNodeData(), OJBetter.translation.memory.ttTree.getTransResultMap()); // 更新DB中的数据
  7797. }
  7798. });
  7799. }
  7800.  
  7801. /**
  7802. * 注册复制按钮事件
  7803. * @param {string} text 复制的文本
  7804. */
  7805. registerCopyButtonEvent(text) {
  7806. this.copyButton.on("click", () => {
  7807. GM_setClipboard(text);
  7808. this.copyButton.setButtonState('success', i18next.t('copy.copied', { ns: 'button' }));
  7809. // 复制提示
  7810. setTimeout(() => {
  7811. this.copyButton.setButtonState('initial', i18next.t('copy.normal', { ns: 'button' }));
  7812. }, 2000);
  7813. });
  7814. }
  7815.  
  7816. /**
  7817. * 禁用复制按钮
  7818. */
  7819. disableCopyButton() {
  7820. this.copyButton.css({ 'fill': '#ccc' });
  7821. this.copyButton.off("click");
  7822. }
  7823.  
  7824. /**
  7825. * 设置面板为error状态
  7826. */
  7827. setError() {
  7828. this.div.addClass('error');
  7829. this.panelDiv.addClass('error');
  7830. this.mainDiv.addClass('error');
  7831. }
  7832.  
  7833. /**
  7834. * 设置原始数据数据
  7835. * @param {Object} Object 原始数据
  7836. */
  7837. setRawData(Object) {
  7838. this.mainDivState.rawDataHTML = $("<pre>").text(JSON.stringify(Object, null, 4)).get(0);
  7839. if (this.mainDivState.current === 'rawDataHTML') {
  7840. this.renderMainDiv();
  7841. }
  7842. }
  7843.  
  7844. /**
  7845. * 切换结果面板与原始数据面板
  7846. */
  7847. switchMainDiv() {
  7848. // 在切换之前,保存当前内容的状态
  7849. this.mainDivState[this.mainDivState.current] = this.mainDiv.html();
  7850. // 切换当前状态
  7851. this.debugButton.setButtonState(this.mainDivState.current === 'transHTML' ? 'enabled' : 'initial');
  7852. this.mainDivState.current = this.mainDivState.current === 'transHTML' ? 'rawDataHTML' : 'transHTML';
  7853. // 渲染新的当前状态
  7854. this.renderMainDiv();
  7855. }
  7856.  
  7857. // 渲染当前内容到 mainDiv
  7858. renderMainDiv() {
  7859. requestAnimationFrame(() => {
  7860. this.mainDiv.html(this.mainDivState[this.mainDivState.current]);
  7861. });
  7862. }
  7863.  
  7864. /**
  7865. * 注册debug按钮事件
  7866. */
  7867. registerDebugButtonEvent() {
  7868. this.debugButton.on("click", () => {
  7869. this.switchMainDiv();
  7870. });
  7871. }
  7872.  
  7873. /**
  7874. * 显示debug按钮
  7875. */
  7876. showDebugButton() {
  7877. this.debugButton.show();
  7878. this.registerDebugButtonEvent();
  7879. }
  7880.  
  7881. /**
  7882. * 注册查询余额按钮事件
  7883. * @param {function} callback 查询回调函数
  7884. */
  7885. registerQueryBalanceButtonEvent(callback) {
  7886. this.queryBalanceButton.on("click", async () => {
  7887. this.queryBalanceButton.setButtonState('loading', i18next.t('queryBalance.loading', { ns: 'button' }));
  7888. try {
  7889. const balance = await callback();
  7890. this.queryBalanceButton.setButtonState('success', `${i18next.t('queryBalance.success', { ns: 'button' })} ${balance}`);
  7891. } catch (error) {
  7892. this.queryBalanceButton.setButtonState('error', `${i18next.t('queryBalance.error', { ns: 'button' })} ${error.message}`);
  7893. }
  7894. });
  7895. }
  7896.  
  7897. /**
  7898. * 显示余额查询按钮
  7899. * @param {string} server 服务名称
  7900. */
  7901. showQueryBalanceButton(server) {
  7902. if (server == 'deepl') {
  7903. const quotaConfig = OJBetter.deepl.config.quota;
  7904. if (quotaConfig.url && quotaConfig.surplus && quotaConfig.header) {
  7905. this.queryBalanceButton.show();
  7906. this.registerQueryBalanceButtonEvent(() => {
  7907. return queryServerBalance(OJBetter.deepl.config.quota);
  7908. });
  7909. }
  7910. } else if (server == 'openai') {
  7911. const quotaConfig = OJBetter.chatgpt.config.quota;
  7912. if (quotaConfig.url && quotaConfig.surplus && quotaConfig.header) {
  7913. this.queryBalanceButton.show();
  7914. this.registerQueryBalanceButtonEvent(() => {
  7915. return queryServerBalance(OJBetter.chatgpt.config.quota);
  7916. });
  7917. }
  7918. }
  7919. }
  7920. }
  7921.  
  7922. // 元素关系树
  7923. class ElementsTree {
  7924. constructor(elements) {
  7925. this.node = [];
  7926. this.transResultMap = {};
  7927. this.index = 0;
  7928. // this.tagNames = ["DIV", "P", "UL", "LI"]
  7929. this.tagNames = ["DIV", "P", "UL", "LI", "SECTION", "SPAN"]
  7930. this.init($(elements));
  7931. }
  7932.  
  7933. // Iterate through all elements, because there may be multiple ttypography
  7934. init(elements) {
  7935. elements.each((i, e) => {
  7936. this.node.push({}); // add one element
  7937. this.index = 0; // reset index
  7938. this.create(i, $(e));
  7939. });
  7940. }
  7941.  
  7942. // 刷新关系树
  7943. refreshNode(elements) {
  7944. this.node = [];
  7945. this.index = 0;
  7946. this.init($(elements));
  7947. }
  7948.  
  7949. // 创建节点间的关系树
  7950. create(i_, element) {
  7951. var prev = null;
  7952. var node = this.node[i_];
  7953. element.children().each((i, e) => {
  7954. // only add element with tagNames
  7955. if (this.tagNames.includes($(e).prop("tagName"))) {
  7956. prev = this.addNode(i_, prev, e);
  7957. }
  7958. // recursively child element
  7959. if ($(e).children().length > 0 && prev !== null) {
  7960. node[prev].firstChild = this.index;
  7961. this.create(i_, $(e));
  7962. }
  7963. });
  7964. }
  7965.  
  7966. // 向树中添加一个节点
  7967. addNode(i_, prev, e) {
  7968. let node = this.node[i_];
  7969. node[this.index] = {
  7970. prev: prev,
  7971. next: null,
  7972. firstChild: null,
  7973. type: $(e).prop("tagName"),
  7974. isTranslateDiv: $(e).hasClass("translateDiv"),
  7975. topText: $(e).attr("data-topText"),
  7976. id: $(e).attr("id"),
  7977. };
  7978.  
  7979. if (prev !== null) {
  7980. node[prev].next = this.index;
  7981. }
  7982.  
  7983. prev = this.index;
  7984.  
  7985. this.index++;
  7986. return prev;
  7987. }
  7988.  
  7989. getNodeData() {
  7990. return this.node;
  7991. }
  7992.  
  7993. setNodeData(node) {
  7994. this.node = node;
  7995. }
  7996.  
  7997. getTransResultMap() {
  7998. return this.transResultMap;
  7999. }
  8000.  
  8001. setTransResultMap(transResultMap) {
  8002. this.transResultMap = transResultMap;
  8003. }
  8004.  
  8005. rmTransResultMap(id) {
  8006. delete this.transResultMap[id];
  8007. }
  8008.  
  8009. addTransResultMap(id, text) {
  8010. this.transResultMap[id] = text;
  8011. }
  8012.  
  8013. getTranslateDivNum(ttTree) {
  8014. var num = 0;
  8015. for (var i in ttTree) {
  8016. if (ttTree[i].isTranslateDiv) {
  8017. num++;
  8018. }
  8019. }
  8020. return num;
  8021. }
  8022.  
  8023. // 恢复目标元素中的translateDiv
  8024. recover(elements) {
  8025. elements.each((i, e) => {
  8026. var ttTreeNode = this.node[i];
  8027. var missingTranslateDivs = this.getTranslateDivNum(ttTreeNode);
  8028. if (missingTranslateDivs > 0) {
  8029. this.recoverOneElement($(e), ttTreeNode);
  8030. }
  8031. });
  8032. }
  8033.  
  8034. recoverOneElement(element, ttTreeNode) {
  8035. this.recoverOneFork(element.children().eq(0), ttTreeNode, 0);
  8036. }
  8037.  
  8038. // 恢复一个分支
  8039. recoverOneFork(pElement, ttTreeNode, index) {
  8040. do {
  8041. // only recover element with tagNames
  8042. if (!this.tagNames.includes(pElement.prop("tagName"))) {
  8043. if (pElement.next().length > 0) {
  8044. pElement = pElement.next();
  8045. } else {
  8046. return;
  8047. }
  8048. }
  8049. if (!ttTreeNode[index] || pElement.prop("tagName") !== ttTreeNode[index].type) {
  8050. // console.warn(`元素不存在或类型不同, 元素结构可能已经发生了变化: \nindex: ${index}`, pElement);
  8051. return;
  8052. } else {
  8053. // recursively child element
  8054. var node = ttTreeNode[index];
  8055. if (node.firstChild !== null) {
  8056. this.recoverOneFork(
  8057. pElement.children().eq(0),
  8058. ttTreeNode,
  8059. node.firstChild
  8060. );
  8061. }
  8062. // check if next node is translateDiv
  8063. if (node.next !== null) {
  8064. index = node.next;
  8065.  
  8066. var ne_node = ttTreeNode[index];
  8067. if (ne_node.isTranslateDiv) {
  8068. var id = ne_node.id;
  8069. var topText = ne_node.topText;
  8070. var text = this.transResultMap[id];
  8071. // create element after pElement
  8072. this.reCreateTransDiv(pElement, id, text, topText);
  8073. }
  8074. pElement = pElement.next(); // go to next element
  8075. }
  8076. }
  8077. } while (node.next !== null);
  8078. }
  8079.  
  8080. // 重新创建translateDiv
  8081. reCreateTransDiv(pElement, id, translatedText, topText) {
  8082. const translateDiv = new TranslateDiv(id);
  8083. pElement.after(translateDiv.getDiv());
  8084. translateDiv.setTopText(topText);
  8085. translateDiv.registerUpButtonEvent();
  8086. translateDiv.registerCloseButtonEvent();
  8087. if (!OJBetter.typeOfPage.is_oldLatex && !OJBetter.typeOfPage.is_acmsguru) {
  8088. translateDiv.registerCopyButtonEvent(translatedText);
  8089. } else {
  8090. translateDiv.disableCopyButton();
  8091. }
  8092. translateDiv.updateTranslateDiv(translatedText, !(OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru));
  8093. // 标记已翻译并添加到翻译按钮的结果栈中
  8094. let transButton = pElement.prev('.html2md-panel').find('.translateButton');
  8095. if (transButton.length == 0) {
  8096. // 如果没有找到,则应该是得在父元素中找到
  8097. transButton = pElement.parent().prev('.html2md-panel').find('.translateButton');
  8098. }
  8099. transButton.pushResultToTransButton({
  8100. translateDiv: translateDiv,
  8101. status: 0
  8102. });
  8103. transButton.setTransButtonState('success');
  8104. }
  8105. }
  8106.  
  8107. // 更新TransDB中的翻译数据
  8108. async function updateTransDBData(nodeDate, transResultMap) {
  8109. var url = window.location.href.replace(/#/, "");
  8110. try {
  8111. await OJBetter.common.database.translateData.put({ url, transResultMap, nodeDate });
  8112. return 'translateData saved successfully';
  8113. } catch (error) {
  8114. throw new Error(`Failed to save translateData: ${error}`);
  8115. }
  8116. }
  8117.  
  8118. // 获取TransDB中保存的翻译数据
  8119. async function getTransDBData() {
  8120. var url = window.location.href.replace(/#/, "");
  8121. try {
  8122. const result = await OJBetter.common.database.translateData.get(url);
  8123. return result;
  8124. } catch (error) {
  8125. throw new Error(`Failed to get translateData: ${error}`);
  8126. }
  8127. }
  8128.  
  8129. /**
  8130. * 翻译结果恢复功能初始化
  8131. * @returns
  8132. */
  8133. async function initTransResultsRecover() {
  8134. OJBetter.translation.memory.ttTree = new ElementsTree("#task-statement"); // 初始化当前页面#task-statement元素的结构树
  8135. let result = await getTransDBData();
  8136. if (!result) return;
  8137. OJBetter.translation.memory.ttTree.setNodeData(result.nodeDate);
  8138. OJBetter.translation.memory.ttTree.setTransResultMap(result.transResultMap);
  8139. OJBetter.translation.memory.ttTree.recover($("#task-statement"));
  8140. }
  8141.  
  8142. /**
  8143. * 自动翻译
  8144. */
  8145. async function initTransWhenViewable() {
  8146. await waitForMathJaxIdle();
  8147.  
  8148. // const elements = $('.ttypography, .comments').find('.translateButton');
  8149. const elements = $('#task-statement').find('.translateButton');
  8150. const observers = [];
  8151.  
  8152. // Use a single Intersection Observer for all elements
  8153. const observer = new IntersectionObserver((entries, obs) => {
  8154. entries.forEach((entry) => {
  8155. if (entry.isIntersecting) {
  8156. const button = $(entry.target);
  8157. const state = button.getButtonState();
  8158. const notAutoTranslate = button.getNotAutoTranslate();
  8159. // Check if the button meets the criteria
  8160. if (state === 'normal' && !notAutoTranslate) {
  8161. let trans = OJBetter.translation.choice;
  8162.  
  8163. if (OJBetter.translation.auto.mixTrans.enabled && button.IsCommentButton() && OJBetter.translation.auto.mixTrans.servers.length > 0) {
  8164. const randomIndex = Math.floor(Math.random() * OJBetter.translation.auto.mixTrans.servers.length);
  8165. trans = OJBetter.translation.auto.mixTrans.servers[randomIndex];
  8166. }
  8167. button.data("translatedItBy")(trans);
  8168. }
  8169.  
  8170. // Stop observing the element
  8171. obs.unobserve(entry.target);
  8172. }
  8173. });
  8174. });
  8175.  
  8176. // Observe each element
  8177. elements.each((i, e) => {
  8178. observer.observe(e);
  8179. });
  8180.  
  8181. // Store the observer in case you need to disconnect it later
  8182. observers.push(observer);
  8183. }
  8184.  
  8185. /**
  8186. * 翻译返回结果结构体
  8187. * @typedef {Object} TranslateResult
  8188. * @property {string} status 翻译状态
  8189. * @property {TranslateDiv} translateDiv 翻译结果面板
  8190. * @property {TransRawData} rawData 原始翻译数据
  8191. */
  8192.  
  8193. /**
  8194. * 翻译主方法
  8195. * @param {string} text 待翻译文本
  8196. * @param {HTMLElement} element_node 元素节点
  8197. * @param {Boolean} is_comment 是否为评论区文本
  8198. * @param {string} overrideTrans 覆盖全局翻译服务设定
  8199. * @returns {TranslateResult} 翻译结果对象
  8200. */
  8201. async function translateProblemStatement(text, element_node, is_comment, overrideTrans) {
  8202. /** @type {number} 翻译结果的ID*/
  8203. const id = OJB_getRandomNumber(8);
  8204. /** @type {TextBlockReplacer} 文本块替换/恢复实例*/
  8205. const textBlockReplacer = new TextBlockReplacer();
  8206. /** @type {string} 翻译结果文本*/
  8207. let translatedText = "";
  8208.  
  8209. /** @type {string} 当前实际应用的翻译服务 */
  8210. const realTransServer = overrideTrans ||
  8211. (is_comment && OJBetter.translation.comment.choice != "0" ?
  8212. OJBetter.translation.comment.choice :
  8213. OJBetter.translation.choice);
  8214.  
  8215. /** @type {TranslateResult} 翻译结果对象 */
  8216. const translateResult = {
  8217. status: "ok",
  8218. rawData: {
  8219. done: false
  8220. }
  8221. }
  8222.  
  8223. /**
  8224. * LaTeX替换
  8225. * @param {string} text 待翻译文本
  8226. * @returns {string} 处理后的文本
  8227. */
  8228. const replaceLatex = function (text) {
  8229. if (OJBetter.typeOfPage.is_oldLatex) {
  8230. const regex = /<span\s+class="tex-span">.*?<\/span>/gi;
  8231. text = textBlockReplacer.replace(text, regex);
  8232. text = text.replace(/<p>(.*?)<\/p>/g, "$1\n\n"); // <p/>标签换为换行
  8233. } else if (OJBetter.typeOfPage.is_acmsguru) {
  8234. const regex = /<i>.*?<\/i>|<sub>.*?<\/sub>|<sup>.*?<\/sup>|<pre>.*?<\/pre>/gi;
  8235. text = textBlockReplacer.replace(text, regex);
  8236. } else if (realTransServer != "openai") {
  8237. // 使用GPT翻译时不必替换latex公式
  8238. const regex = /\$\$(\\.|[^\$])*?\$\$|\$(\\.|[^\$])*?\$/g;
  8239. text = textBlockReplacer.replace(text, regex);
  8240.  
  8241. // 替换行间代码块```
  8242. const regex2 = /```[\s\S]*?```/g;
  8243. text = textBlockReplacer.replace(text, regex2);
  8244. }
  8245. return text;
  8246. }
  8247.  
  8248. /**
  8249. * LaTeX恢复
  8250. * @param {string} text 已翻译的文本
  8251. * @returns {string} 恢复后的文本
  8252. */
  8253. const recoverLatex = function (text) {
  8254. // 两个公式之间加个空格,防止有些LaTeX解析器解析错误
  8255. let resultText = text
  8256. .replace(/】【/g, '】 【')
  8257. .replace(/\]\[/g, '] [')
  8258. .replace(/\}\{/g, '} {');
  8259.  
  8260. if (OJBetter.typeOfPage.is_oldLatex) {
  8261. resultText = resultText.replace(/(.+?)(\n\n|$)/g, "<p>$1</p>"); // 换行符还原为<p/>标签
  8262. resultText = textBlockReplacer.recover(resultText);
  8263. } else if (OJBetter.typeOfPage.is_acmsguru) {
  8264. resultText = textBlockReplacer.recover(resultText);
  8265. } else if (realTransServer != "openai") {
  8266. resultText = textBlockReplacer.recover(resultText);
  8267. }
  8268. return resultText;
  8269. }
  8270.  
  8271. /**
  8272. * 格式化翻译结果
  8273. * @param {string} text
  8274. * @returns {string} 处理后的翻译结果
  8275. */
  8276. const formatText = function (text) {
  8277. // 转义LaTex中的特殊符号
  8278. if (!OJBetter.typeOfPage.is_oldLatex && !OJBetter.typeOfPage.is_acmsguru) {
  8279.  
  8280. // 先替换掉行间代码块
  8281. const replacer = new TextBlockReplacer();
  8282. text = replacer.replace(text, /```[\s\S]*?```/g);
  8283.  
  8284. // 处理LaTeX公式
  8285. const escapeRules = [
  8286. { pattern: /(?<!\\)>(?!\s)/g, replacement: " &gt; " }, // >符号
  8287. { pattern: /(?<!\\)</g, replacement: " &lt; " }, // <符号
  8288. { pattern: /(?<!\\)\*/g, replacement: " &#42; " }, // *符号
  8289. { pattern: /(?<!\\)_/g, replacement: " &#95; " }, // _符号
  8290. { pattern: /(?<!\\)\\\\(?=\s)/g, replacement: "\\\\\\\\" }, // \\符号
  8291. { pattern: /(?<!\\)\\(?![\\a-zA-Z0-9])/g, replacement: "\\\\" }, // \符号
  8292. ];
  8293.  
  8294. let latexMatches = [...text.matchAll(/\$\$([\s\S]*?)\$\$|\$(.*?)\$|\$([\s\S]*?)\$/g)];
  8295. for (const match of latexMatches) {
  8296. const matchedText = match[0];
  8297. let escapedText = matchedText;
  8298.  
  8299. for (const rule of escapeRules) {
  8300. escapedText = escapedText.replaceAll(rule.pattern, rule.replacement);
  8301. }
  8302. escapedText = escapedText.replace(/\$\$/g, "$$$$$$$$");// $$符号(因为后面需要作为replacement,双倍消耗)
  8303. text = text.replace(matchedText, escapedText);
  8304. }
  8305.  
  8306. // 恢复行间代码块
  8307. text = replacer.recover(text);
  8308. }
  8309.  
  8310. // // 使符合mathjx的转换语法
  8311. // const mathjaxRuleMap = [
  8312. // { pattern: /\$/g, replacement: "$$$$$$" }, // $$ 行间
  8313. // ];
  8314. // mathjaxRuleMap.forEach(({ pattern, replacement }) => {
  8315. // text = text.replace(pattern, replacement);
  8316. // });
  8317.  
  8318. // markdown修正
  8319. const mdRuleMap = [
  8320. { pattern: /(\s_[\u4e00-\u9fa5]+_)([\u4e00-\u9fa5]+)/g, replacement: "$1 $2" }, // 斜体
  8321. { pattern: /(_[\u4e00-\u9fa5]+_\s)([\u4e00-\u9fa5]+)/g, replacement: " $1$2" },
  8322. { pattern: /(_[\u4e00-\u9fa5]+_)([\u4e00-\u9fa5]+)/g, replacement: " $1 $2" },
  8323. { pattern: /(([\s\S]*?))/g, replacement: "($1)" }, // 中文()
  8324. // { pattern: /:/g, replacement: ":" }, // 中文:
  8325. { pattern: /\*\* (.*?) \*\*/g, replacement: "\*\*$1\*\*" } // 加粗
  8326. ];
  8327. mdRuleMap.forEach(({ pattern, replacement }) => {
  8328. text = text.replace(pattern, replacement);
  8329. });
  8330.  
  8331. return text;
  8332. }
  8333.  
  8334. // 创建翻译结果元素并放在element_node的后面
  8335. translateResult.translateDiv = new TranslateDiv(id);
  8336. $(element_node).after(translateResult.translateDiv.getDiv());
  8337.  
  8338. // 顶栏左侧信息
  8339. translateResult.translateDiv.setTopText(i18next.t('servers.' + realTransServer, { ns: 'translator' }) +
  8340. i18next.t('translateDiv.topTextSuffix', { ns: 'translator' }));
  8341.  
  8342. // 注册按钮
  8343. translateResult.translateDiv.registerUpButtonEvent();
  8344. translateResult.translateDiv.registerCloseButtonEvent();
  8345. if (OJBetter.translation.choice == 'openai' || OJBetter.translation.choice == 'deepl') {
  8346. translateResult.translateDiv.showQueryBalanceButton(OJBetter.translation.choice); // 显示额度查询
  8347. }
  8348.  
  8349. // 翻译内容是否可能为代码片段
  8350. if (isLikelyCodeSnippet(text)) {
  8351. const shouldContinue = await OJB_createDialog(
  8352. i18next.t('isLikelyCodeSnippet.title', { ns: 'dialog' }),
  8353. i18next.t('isLikelyCodeSnippet.content', { ns: 'dialog' }),
  8354. [
  8355. i18next.t('isLikelyCodeSnippet.buttons.0', { ns: 'dialog' }),
  8356. i18next.t('isLikelyCodeSnippet.buttons.1', { ns: 'dialog' })
  8357. ],
  8358. true
  8359. );
  8360. if (shouldContinue) {
  8361. translateResult.status = "skip";
  8362. return translateResult;
  8363. }
  8364. }
  8365.  
  8366. // 替换latex公式
  8367. text = replaceLatex(text);
  8368.  
  8369. // 过滤**号
  8370. if (OJBetter.translation.filterTextWithoutEmphasis && GM_getValue("translation") !== "openai") { // TODO
  8371. text = text.replace(/\*\*/g, "");
  8372. }
  8373.  
  8374. // 字符数上限
  8375. const translationLimits = {
  8376. deepl: 5000,
  8377. iflyrec: 2000,
  8378. youdao: 600,
  8379. google: 5000,
  8380. caiyun: 5000
  8381. };
  8382. if (translationLimits.hasOwnProperty(realTransServer) && text.length > translationLimits[realTransServer]) {
  8383. let textLength = translationLimits[realTransServer];
  8384. let realTextLength = text.length;
  8385. const shouldContinue = await OJB_createDialog(
  8386. i18next.t('transTextLimits.title', { ns: 'dialog' }),
  8387. i18next.t('transTextLimits.content', { ns: 'dialog', textLength: textLength, realTextLength: realTextLength }),
  8388. [
  8389. i18next.t('transTextLimits.buttons.0', { ns: 'dialog' }),
  8390. i18next.t('transTextLimits.buttons.1', { ns: 'dialog' })
  8391. ],
  8392. true
  8393. ); // 字数超限确认
  8394. if (shouldContinue) {
  8395. translateResult.status = "skip";
  8396. return translateResult;
  8397. }
  8398. }
  8399.  
  8400. /**
  8401. * 调用各个翻译服务
  8402. * @param {string} transServer 翻译服务
  8403. * @returns {TransRawData} 原始翻译数据
  8404. */
  8405. async function translate(transServer) {
  8406. const is_renderLaTeX = !(OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru);
  8407. const servername = i18next.t('servers.' + realTransServer, { ns: 'translator' });
  8408. /** @type {TransRawData} 原始翻译数据*/
  8409. let rawData = {};
  8410. try {
  8411. if (transServer == "deepl") {
  8412. if (OJBetter.deepl.config.type == 'free') {
  8413. translateResult.translateDiv.updateTranslateDiv(`${i18next.t('transingTip.basic', { ns: 'translator', server: servername })}`, is_renderLaTeX);
  8414. rawData = await translate_deepl(text);
  8415. } else if (OJBetter.deepl.config.type == 'api') {
  8416. translateResult.translateDiv.updateTranslateDiv(`${i18next.t('transingTip.deeplApi', { ns: 'translator', deepl_configName: OJBetter.deepl.config.name })}`, is_renderLaTeX);
  8417. if (OJBetter.deepl.config.apiGenre == 'deeplx') {
  8418. rawData = await translate_deeplx(text);
  8419. } else {
  8420. if (OJBetter.deepl.enableEmphasisProtection) text = convertBoldMarkdownToHTML(text);
  8421. if (OJBetter.deepl.enableLinkProtection) text = convertLinksMarkdownToHTML(text);
  8422. if (OJBetter.deepl.config.apiGenre == 'api-free') {
  8423. rawData = await translate_deepl_api_free(text);
  8424. } else if (OJBetter.deepl.config.apiGenre == 'api-pro') {
  8425. rawData = await translate_deepl_api_pro(text);
  8426. }
  8427. if (OJBetter.deepl.enableEmphasisProtection) rawData.text = convertBoldHTMLToMarkdown(rawData.text);
  8428. if (OJBetter.deepl.enableLinkProtection) rawData.text = convertLinksHTMLToMarkdown(rawData.text);
  8429. }
  8430. }
  8431. } else if (transServer == "iflyrec") {
  8432. translateResult.translateDiv.updateTranslateDiv(`${i18next.t('transingTip.basic', { ns: 'translator', server: servername })}`, is_renderLaTeX);
  8433. rawData = await translate_iflyrec(text);
  8434. } else if (transServer == "youdao") {
  8435. translateResult.translateDiv.updateTranslateDiv(`${i18next.t('transingTip.basic', { ns: 'translator', server: servername })}`, is_renderLaTeX);
  8436. rawData = await translate_youdao_mobile(text);
  8437. } else if (transServer == "google") {
  8438. translateResult.translateDiv.updateTranslateDiv(`${i18next.t('transingTip.basic', { ns: 'translator', server: servername })}`, is_renderLaTeX);
  8439. rawData = await translate_gg(text);
  8440. } else if (transServer == "caiyun") {
  8441. translateResult.translateDiv.updateTranslateDiv(`${i18next.t('transingTip.basic', { ns: 'translator', server: servername })}`, is_renderLaTeX);
  8442. rawData = await translate_caiyun(text);
  8443. } else if (transServer == "openai") {
  8444. translateResult.translateDiv.updateTranslateDiv(`${i18next.t('transingTip.openai', { ns: 'translator', openai_name: OJBetter.chatgpt.config.name })}${!OJBetter.chatgpt.isStream
  8445. ? i18next.t('transingTip.openai_isStream', { ns: 'translator' }) : ""}`,
  8446. is_renderLaTeX);
  8447. if (OJBetter.chatgpt.isStream) {
  8448. // 流式传输
  8449. rawData = await translate_openai_stream(text, translateResult.translateDiv);
  8450. } else {
  8451. // 普通模式
  8452. rawData = await translate_openai(text);
  8453. }
  8454. }
  8455. translatedText = rawData.text;
  8456. if (!rawData.done) {
  8457. translateResult.status = "error";
  8458. }
  8459. } catch (e) {
  8460. translateResult.status = "error";
  8461. rawData.message = i18next.t('error.unexpected', { ns: 'translator' });
  8462. console.warn(e);
  8463. }
  8464. return rawData;
  8465. }
  8466. translateResult.rawData = await translate(realTransServer);
  8467.  
  8468. if (translateResult.status == "error") {
  8469. translateResult.translateDiv.updateTranslateDiv(translateResult.rawData.message);
  8470. return translateResult;
  8471. }
  8472.  
  8473. // 还原latex公式
  8474. translatedText = recoverLatex(translatedText);
  8475.  
  8476. // 注册结果复制按钮
  8477. if (!OJBetter.typeOfPage.is_oldLatex && !OJBetter.typeOfPage.is_acmsguru) {
  8478. translateResult.translateDiv.registerCopyButtonEvent(translatedText);
  8479. } else {
  8480. translateResult.translateDiv.disableCopyButton();
  8481. }
  8482.  
  8483. // 翻译结果格式化
  8484. translatedText = formatText(translatedText);
  8485.  
  8486. // 保存翻译结果
  8487. if ((OJBetter.typeOfPage.is_problem || OJBetter.typeOfPage.is_completeProblemset) && OJBetter.translation.memory.enabled) {
  8488. // OJBetter.translation.memory.ttTree.refreshNode(".ttypography"); // 刷新当前页面.ttypography元素的结构树实例
  8489. OJBetter.translation.memory.ttTree.refreshNode("#task-statement"); // 刷新当前页面.ttypography元素的结构树实例
  8490. OJBetter.translation.memory.ttTree.addTransResultMap(id, translatedText);
  8491. updateTransDBData(OJBetter.translation.memory.ttTree.getNodeData(), OJBetter.translation.memory.ttTree.getTransResultMap()); // 更新翻译结果到transDB
  8492. }
  8493.  
  8494. // 翻译结果面板更新
  8495. translateResult.translateDiv.updateTranslateDiv(translatedText, !(OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru));
  8496.  
  8497. return translateResult;
  8498. }
  8499.  
  8500. /**
  8501. * 题目页相关链接栏
  8502. */
  8503. class ProblemPageLinkbar {
  8504. constructor() {
  8505. this.containerElement = this.createToolbar();
  8506. this.commandInvoker = new CommandInvoker();
  8507. }
  8508.  
  8509. /**
  8510. * 创建工具栏
  8511. */
  8512. createToolbar() {
  8513. // const toolbarElement = $("<div>").attr("id", "problemToolbar").insertBefore($(".problemindexholder"));
  8514. const toolbarElement = $("<div>").attr("id", "problemToolbar").insertBefore($(".h2"));
  8515. return new DOMContainer(toolbarElement);
  8516. }
  8517.  
  8518. /**
  8519. * 添加按钮
  8520. * @param {string} id 按钮id
  8521. * @param {string} url 按钮链接
  8522. * @param {string} text 按钮文字
  8523. * @param {JQueryObject} icon 按钮图标
  8524. * @param {string} iconHeight 图标高度
  8525. * @returns {object} 按钮对象
  8526. */
  8527. addLinkButton(id, url, text, icon = $('<div>'), iconHeight = "22px") {
  8528. const linkElement = $("<a>")
  8529. .attr("href", url)
  8530. .attr("target", "_blank")
  8531. .addClass("ojb_btn")
  8532. .attr("id", id);
  8533.  
  8534. linkElement.append(icon);
  8535. icon.css("height", iconHeight);
  8536.  
  8537. const textSpan = $("<span>").html(text);
  8538. linkElement.append(textSpan);
  8539.  
  8540. this.commandInvoker.execute(new AddElementCommand(this.containerElement, linkElement));
  8541. return {
  8542. element: linkElement,
  8543. text: textSpan,
  8544. icon: icon
  8545. };
  8546. }
  8547.  
  8548. /**
  8549. * 更新链接
  8550. * @param {object} button 按钮对象
  8551. * @param {string} url 按钮链接
  8552. */
  8553. updateUrl(button, url) {
  8554. button.element.attr("href", url);
  8555. }
  8556.  
  8557. /**
  8558. * 更新文字
  8559. * @param {object} button 按钮对象
  8560. * @param {string} text 按钮文字
  8561. */
  8562. updateText(button, text) {
  8563. button.text.html(text);
  8564. }
  8565.  
  8566. /**
  8567. * 设置文字为粗体
  8568. * @param {object} button 按钮对象
  8569. */
  8570. setBold(button) {
  8571. button.text.css("font-weight", "bold");
  8572. }
  8573.  
  8574. /**
  8575. * 更新图标
  8576. * @param {object} button 按钮对象
  8577. * @param {JQueryObject} icon 按钮图标
  8578. * @param {string} iconHeight 图标高度
  8579. */
  8580. updateIcon(button, icon, iconHeight = "16px") {
  8581. button.icon.remove();
  8582. button.text.prepend(icon);
  8583. icon.css("height", iconHeight);
  8584. button.icon = icon;
  8585. }
  8586.  
  8587. /**
  8588. * 添加类
  8589. * @param {object} button 按钮对象
  8590. * @param {string} className 类名
  8591. */
  8592. addClass(button, className) {
  8593. button.element.addClass(className);
  8594. }
  8595.  
  8596. /**
  8597. * 禁用链接按钮
  8598. * @param {object} button 按钮对象
  8599. */
  8600. disableButton(button) {
  8601. button.element.addClass("disabled");
  8602. }
  8603.  
  8604. /**
  8605. * 启用链接按钮
  8606. * @param {object} button 按钮对象
  8607. */
  8608. enableButton(button) {
  8609. button.element.removeClass("disabled");
  8610. }
  8611. }
  8612.  
  8613. /**
  8614. * 获取题目的id
  8615. * @param {String} url 题目的链接
  8616. * @returns 题目的id,形如2000A
  8617. */
  8618. function getProblemId(url) {
  8619. const regex = /\/contests\/([A-Za-z\d]+)\/tasks\/([A-Za-z\d\_]+)/;
  8620. const matchResult = url.match(regex);
  8621. return matchResult && matchResult.length >= 3
  8622. ? `${matchResult[2]}`
  8623. : '';
  8624. };
  8625.  
  8626. /**
  8627. * 跳转到洛谷
  8628. * @param {ProblemPageLinkbar} problemToolbar
  8629. */
  8630. async function CF2luogu(problemToolbar) {
  8631. const url = window.location.href;
  8632. const problemId = getProblemId(url);
  8633. const luoguButton = problemToolbar.addLinkButton(
  8634. "luoguButton",
  8635. "https://www.luogu.com.cn/",
  8636. i18next.t('state.loading', { ns: 'button' }),
  8637. $("<img>").attr("src", "https://cdn.luogu.com.cn/fe/logo.png")
  8638. );
  8639.  
  8640. const checkLinkExistence = async (url) => {
  8641. return OJB_promiseRetryWrapper(async () => {
  8642. const response = await OJB_GMRequest({
  8643. method: "GET",
  8644. url
  8645. });
  8646. return !response.responseText.match(/出错了/g);
  8647. }, {
  8648. maxRetries: 3,
  8649. retryInterval: 1000
  8650. });
  8651. };
  8652.  
  8653. const LuoguUrl = `https://www.luogu.com.cn/problem/AT_${problemId}`;
  8654. try {
  8655. const result = await checkLinkExistence(LuoguUrl);
  8656. if (problemId && result) {
  8657. problemToolbar.updateText(luoguButton, "");
  8658. problemToolbar.updateUrl(luoguButton, LuoguUrl);
  8659. } else {
  8660. problemToolbar.updateText(luoguButton, i18next.t('state.404', { ns: 'button' }));
  8661. problemToolbar.disableButton(luoguButton);
  8662. }
  8663. } catch (error) {
  8664. if (error instanceof OJB_GMError && error.type == "error") {
  8665. problemToolbar.updateText(luoguButton, i18next.t('state.netError', { ns: 'button' }));
  8666. problemToolbar.disableButton(luoguButton);
  8667. }
  8668. }
  8669. }
  8670.  
  8671. /**
  8672. * 跳转到 Virtual Judge
  8673. * @param {ProblemPageLinkbar} problemToolbar
  8674. */
  8675. async function CF2vjudge(problemToolbar) {
  8676. const url = window.location.href;
  8677. const problemId = getProblemId(url);
  8678. const vjudgeButton = problemToolbar.addLinkButton(
  8679. "vjudgeButton",
  8680. "https://vjudge.net/",
  8681. i18next.t('state.loading', { ns: 'button' }),
  8682. $("<img>").attr("src", "https://aowuucdn.oss-accelerate.aliyuncs.com/vjudge.ico")
  8683. );
  8684.  
  8685. const checkLinkExistence = async (url) => {
  8686. return OJB_promiseRetryWrapper(async () => {
  8687. const response = await OJB_GMRequest({
  8688. method: "HEAD",
  8689. url: url,
  8690. });
  8691. if (response.status >= 200 && response.status < 300) return true;
  8692. else if (response.status == 404) return false;
  8693. else throw new OJB_GMError('network', 'An unknown network error occurred!', response);
  8694. }, {
  8695. maxRetries: 3,
  8696. retryInterval: 1000
  8697. });
  8698. };
  8699.  
  8700. const VjudgeUrl = `https://vjudge.net/problem/AtCoder-${problemId}`;
  8701. try {
  8702. const result = await checkLinkExistence(VjudgeUrl);
  8703. if (problemId && result) {
  8704. problemToolbar.updateText(vjudgeButton, "VJudge");
  8705. problemToolbar.updateUrl(vjudgeButton, VjudgeUrl);
  8706. } else {
  8707. problemToolbar.updateText(vjudgeButton, i18next.t('state.404', { ns: 'button' }));
  8708. problemToolbar.disableButton(vjudgeButton);
  8709. }
  8710. } catch (error) {
  8711. if (error instanceof OJB_GMError && error.type == "error") {
  8712. problemToolbar.updateText(vjudgeButton, i18next.t('state.netError', { ns: 'button' }));
  8713. problemToolbar.disableButton(vjudgeButton);
  8714. }
  8715. }
  8716. }
  8717.  
  8718. // RatingClass
  8719. const ratingClassMap = {
  8720. NaN: "rating_by_clist_colorNaN",
  8721. 0: "rating_by_clist_color0",
  8722. 1200: "rating_by_clist_color1",
  8723. 1400: "rating_by_clist_color2",
  8724. 1600: "rating_by_clist_color3",
  8725. 1900: "rating_by_clist_color4",
  8726. 2100: "rating_by_clist_color5",
  8727. 2300: "rating_by_clist_color6",
  8728. 2400: "rating_by_clist_color7",
  8729. 2600: "rating_by_clist_color8",
  8730. 3000: "rating_by_clist_color9"
  8731. };
  8732. const cssMap = {
  8733. "rating_by_clist_colorNaN": "#cccccc",
  8734. "rating_by_clist_color0": "#808080",
  8735. "rating_by_clist_color1": "#73e473",
  8736. "rating_by_clist_color2": "#77ddbb",
  8737. "rating_by_clist_color3": "#aaaaff",
  8738. "rating_by_clist_color4": "#ff88ff",
  8739. "rating_by_clist_color5": "#ffcc88",
  8740. "rating_by_clist_color6": "#ffbb55",
  8741. "rating_by_clist_color7": "#ff7777",
  8742. "rating_by_clist_color8": "#ff3333",
  8743. "rating_by_clist_color9": "#aa0000"
  8744. };
  8745. // TODO 7
  8746. /**
  8747. * clist 访问有效性检查
  8748. * @param {boolean} onlyCookie 是否只检查Cookie
  8749. * @returns {Promise<boolean>} 是否有效
  8750. */
  8751. async function validateClistConnection(onlyCookie = false) {
  8752. const clistApiUrl = "https://clist.by:443/api/v4/contest/?limit=1&resource_id=1";
  8753. const requestOptions = {
  8754. method: "GET",
  8755. url: clistApiUrl,
  8756. timeout: 5000,
  8757. };
  8758.  
  8759. // 尝试发送请求
  8760. async function tryRequest(options) {
  8761. try {
  8762. const response = await OJB_GMRequest(options);
  8763. if (response.status === 200) {
  8764. return { ok: true };
  8765. } else if (response.status === 401) {
  8766. throw new Error('unauthorized');
  8767. } else if (response.status === 404) {
  8768. throw new Error('not_found');
  8769. } else {
  8770. throw new Error('other_error');
  8771. }
  8772. } catch (error) {
  8773. console.warn(`Error accessing clist.by: ${error.message}`);
  8774. return { ok: false, error: error.message };
  8775. }
  8776. }
  8777.  
  8778. // 尝试携带Key发送请求
  8779. let result = await tryRequest(requestOptions);
  8780. if (!onlyCookie && !result.ok) {
  8781. requestOptions.headers = { "Authorization": OJBetter.clist.authorization };
  8782. result = await tryRequest(requestOptions);
  8783. }
  8784.  
  8785. // 根据结果显示错误信息
  8786. if (!result.ok) {
  8787. let errorType = result.error;
  8788. const loadingMessage = new LoadingMessage();
  8789. let state;
  8790. if (errorType === 'not_found') {
  8791. state = i18next.t('error.clist.404', { ns: 'alert' });
  8792. } else if (errorType === 'unauthorized') {
  8793. state = i18next.t('error.clist.cookie', { ns: 'alert' });
  8794. } else {
  8795. state = i18next.t('error.clist.other', { ns: 'alert' });
  8796. }
  8797. loadingMessage.updateStatus(`${OJBetter.state.name} —— ${state}`, 'error');
  8798. }
  8799. return result.ok;
  8800. }
  8801.  
  8802. /**
  8803. * 创建Rating相关css
  8804. * @param {boolean} [hasBorder=true] 是否有边框
  8805. */
  8806. function creatRatingCss(hasBorder = true) {
  8807. const defaultBorderColor = '#dcdfe6';
  8808. let dynamicCss = "";
  8809. let hoverSelector = OJBetter.clist.ratingHidden ? ":hover" : "";
  8810. for (let cssClass in cssMap) {
  8811. dynamicCss += `a.${cssClass}${hoverSelector}, a.${cssClass}${hoverSelector}:link {\n`;
  8812. let borderColor = hasBorder ? cssMap[cssClass] : defaultBorderColor;
  8813. dynamicCss += ` color: ${cssMap[cssClass]} ${OJBetter.clist.ratingHidden ? "!important" : ""};\n`;
  8814. dynamicCss += `}\n`;
  8815. }
  8816. GM_addStyle(dynamicCss);
  8817. if (OJBetter.clist.ratingHidden) {
  8818. GM_addStyle(`
  8819. #clistButton {
  8820. color: #ffffff00;
  8821. }
  8822. `);
  8823. }
  8824. }
  8825.  
  8826. /**
  8827. * 模拟clist网页访问获取rating
  8828. * @param {string} problem 题目名称
  8829. * @param {string} problem_url 题目链接
  8830. * @param {string} contest 比赛名称
  8831. * @returns {Promise<{rating: number, problem: string}>} 题目难度
  8832. */
  8833. async function getRatingFromHTML(problem, problem_url, contest = null) {
  8834. // 去除题目名称中的括号,以及首尾的空白符
  8835. problem = problem.replace(/\([\s\S]*?\)/g, '').trim();
  8836.  
  8837. return OJB_promiseRetryWrapper(async () => {
  8838. const queryString = `search=${encodeURIComponent(problem)}&resource=1`;
  8839. const response = await OJB_GMRequest({
  8840. method: 'GET',
  8841. url: `https://clist.by/problems/?${queryString}`,
  8842. });
  8843.  
  8844. if (!response.responseText) throw new OJB_GMError('network', 'An unknown network error occurred!', response);
  8845. const html = response.responseText;
  8846. const cleanedHtml = html.replace(/src=(.|\s)*?"/g, '');
  8847. const parser = new DOMParser();
  8848. const doc = parser.parseFromString(cleanedHtml, 'text/html');
  8849. const trs = doc.querySelectorAll('table tbody tr');
  8850.  
  8851. for (let tr of trs) {
  8852. const rating = tr.querySelector('.problem-rating-column').textContent.trim();
  8853. const linkElement = tr.querySelector('.problem-name-column a:nth-of-type(2)');
  8854. let link = linkElement ? OJB_cleanLink(linkElement) : null;
  8855.  
  8856. if (link === problem_url || link === problem_url + '/') {
  8857. return {
  8858. rating: parseInt(rating),
  8859. problem: problem
  8860. };
  8861. } else if (contest !== null) {
  8862. const contestTitles = [...tr.querySelectorAll('.problem-name-column .pull-right a[title], .problem-name-column .pull-right span[title]')].map(el => el.title);
  8863. if (contestTitles.includes(contest)) {
  8864. return {
  8865. rating: parseInt(rating),
  8866. problem: problem
  8867. };
  8868. }
  8869. }
  8870. }
  8871. console.warn(`No data found for the question: ${problem}`);
  8872. }, {
  8873. maxRetries: 3,
  8874. retryInterval: 500
  8875. });
  8876. }
  8877.  
  8878. /**
  8879. * 从clist API获取题目的rating
  8880. * @param {string} problem_name 题目名
  8881. * @param {string} problem_url 题目链接
  8882. * @returns {Promise<number>} 题目rating
  8883. *
  8884. * 使用两个Map对象来存储和快速访问题目信息:
  8885. * - problemsMap: 通过题目的URL作为键来存储题目信息。
  8886. * - nameMap: 通过题目的名称作为键来存储题目信息。
  8887. *
  8888. * 每个题目信息是一个对象,包含以下属性:
  8889. * @typedef {Object} ProblemInfo
  8890. * @property {string} name 题目名称
  8891. * @property {string} url 题目URL
  8892. * @property {number} rating 题目评分,如果没有评分信息则为NaN
  8893. */
  8894. async function getRatingFromApi_problem(problem_name, problem_url) {
  8895. return OJB_promiseRetryWrapper(async () => {
  8896. const response = await OJB_GMRequest({
  8897. method: "GET",
  8898. // url: `https://clist.by:443/api/v4/problem/?name=${encodeURIComponent(problem_name)}&resource__regex=codeforces.com`,
  8899. url: `https://clist.by:443/api/v4/problem/?url__regex=${encodeURIComponent(problem_name)}&resource__regex=atcoder.jp`,
  8900. headers: { "Authorization": OJBetter.clist.authorization }
  8901. });
  8902.  
  8903. if (!response.responseText) throw new OJB_GMError('network', 'An unknown network error occurred!', response);
  8904. let data = JSON.parse(response.responseText);
  8905. /**
  8906. * 使用题目的URL作为键来存储题目信息。
  8907. * @type {Map<string, ProblemInfo>}
  8908. */
  8909. let problemsMap = new Map();
  8910.  
  8911. /**
  8912. * 使用题目的名称作为键来存储题目信息。
  8913. * @type {Map<string, ProblemInfo>}
  8914. */
  8915. let nameMap = new Map();
  8916.  
  8917. data.objects.forEach(problem => {
  8918. /** @type {ProblemInfo} 题目信息*/
  8919. let problemInfo = {
  8920. name: problem.name,
  8921. url: problem.url,
  8922. rating: problem.rating ? problem.rating : NaN
  8923. };
  8924. problemsMap.set(OJB_cleanLink(problem.url), problemInfo);
  8925. nameMap.set(problem.name, problemInfo);
  8926. });
  8927.  
  8928. if (problemsMap.has(problem_url)) {
  8929. return problemsMap.get(problem_url).rating;
  8930. } else if (nameMap.has(problem_name)) {
  8931. return nameMap.get(problem_name).rating;
  8932. } else {
  8933. console.warn('Problem not found in the response');
  8934. }
  8935. }, {
  8936. maxRetries: 5,
  8937. retryInterval: 1000
  8938. });
  8939. }
  8940.  
  8941. /**
  8942. * 获取字符串中的关键词列表
  8943. * @param {string} text 字符串文本
  8944. * @returns {array<string>} 返回关键词列表
  8945. */
  8946. function getKeywords(text) {
  8947. // 定义要过滤掉的高频词
  8948. const highFrequencyWords = ['Educational', 'Codeforces', 'Round', 'Div'];
  8949.  
  8950. // 使用正则表达式替换掉特殊符号(保留空格以便分词)
  8951. const sanitizedText = text.replace(/[^\w\s]|_/g, '').replace(/\s+/g, ' ');
  8952.  
  8953. // 将字符串拆分为单词数组
  8954. const words = sanitizedText.split(' ');
  8955.  
  8956. // 过滤掉高频词和空字符串
  8957. const filteredWords = words.filter(word => {
  8958. return word && highFrequencyWords.indexOf(word) === -1;
  8959. });
  8960.  
  8961. // 返回关键词列表
  8962. return filteredWords;
  8963. }
  8964.  
  8965. /**
  8966. * 根据关键词从 Clist API 中获取实际比赛名称
  8967. * @param {string} contestName 比赛名
  8968. * @param {string} contestUrl 比赛链接
  8969. * @returns {string|null} 该比赛在Clist中的实际名字
  8970. */
  8971. async function getContestNameFromApi(contestName, contestUrl) {
  8972. return OJB_promiseRetryWrapper(async () => {
  8973. const options = {
  8974. method: "GET",
  8975. // url: `https://clist.by:443/api/v4/contest/?resource_id=1&event__regex=${encodeURIComponent(contestName)}`,
  8976. url: `https://clist.by:443/api/v4/contest/?resource_id=93&event__regex=${encodeURIComponent(contestName)}`,
  8977. headers: {
  8978. "Authorization": OJBetter.clist.authorization
  8979. }
  8980. };
  8981.  
  8982. let response = await OJB_GMRequest(options);
  8983.  
  8984. if (!response.responseText) throw new OJB_GMError('network', 'An unknown network error occurred!', response);
  8985.  
  8986. let data = JSON.parse(response.responseText);
  8987. let objects = data.objects;
  8988.  
  8989. if (objects.length > 0) {
  8990. for (const contest of objects) {
  8991. // const href = contest.href.replace(/\/contests\//i, '/contest/'); // 链接可能是contests而不是contest,换回来
  8992. const href = contest.href;
  8993. if (OJB_cleanLink(href) == contestUrl) {
  8994. return contest.event;
  8995. }
  8996. }
  8997. }
  8998. return null;
  8999. }, {
  9000. maxRetries: 5,
  9001. retryInterval: 1000
  9002. });
  9003. }
  9004.  
  9005. /**
  9006. * 获取在clist中的实际比赛名称
  9007. * @param {string} contestName 待搜索的比赛名称
  9008. * @param {string} contestUrl 比赛的url
  9009. * @returns {Promise<string|null>} 在clist中的实际比赛名称,如果没有找到,则返回null
  9010. */
  9011. async function getActualContestName(contestName, contestUrl) {
  9012. // 首先尝试使用完整的比赛名称进行搜索
  9013. let actualContestName = await getContestNameFromApi(contestName, contestUrl);
  9014. if (actualContestName) {
  9015. return actualContestName;
  9016. }
  9017.  
  9018. // 如果使用完整名称没有找到,则尝试使用关键词进行搜索
  9019. const keywords = getKeywords(contestName);
  9020. const maxKeywordAttempts = 1; // 最多尝试到第几个关键词(因为Clist API有频率限制)
  9021. for (let i = 0; i < Math.min(keywords.length, maxKeywordAttempts); i++) {
  9022. actualContestName = await getContestNameFromApi(keywords[i], contestUrl);
  9023. if (actualContestName) {
  9024. return actualContestName;
  9025. }
  9026. }
  9027.  
  9028. // 如果全部尝试后仍没有找到,返回null
  9029. return null;
  9030. }
  9031.  
  9032. /**
  9033. * 从clist API获取比赛题目集的rating
  9034. * @param {string} contestName 比赛名
  9035. * @returns {Promise<Map<string, number>>} 题目rating
  9036. */
  9037. async function getRatingFromApi_contest(contestName, contestUrl) {
  9038. const actualContestName = await getActualContestName(contestName, contestUrl);
  9039. return OJB_promiseRetryWrapper(async () => {
  9040. const options = {
  9041. method: "GET",
  9042. url: `https://clist.by:443/api/v4/contest/?resource_id=93&with_problems=true&event=${encodeURIComponent(actualContestName)}`,
  9043. headers: {
  9044. "Authorization": OJBetter.clist.authorization
  9045. }
  9046. };
  9047.  
  9048. let response = await OJB_GMRequest(options);
  9049.  
  9050. if (!response.responseText) throw new OJB_GMError('network', 'An unknown network error occurred!', response);
  9051.  
  9052. let data = JSON.parse(response.responseText);
  9053. let objects = data.objects;
  9054. let problemsMap = new Map();
  9055.  
  9056. if (objects.length > 0 && objects[0].problems) {
  9057. objects[0].problems.forEach(problem => {
  9058. problemsMap.set(OJB_cleanLink(problem.url), problem.rating ? problem.rating : NaN);
  9059. });
  9060. }
  9061.  
  9062. return problemsMap;
  9063. }, {
  9064. maxRetries: 5,
  9065. retryInterval: 1000
  9066. });
  9067. }
  9068.  
  9069. /**
  9070. * 根据rating获取对应的颜色class名
  9071. * @param {number} rating 题目rating
  9072. * @returns {string} 颜色class名
  9073. */
  9074. function getClassNameByRating(rating) {
  9075. let className = "rating_by_clist_color9";
  9076. if (Number.isNaN(rating)) {
  9077. className = "rating_by_clist_colorNaN";
  9078. } else {
  9079. let keys = Object.keys(ratingClassMap);
  9080. for (let i = 0; i < keys.length; i++) {
  9081. if (rating < keys[i]) {
  9082. className = ratingClassMap[keys[i - 1]];
  9083. break;
  9084. }
  9085. }
  9086. }
  9087. return className;
  9088. }
  9089.  
  9090. /**
  9091. * problem题目页显示Rating
  9092. * @param {ProblemPageLinkbar} problemToolbar
  9093. * @returns {Promise<void>}
  9094. */
  9095. async function showRatingByClist_problem(problemToolbar) {
  9096. // 题目名
  9097. // const problem = $('.header .title').eq(0).text().replace(/[\s\S]*?. /, '');
  9098. // if (OJBetter.typeOfPage.is_acmsguru) problem = $('h4').eq(0).text().replace(/[\s\S]*?. /, '');
  9099. const url = window.location.href;
  9100. const problemId = getProblemId(url);
  9101.  
  9102. // 创建Rating按钮元素
  9103. creatRatingCss(false);
  9104. // TODO
  9105. // const clistButton = problemToolbar.addLinkButton(
  9106. // 'clistButton',
  9107. // `https://clist.by/problems/?search=${problem}&resource=1`,
  9108. // i18next.t('state.wait', { ns: 'button' }),
  9109. // $("<img>").attr("src", "https://clist.by/static/img/logo-48.png"),
  9110. // "15px"
  9111. // );
  9112. const clistButton = problemToolbar.addLinkButton(
  9113. 'clistButton',
  9114. `https://clist.by/problems/?search=${problemId}&resource=93`,
  9115. i18next.t('state.wait', { ns: 'button' }),
  9116. $("<img>").attr("src", "https://clist.by/static/img/logo-48.png"),
  9117. "15px"
  9118. );
  9119.  
  9120. // 检测clist连接
  9121. if (!await validateClistConnection()) {
  9122. problemToolbar.updateText(clistButton, i18next.t('state.netError', { ns: 'button' }));
  9123. return;
  9124. }
  9125.  
  9126. // 题目链接
  9127. let problem_url = window.location.href;
  9128. if (problem_url.includes('/contest/')) {
  9129. problem_url = problem_url.replace(/\/contest\/(\d+)\/problem\/(\w+)[^\w]*/, '/contest/$1/problem/$2');
  9130. } else {
  9131. problem_url = problem_url.replace(/\/problemset\/problem\/(\d+)\/(\w+)/, '/contest/$1/problem/$2');
  9132. }
  9133. if (OJBetter.typeOfPage.is_mSite) problem_url = problem_url.replace(/\/\/(\w+).codeforces.com/, '//codeforces.com'); // 轻量站
  9134.  
  9135. // 比赛名
  9136. // let contest = $('#sidebar').children().first().find('.rtable th').first().text();
  9137.  
  9138. // rating
  9139. problemToolbar.updateText(clistButton, i18next.t('state.loading', { ns: 'button' }));
  9140. let rating = await getRatingFromApi_problem(problemId, problem_url);
  9141. if (rating) {
  9142. let className = getClassNameByRating(rating);
  9143. problemToolbar.updateText(clistButton, rating);
  9144. problemToolbar.setBold(clistButton);
  9145. problemToolbar.addClass(clistButton, className);
  9146. } else {
  9147. problemToolbar.updateText(clistButton, i18next.t('state.404', { ns: 'button' }));
  9148. problemToolbar.disableButton(clistButton);
  9149. }
  9150. }
  9151.  
  9152. /**
  9153. * contest页显示Rating
  9154. * @returns {Promise<void>}
  9155. */
  9156. async function showRatingByClist_contest() {
  9157. // 创建Rating显示框
  9158. creatRatingCss();
  9159. let ratingBadges = {};
  9160. // $('.datatable .id.left').each(function () {
  9161. // let href = 'https://codeforces.com' + $(this).find('a').attr('href');
  9162. // let badge = OJB_safeCreateJQElement(`<a id="clistButton" class="ratingBadge">${i18next.t('state.wait', { ns: 'button' })}</a>`);
  9163. // $(this).find('a').after(badge);
  9164. // ratingBadges[href] = badge;
  9165. // });
  9166. $('table tbody tr').each(function () {
  9167. let href = 'https://atcoder.jp' + $(this).find('a').attr('href');
  9168. let badge = OJB_safeCreateJQElement(`<a id="clistButton" class="ratingBadge">${i18next.t('state.wait', { ns: 'button' })}</a>`);
  9169. $(this).find('a:first').after(badge);
  9170. ratingBadges[href] = badge;
  9171. });
  9172.  
  9173. // 检测clist连接
  9174. if (!await validateClistConnection()) {
  9175. for (let href in ratingBadges) {
  9176. ratingBadges[href].text('error').addClass('ratingBadge_error');
  9177. }
  9178. return;
  9179. }
  9180.  
  9181. // 显示loading
  9182. for (let href in ratingBadges) {
  9183. ratingBadges[href].text(i18next.t('state.loading', { ns: 'button' })).addClass('ratingBadge_loading');
  9184. }
  9185.  
  9186. // 获取Rating
  9187. // let contestName = $('#sidebar').children().first().find('.rtable th').first().text();
  9188. let contestName = window.location.href.match(/\/contests\/[^\/]*?(\d+)\/tasks/)?.[1];
  9189. // let contestUrl = OJB_cleanLink(window.location.href);
  9190. let contestUrl = OJB_cleanLink(window.location.href.replace(/\/tasks\/?.*$/, ''));
  9191. try {
  9192. let problemsMap = await getRatingFromApi_contest(contestName, contestUrl);
  9193.  
  9194. // 填充数据
  9195. for (let href in ratingBadges) {
  9196. if (problemsMap.has(href)) {
  9197. let rating = problemsMap.get(href);
  9198. let className = getClassNameByRating(rating);
  9199. ratingBadges[href].text(rating).addClass(className);
  9200. } else {
  9201. ratingBadges[href].text(i18next.t('state.404', { ns: 'button' })).addClass('ratingBadge_no');
  9202. }
  9203. }
  9204. } catch (error) {
  9205. // 填充数据
  9206. for (let href in ratingBadges) {
  9207. ratingBadges[href].text(i18next.t('state.netError', { ns: 'button' })).addClass('ratingBadge_no');
  9208. }
  9209. console.warn(error);
  9210. }
  9211. }
  9212.  
  9213. /**
  9214. * problemset页显示Rating
  9215. * @returns {Promise<void>}
  9216. */
  9217. async function showRatingByClist_problemset() {
  9218. creatRatingCss();
  9219. let ratingBadges = [];
  9220. const $problems = $('.problems');
  9221. const $trs = $problems.find('tbody tr:gt(0)');
  9222.  
  9223. // 先创建Rating显示框,并将关系存进数组ratingBadges
  9224. for (let i = 0; i < $trs.length; i++) {
  9225. const $tds = $($trs[i]).find('td');
  9226. const $firstDiv = $($tds[1]).find('div:first');
  9227. let problem = $firstDiv.text();
  9228. let problem_url = $firstDiv.find('a').attr('href');
  9229. problem_url = problem_url.replace(/^\/problemset\/problem\/(\d+)\/(\w+)/, 'https://codeforces.com/contest/$1/problem/$2');
  9230.  
  9231. const ratingBadge = OJB_safeCreateJQElement(`<a id="clistButton" class="ratingBadge"></a>`);
  9232. const rating = OJB_safeCreateJQElement(`<span class="rating">${i18next.t('state.wait', { ns: 'button' })}</span>`);
  9233. ratingBadge.append(rating);
  9234. $($tds[0]).find('a').after(ratingBadge);
  9235. ratingBadges.push({ ratingBadge, rating, problem, problem_url });
  9236. }
  9237.  
  9238. // 检测clist连接
  9239. if (!await validateClistConnection()) {
  9240. for (let i = 0; i < rating.length; i++) {
  9241. ratingBadges[i].rating.text(i18next.t('state.netError', { ns: 'button' }));
  9242. }
  9243. return;
  9244. }
  9245.  
  9246. // 每次只获取3个rating
  9247. for (let i = 0; i < ratingBadges.length; i += 3) {
  9248. const promises = [];
  9249. const endIndex = Math.min(i + 3, ratingBadges.length);
  9250.  
  9251. for (let j = i; j < endIndex; j++) {
  9252. const ratingBadge = ratingBadges[j];
  9253. // 显示请求中
  9254. ratingBadge.rating.text(i18next.t('state.loading', { ns: 'button' }));
  9255. promises.push(getRatingFromHTML(ratingBadge.problem, ratingBadge.problem_url).catch(error => console.warn(error)));
  9256. }
  9257.  
  9258. const results = await Promise.all(promises);
  9259.  
  9260. for (let j = i; j < endIndex; j++) {
  9261. const result = results[j - i];
  9262. const ratingBadge = ratingBadges[j];
  9263. if (result) {
  9264. let className = getClassNameByRating(result.rating);
  9265. ratingBadge.ratingBadge.addClass(className);
  9266. ratingBadge.rating.text(result.rating);
  9267. } else {
  9268. ratingBadge.rating.text(i18next.t('state.404', { ns: 'button' }));
  9269. }
  9270. }
  9271. }
  9272. }
  9273.  
  9274. /**
  9275. * 存放编辑器语言select的值与Monaco语言对应关系的map.
  9276. * @type {Object.<string, string>}
  9277. */
  9278. // const value_monacoLanguageMap = {
  9279. // "4": "pascal", "6": "php", "7": "python", "9": "csharp", "13": "perl", "20": "scala", "31": "python",
  9280. // "32": "go", "34": "javascript", "36": "java", "40": "python", "41": "python", "43": "cpp",
  9281. // "50": "cpp", "51": "pascal", "52": "cpp", "54": "cpp", "55": "javascript", "59": "cpp", "60": "java",
  9282. // "61": "cpp", "65": "csharp", "67": "ruby", "70": "python", "73": "cpp", "74": "java", "75": "rust",
  9283. // "77": "kotlin", "79": "csharp", "80": "cpp", "83": "kotlin", "87": "java"
  9284. // };
  9285. const value_monacoLanguageMap = {
  9286. "5001": "cpp", "5002": "go", "5003": "csharp", "5004": "kotlin", "5005": "java",
  9287. "5006": "nim", "5007": "text", "5008": "text", "5009": "javascript", "5010": "javascript",
  9288. "5011": "r", "5012": "d", "5013": "d", "5014": "swift", "5015": "dart",
  9289. "5016": "php", "5017": "cpp", "5018": "ruby", "5019": "crystal", "5020": "text",
  9290. "5021": "fsharp", "5022": "julia", "5023": "sh", "5024": "text", "5025": "haskell",
  9291. "5026": "fortran", "5027": "lua", "5028": "cpp", "5029": "lisp", "5030": "cobol",
  9292. "5031": "cpp", "5032": "sh", "5033": "python", "5034": "sh", "5035": "text",
  9293. "5036": "text", "5037": "perl", "5038": "sh", "5039": "text", "5040": "text",
  9294. "5041": "pascal", "5042": "csharp", "5043": "lua", "5044": "prolog", "5045": "sh",
  9295. "5046": "scheme", "5047": "scala", "5048": "vbscript", "5049": "text", "5050": "clojure",
  9296. "5051": "erlang", "5052": "typescript", "5053": "cpp", "5054": "rust", "5055": "python",
  9297. "5056": "scala", "5057": "text", "5058": "typescript", "5059": "ocaml", "5060": "raku",
  9298. "5061": "text", "5062": "lisp", "5063": "python", "5064": "clojure", "5065": "text",
  9299. "5066": "text", "5067": "text", "5068": "ada", "5069": "text", "5070": "text",
  9300. "5071": "clojure", "5072": "cpp", "5073": "cpp", "5074": "text", "5075": "lisp",
  9301. "5076": "text", "5077": "d", "5078": "python", "5079": "text", "5080": "text",
  9302. "5081": "ocaml", "5082": "python", "5083": "matlab", "5084": "haxe", "5085": "elixir",
  9303. "5086": "text", "5087": "text", "5088": "lisp", "5089": "text", "5090": "cobol"
  9304. };
  9305.  
  9306. /**
  9307. * 更新代码提交页的HTML
  9308. * @param {string} submitUrl 提交页面的URL
  9309. * @param {string} cacheKey 本地缓存的键名
  9310. * @returns {Promise<jQuery<HTMLElement>>} 返回 jQuery 包装的 HTML 元素
  9311. */
  9312. async function CloneOriginalHTML(submitUrl, cacheKey) {
  9313. return OJB_promiseRetryWrapper(async () => {
  9314. const response = await OJB_GMRequest({
  9315. method: 'GET',
  9316. url: submitUrl
  9317. });
  9318. const html = response.responseText;
  9319. const parser = new DOMParser();
  9320. const doc = parser.parseFromString(html, 'text/html');
  9321. const cloneHTML = $(doc.body).html();
  9322. localStorage.setItem(cacheKey, html);
  9323. return $(cloneHTML);
  9324. }, {
  9325. maxRetries: 5,
  9326. retryInterval: 1000,
  9327. errorHandler: (err) => {
  9328. console.error('A network error occurred while retrieving the HTML for the code submission page.', submitUrl);
  9329. }
  9330. });
  9331. }
  9332.  
  9333. /**
  9334. * 获取代码提交页的HTML元素
  9335. * @param {string} submitUrl
  9336. * @returns {Promise<jQuery>}
  9337. */
  9338. async function getSubmitHTML(submitUrl) {
  9339. const cacheKey = 'OJBetter_CloneOriginalHTML';
  9340. const cookieKey = 'OJBetter_CloneOriginalHTML_time';
  9341. if (OJB_getCookie(cookieKey) === '1') {
  9342. // 存在缓存
  9343. CloneOriginalHTML(submitUrl, cacheKey);
  9344. // 校验
  9345. let cloneHTML = $(localStorage.getItem(cacheKey));
  9346. if (cloneHTML.find('form.submit-form').length > 0) {
  9347. return cloneHTML;
  9348. } else {
  9349. // 存在错误,更新缓存
  9350. console.warn(`Cache error detected!\nattempting to update, cache destination submitUrl:\n${submitUrl}`);
  9351. return await CloneOriginalHTML(submitUrl, cacheKey);
  9352. }
  9353.  
  9354. } else {
  9355. // 没有缓存,更新
  9356. document.cookie = `${cookieKey}=1; path=/`;
  9357. return await CloneOriginalHTML(submitUrl, cacheKey);
  9358. }
  9359. }
  9360.  
  9361. // 代码自动保存
  9362. async function saveCode(url, code) {
  9363. try {
  9364. await OJBetter.common.database.editorCode.put({ url, code });
  9365. return 'Code saved successfully';
  9366. } catch (error) {
  9367. throw new Error('Failed to save code');
  9368. }
  9369. }
  9370.  
  9371. async function getCode(url) {
  9372. try {
  9373. const result = await OJBetter.common.database.editorCode.get(url);
  9374. return result ? result.code : null;
  9375. } catch (error) {
  9376. throw new Error('Failed to get code');
  9377. }
  9378. }
  9379.  
  9380. // 创建代码编辑调试表单元素
  9381. // async function createCodeEditorForm(submitUrl, cloneHTML) {
  9382. async function createCodeEditorForm(submitUrl) {
  9383. // 表单
  9384. let formDiv = $('<form method="post" id="OJBetter_SubmitForm" class="input-output-copier"></form>');
  9385. // $('.ttypography').after(formDiv);
  9386. $('#task-statement').after(formDiv);
  9387. // formDiv.attr('action', submitUrl + "?csrf_token=" + OJBetter.common.at_csrf_token);
  9388. formDiv.attr('action', submitUrl);
  9389. formDiv.attr('method', 'POST');
  9390.  
  9391. // 顶部区域
  9392. let topDiv = OJB_safeCreateJQElement(`<div class="topDiv"></div>`);
  9393. let selectLang = $('#select-lang').clone(); // 语言选择
  9394. // selectLang.css({ 'margin': '10px 0px' }).attr('id', 'programTypeId');
  9395. topDiv.append(selectLang);
  9396. let topRightDiv = OJB_safeCreateJQElement(`<div class="topRightDiv"></div>`);
  9397. topDiv.append(topRightDiv);
  9398. formDiv.append(topDiv);
  9399.  
  9400. // 问题选择/编号
  9401. // let selectProblem = $('<input name="submittedProblemIndex" style="display:none;"></input>');
  9402. // let problemCode;
  9403. // if (OJBetter.typeOfPage.is_acmsguru) {
  9404. // problemCode = $('h4').eq(0).text();
  9405. // let matchResult = problemCode.match(/([A-Z0-9]+)/);
  9406. // problemCode = matchResult[0];
  9407. // } else if (OJBetter.typeOfPage.is_problemset_problem) {
  9408. // let match = window.location.href.match(/\/problem\/([0-9]+?)\/([A-Z0-9]+?)(?!=[A-Z0-9])/);
  9409. // problemCode = match[1] + match[2];
  9410. // selectProblem.attr('name', 'submittedProblemCode');
  9411. // } else {
  9412. // problemCode = $('.header .title').eq(0).text();
  9413. // let matchResult = problemCode.match(/([A-Z0-9]+)/);
  9414. // problemCode = matchResult[0];
  9415. // }
  9416. // selectProblem.val(problemCode);
  9417. let selectProblem = $('input[name="data.TaskScreenName"]').clone();
  9418. formDiv.append(selectProblem);
  9419.  
  9420. // 隐藏的代码记录
  9421. // let sourceDiv = $('<textarea id="sourceCodeTextarea" name="source" style="display: none;"></textarea>');
  9422. let sourceDiv = $('<textarea id="plain-textarea" name="sourceCode" style="display: none;"></textarea>');
  9423. formDiv.append(sourceDiv);
  9424.  
  9425. // 隐藏的crsf token
  9426. let csrfDiv = $(`<input type="hidden" name="csrf_token" value=${OJBetter.common.at_csrf_token}>`);
  9427. formDiv.append(csrfDiv);
  9428.  
  9429. // 代码编辑器
  9430. let editorDiv = $('<div id="OJBetter_editor"></div>');
  9431. formDiv.append(editorDiv);
  9432.  
  9433. // monaco
  9434. let monaco = $('<div id="OJBetter_monaco"></div>');
  9435. editorDiv.append(monaco);
  9436.  
  9437. // 自定义调试
  9438. let customTestDiv = OJB_safeCreateJQElement(`
  9439. <details id="customTestBlock">
  9440. <summary >${i18next.t('customTestBlock.title', { ns: 'codeEditor' })}</summary>
  9441. <div id="customTests" style="min-height: 30px;"></div>
  9442. <div id="control" style="display:flex;">
  9443. <div style="display: flex;margin: 5px;">
  9444. <input type="checkbox" id="onlyCustomTest"}><label for="onlyCustomTest">
  9445. ${i18next.t('customTestBlock.onlyCustom', { ns: 'codeEditor' })}
  9446. </label>
  9447. </div>
  9448. <div style="display: flex;margin: 5px;">
  9449. <input type="checkbox" id="DontShowDiff"}>
  9450. <label for="DontShowDiff">
  9451. ${i18next.t('customTestBlock.DontShowDiff', { ns: 'codeEditor' })}
  9452. </label>
  9453. </div>
  9454. <button type="button" id="addCustomTest">${i18next.t('customTestBlock.add', { ns: 'codeEditor' })}</button>
  9455. </div>
  9456. </details>
  9457. `)
  9458. formDiv.append(customTestDiv);
  9459.  
  9460. // 调试/提交
  9461. let submitDiv = $('<div id="OJBetter_submitDiv"></div>');
  9462. let CompilerArgsInput = $('<input type="text" id="CompilerArgsInput">');
  9463. submitDiv.append(CompilerArgsInput);
  9464.  
  9465. let runButton = OJB_safeCreateJQElement(`
  9466. <button type="button" id="RunTestButton" class="ojb_btn ojb_btn_popover top">
  9467. <i class="iconfont">&#xe6c1;</i>
  9468. <span class="popover_content">${i18next.t('runTestButton.initial', { ns: 'codeEditor' })}</span>
  9469. </button>
  9470. `);
  9471. let submitButton = OJB_safeCreateJQElement(`
  9472. <button id="SubmitButton" class="ojb_btn ojb_btn_popover top" type="submit">
  9473. <i class="iconfont">&#xe633;</i>
  9474. <span class="popover_content">${i18next.t('submitButton', { ns: 'codeEditor' })}</span>
  9475. </button>
  9476. `);
  9477. if (OJBetter.monaco.setting.submitButtonPosition == "bottom") {
  9478. // 添加测试/提交按钮到底部
  9479. submitDiv.append(runButton);
  9480. submitDiv.append(submitButton);
  9481. }
  9482.  
  9483. formDiv.append(submitDiv);
  9484. let CompilerSetting = OJB_safeCreateJQElement(`
  9485. <div id="CompilerSetting"></div>
  9486. `);
  9487. formDiv.append(CompilerSetting);
  9488. let statePanel = OJB_safeCreateJQElement(`
  9489. <div id="statePanel"></div>
  9490. `);
  9491. formDiv.append(statePanel);
  9492.  
  9493. //==================================
  9494. // 去除原有的编辑器
  9495. //==================================
  9496. $('.form-code-submit').remove();
  9497.  
  9498. let from = {
  9499. formDiv: formDiv,
  9500. selectLang: selectLang.find('select:first'),
  9501. topRightDiv: topRightDiv,
  9502. sourceDiv: sourceDiv,
  9503. editorDiv: editorDiv,
  9504. monaco: monaco,
  9505. runButton: runButton,
  9506. submitButton: submitButton,
  9507. submitDiv: submitDiv,
  9508. CompilerSetting: CompilerSetting,
  9509. statePanel: statePanel
  9510. };
  9511. return from;
  9512. }
  9513.  
  9514. // 解析ace格式的补全规则(acwing)
  9515. function parseAceCompleter(rules, range) {
  9516. const suggestions = [];
  9517. if (rules && rules.templates && rules.templates.items) {
  9518. const items = rules.templates.items;
  9519. for (let i = 0; i < items.length; i++) {
  9520. const item = items[i];
  9521. const parts = item.caption.split(' ');
  9522. for (let i = 0; i < parts.length; i++) {
  9523. if (item.value.startsWith(parts[i])) {
  9524. item.value = item.value.replace(parts[i], parts.slice(0, i + 1).join(' '));
  9525. break;
  9526. }
  9527. }
  9528. const completionItem = {
  9529. label: item.caption,
  9530. kind: monaco.languages.CompletionItemKind.Function,
  9531. insertText: item.value,
  9532. range: range
  9533. };
  9534. suggestions.push(completionItem);
  9535. }
  9536. }
  9537. return { suggestions };
  9538. }
  9539.  
  9540. // 解析monaco格式的补全规则
  9541. function parseMonacoCompleter(rules, range) {
  9542. const suggestions_ = [];
  9543. if (rules && rules.suggestions) {
  9544. const suggestion = rules.suggestions;
  9545. for (let i = 0; i < rules.suggestions.length; i++) {
  9546. const item = suggestion[i];
  9547. const completionItem = {
  9548. ...item,
  9549. range: range
  9550. };
  9551. suggestions_.push(completionItem);
  9552. }
  9553. }
  9554. return { suggestions: suggestions_ };
  9555. }
  9556.  
  9557. /**
  9558. * 创建monaco编辑器的一个实例
  9559. */
  9560. async function createMonacoEditor(language, form, support) {
  9561. // 判断monacoLoader是否加载完毕
  9562. async function waitForMonacoLoaderOnload() {
  9563. return new Promise((resolve) => {
  9564. const checkInitialized = () => {
  9565. if (OJBetter.monaco.loaderOnload) {
  9566. resolve();
  9567. } else {
  9568. setTimeout(checkInitialized, 100); // 每100毫秒检查一次initialized的值
  9569. }
  9570. };
  9571. checkInitialized();
  9572. });
  9573. }
  9574. if (!OJBetter.monaco.loaderOnload) await waitForMonacoLoaderOnload();
  9575.  
  9576. /**
  9577. * 通用参数
  9578. */
  9579. var id = 0; // 协议中的id标识
  9580. var workspace = language + "_workspace";
  9581. var rootUri = OJBetter.monaco.lsp.workUri + "/" + workspace;
  9582. // 文件名
  9583. var InstanceID = OJB_getRandomNumber(8).toString();
  9584. var filename = language == "java" ? "hello/src/" + InstanceID : InstanceID;
  9585. // 后缀名
  9586. var fileExtension =
  9587. language === "cpp"
  9588. ? ".cpp"
  9589. : language === "python"
  9590. ? ".py"
  9591. : language === "java"
  9592. ? ".java"
  9593. : "";
  9594. var uri = rootUri + "/" + filename + fileExtension;
  9595. var initialized = false; // 是否已初始化
  9596. var serverInfo; // 服务器返回的支持信息
  9597. var model; // model
  9598. var OJBetter_monaco = {};
  9599. window.OJBetter_monaco = OJBetter_monaco; // 全局方法
  9600.  
  9601. /**
  9602. * 一些工具函数
  9603. */
  9604. // 将lsp格式的rang转换为Monaco格式
  9605. OJBetter_monaco.lspRangeToMonacoRange = function (range) {
  9606. const { start, end } = range;
  9607. return new monaco.Range(
  9608. start.line + 1,
  9609. start.character + 1,
  9610. end.line + 1,
  9611. end.character + 1
  9612. );
  9613. };
  9614. // 将Monaco格式的rang转为lsp格式
  9615. OJBetter_monaco.MonacoRangeTolspRange = function (range) {
  9616. return {
  9617. start: {
  9618. line: range.startLineNumber - 1,
  9619. character: range.startColumn - 1,
  9620. },
  9621. end: {
  9622. line: range.endLineNumber - 1,
  9623. character: range.endColumn - 1,
  9624. },
  9625. };
  9626. };
  9627. // 将Monaco格式的position转为lsp格式的
  9628. OJBetter_monaco.MonacoPositionTolspPosition = function (position) {
  9629. return {
  9630. line: position.lineNumber - 1,
  9631. character: position.column - 1,
  9632. };
  9633. };
  9634. // 将Monaco格式的severity转为lsp格式的
  9635. OJBetter_monaco.MonacoSeverityTolspSeverity = function (severity) {
  9636. switch (severity) {
  9637. case 8:
  9638. return 1;
  9639. case 1:
  9640. return 4;
  9641. case 2:
  9642. return 3;
  9643. case 4:
  9644. return 2;
  9645. default:
  9646. return severity;
  9647. }
  9648. };
  9649. // 将lsp格式的severity转为Monaco格式的
  9650. OJBetter_monaco.lspSeverityToMonacoSeverity = function (severity) {
  9651. switch (severity) {
  9652. case 1:
  9653. return 8;
  9654. case 4:
  9655. return 1;
  9656. case 3:
  9657. return 2;
  9658. case 2:
  9659. return 4;
  9660. default:
  9661. return severity;
  9662. }
  9663. };
  9664. // 收集Monaco数据中的rang数据
  9665. OJBetter_monaco.CollectRange = function (item) {
  9666. return {
  9667. startLineNumber: item.startLineNumber,
  9668. startColumn: item.startColumn,
  9669. endLineNumber: item.endLineNumber,
  9670. endColumn: item.endColumn,
  9671. };
  9672. };
  9673. // 收集Monaco position数据中的rang数据
  9674. OJBetter_monaco.CollectRangeByPosition = function (item) {
  9675. var word = model.getWordUntilPosition(item);
  9676. return {
  9677. startLineNumber: item.lineNumber,
  9678. endLineNumber: item.lineNumber,
  9679. startColumn: word.startColumn,
  9680. endColumn: word.endColumn,
  9681. };
  9682. };
  9683. // 将lsp格式的Edit转换为Monaco格式
  9684. OJBetter_monaco.lspEditToMonacoEdit = function (edit) {
  9685. const edits = [];
  9686.  
  9687. if (language == "python") {
  9688. for (const item1 of edit.documentChanges) {
  9689. for (const item2 of item1.edits) {
  9690. const newElement = {
  9691. textEdit: {
  9692. range: OJBetter_monaco.lspRangeToMonacoRange(item2.range),
  9693. text: item2.newText,
  9694. },
  9695. resource: monaco.Uri.parse(item1.textDocument.uri),
  9696. versionId: model.getVersionId(),
  9697. };
  9698. edits.push(newElement);
  9699. }
  9700. }
  9701. } else if (language == "java") {
  9702. for (const item1 in edit.changes) {
  9703. edit.changes[item1].forEach((item2) => {
  9704. const newElement = {
  9705. textEdit: {
  9706. range: OJBetter_monaco.lspRangeToMonacoRange(item2.range),
  9707. text: item2.newText,
  9708. },
  9709. resource: uri,
  9710. versionId: model.getVersionId(),
  9711. };
  9712. edits.push(newElement);
  9713. });
  9714. }
  9715. } else {
  9716. for (const key in edit.changes) {
  9717. const arr = edit.changes[key];
  9718. for (const item of arr) {
  9719. const newElement = {
  9720. textEdit: {
  9721. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  9722. text: item.newText,
  9723. },
  9724. resource: monaco.Uri.parse(key),
  9725. versionId: model.getVersionId(),
  9726. };
  9727. edits.push(newElement);
  9728. }
  9729. }
  9730. }
  9731. return { edits: edits };
  9732. };
  9733.  
  9734. /**
  9735. * 实例化一个editor
  9736. */
  9737. uri = monaco.Uri.file(uri);
  9738. model = monaco.editor.createModel('', language, uri);
  9739. OJBetter.monaco.editor = monaco.editor.create(document.getElementById("OJBetter_monaco"), {
  9740. model: model,
  9741. rootUri: rootUri,
  9742. fontSize: 15,
  9743. tabSize: 4,
  9744. theme: OJBetter.basic.darkMode == "dark" ? "vs-dark" : "vs",
  9745. bracketPairColorization: {
  9746. enabled: true,
  9747. independentColorPoolPerBracketType: true,
  9748. },
  9749. automaticLayout: true,
  9750. lineNumbersMinChars: 3,
  9751. matchOnWordStartOnly: false,
  9752. wordWrap: "on",
  9753. wrappingIndent: "same",
  9754. glyphMargin: true,
  9755. formatOnType: true,
  9756. scrollbar: {
  9757. verticalScrollbarSize: 10,
  9758. horizontalScrollbarSize: 10,
  9759. alwaysConsumeMouseWheel: OJBetter.monaco.setting.alwaysConsumeMouseWheel
  9760. },
  9761. suggest: {
  9762. selectionMode: 'never' // 代码建议不自动选择
  9763. }
  9764. });
  9765.  
  9766. /**
  9767. * 添加快捷功能
  9768. */
  9769. (OJBetter_monaco.addShortCuts = async () => {
  9770. // 从配置信息更新字体大小
  9771. OJBetter.monaco.editor.updateOptions({ fontSize: parseInt(OJBetter.monaco.setting.fontsize) });
  9772.  
  9773. // 调整字体大小
  9774. let changeSize = OJB_safeCreateJQElement(`
  9775. <div class="ojb_btn ojb_btn_popover top">
  9776. <input type="number" id="fontSizeInput" value="${OJBetter.monaco.setting.fontsize}">
  9777. <span class="popover_content">${i18next.t('fontSizeInput', { ns: 'codeEditor' })}</span>
  9778. </div>`)
  9779. form.topRightDiv.append(changeSize);
  9780. changeSize.find('input#fontSizeInput').on('input', function () {
  9781. var size = $(this).val();
  9782. OJBetter.monaco.editor.updateOptions({ fontSize: parseInt(size) });
  9783. GM_setValue('editorFontSize', size);
  9784. });
  9785.  
  9786. // 全屏按钮
  9787. let fullscreenButton = OJB_safeCreateJQElement(`
  9788. <button type="button" class="ojb_btn ojb_btn_popover top">
  9789. <i class="iconfont">&#xe606;</i>
  9790. <span class="popover_content">${i18next.t('fullscreenButton', { ns: 'codeEditor' })}</span>
  9791. </button>
  9792. `);
  9793. form.topRightDiv.append(fullscreenButton);
  9794. fullscreenButton.on('click', enterFullscreen);
  9795.  
  9796. // 固定到底部按钮
  9797. let fixToBottomButton = OJB_safeCreateJQElement(`
  9798. <button type="button" class="ojb_btn ojb_btn_popover top">
  9799. <i class="iconfont">&#xe607;</i>
  9800. <span class="popover_content">${i18next.t('fixToBottomButton', { ns: 'codeEditor' })}</span>
  9801. </button>
  9802. `);
  9803. form.topRightDiv.append(fixToBottomButton);
  9804. fixToBottomButton.on('click', fixToBottom);
  9805.  
  9806. // 固定到右侧按钮
  9807. let fixToRightButton = OJB_safeCreateJQElement(`
  9808. <button type="button" class="ojb_btn ojb_btn_popover top">
  9809. <i class="iconfont">&#xe605;</i>
  9810. <span class="popover_content">${i18next.t('fixToRightButton', { ns: 'codeEditor' })}</span>
  9811. </button>
  9812. `);
  9813. // form.topRightDiv.append(fixToRightButton);
  9814. fixToRightButton.on('click', fixToRight);
  9815.  
  9816. // 添加测试/提交按钮到顶部
  9817. if (OJBetter.monaco.setting.submitButtonPosition == "top") {
  9818. form.topRightDiv.append(form.runButton);
  9819. form.topRightDiv.append(form.submitButton);
  9820. }
  9821.  
  9822. // 选择记忆
  9823. if (!OJBetter.monaco.setting.position_initialized) {
  9824. OJBetter.monaco.setting.position_initialized = true; // 标记是否已经初始化过
  9825. if (OJBetter.monaco.setting.position == "full") {
  9826. fullscreenButton.click();
  9827. } else if (OJBetter.monaco.setting.position == "bottom") {
  9828. fixToBottomButton.click();
  9829. } else if (OJBetter.monaco.setting.position == "right") {
  9830. fixToRightButton.click();
  9831. }
  9832. }
  9833.  
  9834. // 禁用按钮
  9835. function disableButtons() {
  9836. fullscreenButton.prop("disabled", true);
  9837. fixToBottomButton.prop("disabled", true);
  9838. fixToRightButton.prop("disabled", true);
  9839. }
  9840.  
  9841. // 启用按钮
  9842. function enableButtons() {
  9843. fullscreenButton.prop("disabled", false);
  9844. fixToBottomButton.prop("disabled", false);
  9845. fixToRightButton.prop("disabled", false);
  9846. }
  9847.  
  9848. // 进入全屏
  9849. function enterFullscreen() {
  9850. let editor = $('#OJBetter_editor');
  9851. editor.addClass('fullscreen');
  9852.  
  9853. // 取消按钮
  9854. let cancelButton = OJB_safeCreateJQElement(`
  9855. <button type="button" class="ojb_btn ojb_btn_popover top primary exit_button_bottom">
  9856. <i class="iconfont">&#xe60b;</i>
  9857. <span class="popover_content">${i18next.t('exitFullscreenButton', { ns: 'codeEditor' })}</span>
  9858. </button>
  9859. `).on('click', () => exitFullscreen(cancelButton));
  9860. $('body').append(cancelButton);
  9861.  
  9862. disableButtons();
  9863. GM_setValue("monacoEditor_position", "full");
  9864. }
  9865.  
  9866. // 退出全屏
  9867. const exitFullscreen = (cancelButton) => {
  9868. let editor = $('#OJBetter_editor');
  9869. editor.removeClass('fullscreen');
  9870. cancelButton.remove();
  9871. enableButtons();
  9872. GM_setValue("monacoEditor_position", "initial");
  9873. };
  9874.  
  9875. // 固定到底部
  9876. function fixToBottom() {
  9877. let editor = $('#OJBetter_editor');
  9878. editor.addClass('bottom');
  9879.  
  9880. let halfHeight = $(window).height() * 0.5;
  9881. let blankSpace = $('<div>', {
  9882. 'class': 'blank-space',
  9883. 'style': 'height: ' + (halfHeight + 30) + 'px;'
  9884. });
  9885. $('body').append(blankSpace);
  9886.  
  9887. let cancelButton = OJB_safeCreateJQElement(`
  9888. <button type="button" class="ojb_btn ojb_btn_popover top enabled exit_button_bottom">
  9889. <i class="iconfont">&#xe625;</i>
  9890. <span class="popover_content">${i18next.t('cancelFixButton', { ns: 'codeEditor' })}</span>
  9891. </button>
  9892. `).on('click', () => cancelFixingToBottom(cancelButton, blankSpace));
  9893. $('body').append(cancelButton);
  9894.  
  9895. disableButtons();
  9896. GM_setValue("monacoEditor_position", "bottom");
  9897. }
  9898.  
  9899. // 取消固定到底部
  9900. const cancelFixingToBottom = (cancelButton, blankSpace) => {
  9901. let editor = $('#OJBetter_editor');
  9902. editor.removeClass('bottom');
  9903. cancelButton.remove();
  9904. blankSpace.remove();
  9905. enableButtons();
  9906. GM_setValue("monacoEditor_position", "initial");
  9907. };
  9908.  
  9909. // 固定到右侧边栏
  9910. function fixToRight() {
  9911. const sidebar = $('#sidebar').hide();
  9912.  
  9913. // 添加样式
  9914. const styleElement = GM_addStyle(`
  9915. #body {
  9916. min-width: 50vw;
  9917. max-width: 50vw;
  9918. max-height: 100vh;
  9919. overflow-x: hidden;
  9920. overflow-y: auto;
  9921. padding: 1rem;
  9922. box-sizing: border-box;
  9923. }
  9924. body {
  9925. margin: 0px;
  9926. }
  9927. .content-with-sidebar {
  9928. margin-right: 0px !important;
  9929. }
  9930. .menu-list li {
  9931. margin-right: 0.5em;
  9932. }
  9933. .menu-list li a {
  9934. font-size: 1.4rem;
  9935. }
  9936. #OJBetter_editor{
  9937. height: 100vh;
  9938. width: 50vw;
  9939. }
  9940. `);
  9941.  
  9942. // 包装一层div
  9943. $('#body').wrap('<div id="right-side-wrapper" style="display:flex; max-width: 100vw; overflow: hidden;"></div>');
  9944. const blankSpace = $('<div>').appendTo('#right-side-wrapper');
  9945.  
  9946. // 移动编辑器
  9947. const editor = $('#OJBetter_editor').prependTo(blankSpace).addClass('right-side');
  9948.  
  9949. // 取消按钮
  9950. const cancelButton = OJB_safeCreateJQElement(`
  9951. <button type="button" class="ojb_btn ojb_btn_popover top enabled exit_button_bottom">
  9952. <i class="iconfont">&#xe625;</i>
  9953. <span class="popover_content">${i18next.t('cancelFixButton', { ns: 'codeEditor' })}</span>
  9954. </button>
  9955. `).on('click', () => cancelFixingToRight(sidebar, styleElement, editor, cancelButton)).appendTo('body');
  9956.  
  9957. disableButtons();
  9958. GM_setValue("monacoEditor_position", "right");
  9959.  
  9960. // 补丁:修复固定到右侧导致的样例元素.sample-test相关代码重复执行的问题(具体原因未查)
  9961. $('.sample-test').find('.title').each((i, e) => {
  9962. if ($(e).find('.input-output-copier').length > 1) {
  9963. $(e).find('.input-output-copier').first().remove();
  9964. }
  9965. });
  9966. darkModeStyleAdjustment();
  9967. }
  9968.  
  9969. const cancelFixingToRight = (sidebar, styleElement, editor, cancelButton) => {
  9970. sidebar.show();
  9971. // 移回来
  9972. editor.insertAfter(form.sourceDiv).removeClass('right-side');
  9973.  
  9974. // 移除包装
  9975. $('#body').unwrap();
  9976. cancelButton.remove();
  9977. styleElement.remove(); // 移除添加的样式
  9978.  
  9979. enableButtons();
  9980. GM_setValue("monacoEditor_position", "initial");
  9981. }
  9982.  
  9983. // 代码同步与保存
  9984. var nowUrl = window.location.href;
  9985. nowUrl = nowUrl.replace(/#/, ""); // 当页面存在更改时url会多出一个#,去掉
  9986. const code = await getCode(nowUrl);
  9987. if (code) {
  9988. OJBetter.monaco.editor.setValue(code); // 恢复代码
  9989. form.sourceDiv.val(code);
  9990. }
  9991. OJBetter.monaco.editor.onDidChangeModelContent(async () => {
  9992. // 将monaco editor的内容同步到sourceDiv
  9993. const code = OJBetter.monaco.editor.getValue();
  9994. form.sourceDiv.val(code);
  9995. await saveCode(nowUrl, code);
  9996. });
  9997. })();
  9998.  
  9999. /**
  10000. * 注册本地自动补全
  10001. */
  10002. (OJBetter_monaco.RegisterLocalComplet = async () => {
  10003. // 补全器注册函数
  10004. function registMyCompletionItemProvider(language, genre, rule) {
  10005. if (genre == "monaco") {
  10006. monaco.languages.registerCompletionItemProvider(language, {
  10007. provideCompletionItems: function (model, position) {
  10008. return parseMonacoCompleter(rule, OJBetter_monaco.CollectRangeByPosition(position));
  10009. }
  10010. })
  10011. } else if (genre == "ace") {
  10012. monaco.languages.registerCompletionItemProvider(language, {
  10013. provideCompletionItems: function (model, position) {
  10014. return parseAceCompleter(rule, OJBetter_monaco.CollectRangeByPosition(position));
  10015. }
  10016. })
  10017. }
  10018. }
  10019.  
  10020. // 注册acwing cpp 模板
  10021. if (language == "cpp" && OJBetter.monaco.complet.cppCodeTemplate) {
  10022. try {
  10023. var acwing_cpp_code_completer = JSON.parse(GM_getResourceText("acwing_cpp_code_completer"));
  10024. registMyCompletionItemProvider('cpp', 'ace', acwing_cpp_code_completer);
  10025. } catch (error) {
  10026. console.error("Error registering acwing cpp template:", error);
  10027. }
  10028. }
  10029.  
  10030. // 注册自定义的补全
  10031. let complet_length = OJBetter.monaco.complet.customConfig.configurations.length;
  10032. if (complet_length > 0) {
  10033. for (let i = 0; i < complet_length; i++) {
  10034. let item = OJBetter.monaco.complet.customConfig.configurations[i];
  10035. if (item.isChoose && item.language == language) {
  10036. try {
  10037. let rule = await OJB_getExternalJSON(item.jsonUrl);
  10038. registMyCompletionItemProvider(item.language, item.genre, rule);
  10039. } catch (error) {
  10040. console.error(`Error registering custom completer for ${item.language}:`, error);
  10041. }
  10042. }
  10043. }
  10044. }
  10045. })();
  10046.  
  10047. if (!support || !OJBetter.monaco.lsp.enabled) { return; } // 如果不支持lsp,则到此为止
  10048.  
  10049. /**
  10050. * LSP连接状态指示
  10051. */
  10052. const lspStateButton = OJB_safeCreateJQElement(`
  10053. <div id="lspStateDiv" class="ojb_btn ojb_btn_popover top loading">
  10054. <i class="iconfont">&#xe658;</i>
  10055. <span class="popover_content">${i18next.t('lsp.connect', { ns: 'codeEditor' })}</span>
  10056. </div>
  10057. `).on('click', () => {
  10058. OJB_showModal(LSPLogDiv);
  10059. LSPLogDiv.show();
  10060. });
  10061. form.topRightDiv.prepend(lspStateButton);
  10062.  
  10063. const LSPLogDiv = OJB_safeCreateJQElement(`
  10064. <dialog id="LSPLog" style="display: none;">
  10065. <button class="ojb_btn">${i18next.t('close', { ns: 'common' })}</button>
  10066. <div id="LSPLogList" style="overflow: auto;"></div>
  10067. <dialog>`);
  10068. $('body').append(LSPLogDiv);
  10069.  
  10070. const LSPLogList = $('<ul></ul>');
  10071. $('#LSPLogList').append(LSPLogList);
  10072.  
  10073. const closeButton = LSPLogDiv.find('button');
  10074. closeButton.on('click', function () {
  10075. OJB_closeModal(LSPLogDiv);
  10076. });
  10077.  
  10078. /**
  10079. * 推送新的消息到LSP日志中
  10080. * @param {'error' | 'warn' | 'info'} status
  10081. * @param {string} msg
  10082. * @param {boolean} data
  10083. */
  10084. function pushLSPLogMessage(status, msg, data) {
  10085. var li = $('<li>').text('[' + new Date().toLocaleString() + '] ' + msg);
  10086. if (status === 'error') {
  10087. li.attr('style', 'color: #f44336;');
  10088. } else if (status === 'warn') {
  10089. li.attr('style', 'color: #ff9800;');
  10090. } else if (status === 'info') {
  10091. li.attr('style', 'color: #616161;');
  10092. }
  10093. if (data) {
  10094. var jsonText = JSON.stringify(data, null, 2);
  10095. var details = $('<details>');
  10096. var summary = $('<summary>').text('Data');
  10097. var pre = $('<pre>').text(jsonText);
  10098. details.append(summary, pre);
  10099. li.append(details);
  10100. }
  10101. LSPLogList.append(li);
  10102. }
  10103.  
  10104. /**
  10105. * 添加状态底栏
  10106. */
  10107. var statusBar = $('<div id="OJBetter_statusBar">');
  10108. form.editorDiv.append(statusBar);
  10109.  
  10110. /**
  10111. * languageSocket
  10112. */
  10113. var url = OJBetter.monaco.lsp.socketUrl;
  10114. var languageSocket = new WebSocket(url + language);
  10115. OJBetter.monaco.lsp.socket.push(languageSocket);
  10116. var languageSocketState = false;
  10117. var responseHandlers = new Map(); // 映射表,需要等待返回数据的请求 -> 对应的事件触发函数
  10118.  
  10119. languageSocket.onopen = () => {
  10120. languageSocketState = true;
  10121. lspStateButton.setButtonPopover(i18next.t('lsp.waitingAnswer', { ns: 'codeEditor' }));
  10122. pushLSPLogMessage("info", `languageSocket ${i18next.t('lsp.socket.open', { ns: 'logMessage' })}`);
  10123. };
  10124. languageSocket.onmessage = (event) => {
  10125. const message = JSON.parse(event.data);
  10126. if (message.id === 0 && message.result) {
  10127. // 初始化完成
  10128. lspStateButton.setButtonState('success', i18next.t('lsp.connected', { ns: 'codeEditor' }));
  10129. pushLSPLogMessage("info", `Initialization ${i18next.t('lsp.state.finished', { ns: 'logMessage' })}`);
  10130. serverInfo = message.result; // 存下服务器支持信息
  10131. OJBetter_monaco.openDocRequest(); // 打开文档
  10132. if (!OJBetter.monaco.setting.language.includes(language)) {
  10133. OJBetter.monaco.setting.language.push(language);
  10134. OJBetter_monaco.RegistrationAfterInit(); // 注册语言及功能
  10135. } else {
  10136. location.reload(); // 这里有问题,先贴个补丁
  10137. }
  10138. OJBetter_monaco.PassiveReceiveHandler(); // 注册被动接收函数
  10139. } else if (message.id === 0 && message.error) {
  10140. pushLSPLogMessage("warn", `Initialization ${i18next.t('lsp.state.error', { ns: 'logMessage' })}`);
  10141. } else if (message.id !== undefined && responseHandlers.has(message.id)) {
  10142. // 如果收到带有id字段的消息,则回传给对应的事件触发函数
  10143. const handler = responseHandlers.get(message.id);
  10144. if (handler) {
  10145. handler(message);
  10146. responseHandlers.delete(message.id); // 删除已处理的事件触发函数
  10147. }
  10148. } else if (message.method == "textDocument/publishDiagnostics") {
  10149. // 接收代码诊断推送
  10150. OJBetter_monaco.updateMarkers(message);
  10151. } else if (message.method == "workspace/applyEdit") {
  10152. // 应用服务器推送的更改
  10153. OJBetter_monaco.applyEdit(message);
  10154. }
  10155. };
  10156. languageSocket.onerror = (error) => {
  10157. pushLSPLogMessage("error", `languageSocket ${i18next.t('lsp.state.error', { ns: 'logMessage' })}`, error);
  10158. console.warn(`Error connecting to languageSocket: ${error}`)
  10159. };
  10160. languageSocket.onclose = (event) => {
  10161. languageSocketState = false;
  10162. lspStateButton.setButtonState('error', i18next.t('lsp.error', { ns: 'codeEditor' }));
  10163. pushLSPLogMessage("warn", `languageSocket ${i18next.t('lsp.socket.close', { ns: 'logMessage' })}`);
  10164. };
  10165.  
  10166. /**
  10167. * 等待LanguageSocketState
  10168. */
  10169. async function waitForLanguageSocketState() {
  10170. return new Promise((resolve) => {
  10171. const checkInitialized = () => {
  10172. if (languageSocketState) {
  10173. resolve();
  10174. } else {
  10175. setTimeout(checkInitialized, 100); // 每100毫秒检查一次initialized的值
  10176. }
  10177. };
  10178. checkInitialized();
  10179. });
  10180. }
  10181.  
  10182. // 等待lsp响应初始化结果
  10183. async function waitForInitialized() {
  10184. return new Promise((resolve) => {
  10185. const checkInitialized = () => {
  10186. if (initialized) {
  10187. resolve();
  10188. } else {
  10189. setTimeout(checkInitialized, 100); // 每100毫秒检查一次initialized的值
  10190. }
  10191. };
  10192. checkInitialized();
  10193. });
  10194. }
  10195.  
  10196. /**
  10197. * 与languageSocket通信的包装方法
  10198. */
  10199. async function sendMessage(data, requiresResponse, callback) {
  10200. if (!initialized) {
  10201. await waitForInitialized(); // 等待initialized为真
  10202. }
  10203. if (requiresResponse) {
  10204. responseHandlers.set(data.id, callback) // 将事件触发函数与id关联起来
  10205. }
  10206. if (!languageSocketState) await waitForLanguageSocketState();
  10207. languageSocket.send(JSON.stringify(data));
  10208. }
  10209. // 发送消息并等待返回结果
  10210. function fetchData(params, callback) {
  10211. sendMessage(params, true, callback);
  10212. }
  10213. // 发送消息,不需要等待返回结果
  10214. function sendData(data) {
  10215. sendMessage(data, false);
  10216. }
  10217.  
  10218. /**
  10219. * 代码文件更新fileWebSocket
  10220. */
  10221. var fileWebSocket = new WebSocket(url + "file");
  10222. var fileWebSocketState = false;
  10223. OJBetter.monaco.lsp.socket.push(fileWebSocket);
  10224. fileWebSocket.onopen = () => {
  10225. fileWebSocketState = true;
  10226. pushLSPLogMessage("info", `fileWebSocket ${i18next.t('lsp.socket.open', { ns: 'logMessage' })}`);
  10227. };
  10228. fileWebSocket.onclose = (ev) => {
  10229. fileWebSocketState = false;
  10230. pushLSPLogMessage("warn", `fileWebSocket ${i18next.t('lsp.socket.close', { ns: 'logMessage' })}`, ev);
  10231. };
  10232. fileWebSocket.onmessage = (ev) => {
  10233. let message = JSON.parse(ev.data);
  10234. if (message.result !== "ok")
  10235. pushLSPLogMessage("error", `update file failed: ${ev}`);
  10236. };
  10237. fileWebSocket.onerror = (error) => {
  10238. console.warn(`Error connecting to fileWebSocket: ${error}`);
  10239. };
  10240. async function updateFile(workspace, filename, fileExtension, code) {
  10241. async function waitForfileWebSocketState() {
  10242. return new Promise((resolve) => {
  10243. const checkInitialized = () => {
  10244. if (fileWebSocketState) {
  10245. resolve();
  10246. } else {
  10247. setTimeout(checkInitialized, 100); // 每100毫秒检查一次initialized的值
  10248. }
  10249. };
  10250. checkInitialized();
  10251. });
  10252. }
  10253. if (!fileWebSocketState) await waitForfileWebSocketState();
  10254. fileWebSocket.send(
  10255. JSON.stringify({
  10256. type: "update",
  10257. workspace,
  10258. filename,
  10259. fileExtension,
  10260. code,
  10261. })
  10262. );
  10263. }
  10264.  
  10265. /**
  10266. * 发送初始化请求
  10267. */
  10268. OJBetter_monaco.Initialize = () => {
  10269. //初始化initialize
  10270. const capabilities = {
  10271. workspace: {
  10272. applyEdit: true,
  10273. },
  10274. textDocument: {
  10275. publishDiagnostics: {
  10276. relatedInformation: true,
  10277. versionSupport: false,
  10278. tagSupport: {
  10279. valueSet: [1, 2],
  10280. },
  10281. codeDescriptionSupport: true,
  10282. },
  10283. completion: {
  10284. contextSupport: true,
  10285. completionItem: {
  10286. snippetSupport: true,
  10287. commitCharactersSupport: true,
  10288. documentationFormat: ["markdown", "plaintext"],
  10289. deprecatedSupport: true,
  10290. preselectSupport: true,
  10291. tagSupport: {
  10292. valueSet: [1],
  10293. },
  10294. insertReplaceSupport: true,
  10295. resolveSupport: {
  10296. properties: [
  10297. "documentation",
  10298. "detail",
  10299. "additionalTextEdits",
  10300. ],
  10301. },
  10302. insertTextModeSupport: {
  10303. valueSet: [1, 2],
  10304. },
  10305. },
  10306. },
  10307. hover: {
  10308. dynamicRegistration: true,
  10309. contentFormat: ["markdown", "plaintext"],
  10310. },
  10311. signatureHelp: {
  10312. signatureInformation: {
  10313. documentationFormat: ["markdown", "plaintext"],
  10314. parameterInformation: {
  10315. labelOffsetSupport: true,
  10316. },
  10317. activeParameterSupport: true,
  10318. },
  10319. contextSupport: true,
  10320. },
  10321. definition: {
  10322. dynamicRegistration: true,
  10323. linkSupport: true,
  10324. },
  10325. references: {
  10326. dynamicRegistration: true,
  10327. },
  10328. documentHighlight: {
  10329. dynamicRegistration: true,
  10330. },
  10331. codeAction: {
  10332. codeActionLiteralSupport: {
  10333. codeActionKind: {
  10334. valueSet:
  10335. language == "java"
  10336. ? []
  10337. : [
  10338. "",
  10339. "quickfix",
  10340. "refactor",
  10341. "refactor.extract",
  10342. "refactor.inline",
  10343. "refactor.rewrite",
  10344. "source",
  10345. "source.organizeImports",
  10346. ],
  10347. },
  10348. },
  10349. },
  10350. rename: {
  10351. dynamicRegistration: true,
  10352. prepareSupport: true,
  10353. prepareSupportDefaultBehavior: 1,
  10354. honorsChangeAnnotations: true,
  10355. },
  10356. documentLink: {
  10357. tooltipSupport: true,
  10358. },
  10359. typeDefinition: {
  10360. dynamicRegistration: true,
  10361. linkSupport: true,
  10362. },
  10363. implementation: {
  10364. dynamicRegistration: true,
  10365. linkSupport: true,
  10366. },
  10367. colorProvider: {
  10368. dynamicRegistration: true,
  10369. },
  10370. foldingRange: {
  10371. dynamicRegistration: true,
  10372. rangeLimit: 5000,
  10373. lineFoldingOnly: true,
  10374. },
  10375. declaration: {
  10376. dynamicRegistration: true,
  10377. linkSupport: true,
  10378. },
  10379. semanticTokens: {
  10380. dynamicRegistration: true,
  10381. tokenTypes: [
  10382. "namespace",
  10383. "type",
  10384. "class",
  10385. "enum",
  10386. "interface",
  10387. "struct",
  10388. "typeParameter",
  10389. "parameter",
  10390. "variable",
  10391. "property",
  10392. "enumMember",
  10393. "event",
  10394. "function",
  10395. "method",
  10396. "macro",
  10397. "keyword",
  10398. "modifier",
  10399. "comment",
  10400. "string",
  10401. "number",
  10402. "regexp",
  10403. "operator",
  10404. ],
  10405. tokenModifiers: [
  10406. "declaration",
  10407. "definition",
  10408. "readonly",
  10409. "static",
  10410. "deprecated",
  10411. "abstract",
  10412. "async",
  10413. "modification",
  10414. "documentation",
  10415. "defaultLibrary",
  10416. ],
  10417. formats: ["relative"],
  10418. requests: {
  10419. range: true,
  10420. full: {
  10421. delta: true,
  10422. },
  10423. },
  10424. multilineTokenSupport: false,
  10425. overlappingTokenSupport: false,
  10426. },
  10427. callHierarchy: {
  10428. dynamicRegistration: true,
  10429. },
  10430. },
  10431. window: {
  10432. showMessage: {
  10433. messageActionItem: {
  10434. additionalPropertiesSupport: true,
  10435. },
  10436. },
  10437. showDocument: {
  10438. support: true,
  10439. },
  10440. workDoneProgress: true,
  10441. },
  10442. general: {
  10443. regularExpressions: {
  10444. engine: "ECMAScript",
  10445. version: "ES2020",
  10446. },
  10447. markdown: {
  10448. parser: "marked",
  10449. version: "1.1.0",
  10450. },
  10451. },
  10452. };
  10453.  
  10454. const initializeRequest = {
  10455. id: id++,
  10456. jsonrpc: "2.0",
  10457. method: "initialize",
  10458. params: {
  10459. processId: null,
  10460. clientInfo: {
  10461. name: "CFMonaco" + InstanceID,
  10462. },
  10463. locale: "zh-CN",
  10464. rootPath: null,
  10465. rootUri: null,
  10466. capabilities: capabilities,
  10467. trace: "off",
  10468. workspaceFolders: [
  10469. {
  10470. uri:
  10471. "file:///" + OJBetter.monaco.lsp.workUri + workspace,
  10472. name:
  10473. "file:///" + OJBetter.monaco.lsp.workUri + workspace,
  10474. },
  10475. ],
  10476. },
  10477. };
  10478. languageSocket.send(JSON.stringify(initializeRequest));
  10479.  
  10480. // 打开文档函数
  10481. OJBetter_monaco.openDocRequest = function () {
  10482. const initializ = {
  10483. jsonrpc: "2.0",
  10484. method: "initialized",
  10485. params: {},
  10486. };
  10487. languageSocket.send(JSON.stringify(initializ));
  10488. const openDocRequest = {
  10489. jsonrpc: "2.0",
  10490. method: "textDocument/didOpen",
  10491. params: {
  10492. textDocument: {
  10493. uri: model.uri.toString(),
  10494. languageId: language,
  10495. version: model.getVersionId(),
  10496. text: model.getValue(),
  10497. },
  10498. },
  10499. };
  10500. languageSocket.send(JSON.stringify(openDocRequest));
  10501. initialized = true; // 初始化完成,这里确认逻辑待完善
  10502. };
  10503.  
  10504. // 初始化更新文件
  10505. updateFile(workspace, filename, fileExtension, model.getValue());
  10506. }
  10507.  
  10508. /**
  10509. * 注册语言及功能
  10510. */
  10511. OJBetter_monaco.RegistrationAfterInit = () => {
  10512. // 注册语言
  10513. monaco.languages.register({ id: language });
  10514.  
  10515. // 注册"Command"
  10516. (function registerCommand() {
  10517. serverInfo.capabilities.executeCommandProvider.commands.forEach(
  10518. (item) => {
  10519. pushLSPLogMessage("info", `${i18next.t('lsp.server.regist', { ns: 'logMessage' })}`, item);
  10520. monaco.editor.registerCommand(item, (accessor, ...args) => {
  10521. sendData({
  10522. jsonrpc: "2.0",
  10523. id: id++,
  10524. method: "workspace/executeCommand",
  10525. params: {
  10526. command: item,
  10527. arguments: args,
  10528. },
  10529. });
  10530. });
  10531. }
  10532. );
  10533. })();
  10534.  
  10535. // 注册"增量更新"
  10536. model.onDidChangeContent((event) => {
  10537. updateFile(workspace, filename, fileExtension, model.getValue()); // 更新文件
  10538. const changeDocRequest = {
  10539. jsonrpc: "2.0",
  10540. method: "textDocument/didChange",
  10541. params: {
  10542. textDocument: {
  10543. uri: model.uri.toString(),
  10544. version: model.getVersionId(),
  10545. },
  10546. contentChanges: event.changes.map((change) => ({
  10547. range: OJBetter_monaco.MonacoRangeTolspRange(change.range),
  10548. rangeLength: change.rangeLength,
  10549. text: change.text,
  10550. })),
  10551. },
  10552. };
  10553. sendData(changeDocRequest);
  10554. });
  10555.  
  10556. //注册"自动补全"
  10557. monaco.languages.registerCompletionItemProvider(language, {
  10558. provideCompletionItems: (model, position, context) => {
  10559. const request = {
  10560. jsonrpc: "2.0",
  10561. id: id++,
  10562. method: "textDocument/completion",
  10563. params: {
  10564. textDocument: {
  10565. uri: model.uri.toString(),
  10566. },
  10567. position: OJBetter_monaco.MonacoPositionTolspPosition(position),
  10568. context: {
  10569. triggerKind: context.triggerKind + 1, // 这里要+1,两边的定义不一样。。。
  10570. triggerCharacter: context.triggerCharacter,
  10571. },
  10572. },
  10573. };
  10574. return new Promise((resolve, reject) => {
  10575. fetchData(request, (response) => {
  10576. const result = response.result;
  10577. pushLSPLogMessage("info", `completion ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10578. if (!result) return resolve(null);
  10579. const CompletionItems = {
  10580. suggestions: result.items.map(
  10581. ({
  10582. label,
  10583. kind,
  10584. filterText,
  10585. insertText,
  10586. insertTextFormat,
  10587. sortText,
  10588. textEdit,
  10589. documentation,
  10590. additionalTextEdits,
  10591. }) => ({
  10592. additionalTextEdits: additionalTextEdits
  10593. ? additionalTextEdits.map(({ newText, range }) => ({
  10594. text: newText,
  10595. range: OJBetter_monaco.lspRangeToMonacoRange(range),
  10596. }))
  10597. : [],
  10598. documentation: documentation ? documentation.value : "",
  10599. filterText,
  10600. insertText: insertText ? insertText : textEdit.newText,
  10601. insertTextRules:
  10602. insertTextFormat === 2
  10603. ? monaco.languages.CompletionItemInsertTextRule
  10604. .InsertAsSnippet
  10605. : monaco.languages.CompletionItemInsertTextRule
  10606. .KeepWhitespace,
  10607. kind,
  10608. label,
  10609. sortText,
  10610. range: textEdit
  10611. ? textEdit.range
  10612. ? OJBetter_monaco.lspRangeToMonacoRange(textEdit.range)
  10613. : OJBetter_monaco.lspRangeToMonacoRange(textEdit.insert)
  10614. : null,
  10615. })
  10616. ),
  10617. };
  10618. pushLSPLogMessage("info", `completion ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, CompletionItems);
  10619. resolve(CompletionItems);
  10620. });
  10621. });
  10622. },
  10623. });
  10624.  
  10625. // 注册"代码修复"
  10626. monaco.languages.registerCodeActionProvider(language, {
  10627. provideCodeActions: (model, range, context) => {
  10628. const request = {
  10629. id: id++,
  10630. jsonrpc: "2.0",
  10631. method: "textDocument/codeAction",
  10632. params: {
  10633. textDocument: {
  10634. uri: model.uri.toString(),
  10635. },
  10636. range: OJBetter_monaco.MonacoRangeTolspRange(range),
  10637. context: {
  10638. diagnostics: context.markers.map((item) => ({
  10639. range: OJBetter_monaco.MonacoRangeTolspRange({
  10640. startLineNumber: item.startLineNumber,
  10641. startColumn: item.startColumn,
  10642. endLineNumber: item.endLineNumber,
  10643. endColumn: item.endColumn,
  10644. }),
  10645. severity: OJBetter_monaco.MonacoSeverityTolspSeverity(
  10646. item.severity
  10647. ),
  10648. code: item.code,
  10649. source: item.source,
  10650. message: item.message,
  10651. tags: item.tags,
  10652. relatedInformation: item.relatedInformation
  10653. ? item.relatedInformation.map((item) => ({
  10654. location: {
  10655. uri: item.resource.toString(),
  10656. range: OJBetter_monaco.MonacoRangeTolspRange({
  10657. startLineNumber: item.startLineNumber,
  10658. startColumn: item.startColumn,
  10659. endLineNumber: item.endLineNumber,
  10660. endColumn: item.endColumn,
  10661. }),
  10662. },
  10663. message: item.message,
  10664. }))
  10665. : null,
  10666. })),
  10667. only: context.only ? [context.only] : [],
  10668. triggerKind: context.trigger,
  10669. },
  10670. },
  10671. };
  10672.  
  10673. return new Promise((resolve, reject) => {
  10674. fetchData(request, (response) => {
  10675. const result = response.result;
  10676. pushLSPLogMessage("info", `codeAction ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10677. if (!result) return resolve(null);
  10678. const codeAction = {
  10679. actions: result.map((item) => ({
  10680. title: item.title,
  10681. kind: item.kind ? item.kind : "quickfix",
  10682. command: item.command
  10683. ? item.command.command
  10684. ? {
  10685. id: item.command.command,
  10686. arguments: item.command.arguments,
  10687. title: item.command.title,
  10688. }
  10689. : null
  10690. : null,
  10691. diagnostics: item.diagnostics
  10692. ? item.diagnostics.map((item) => ({
  10693. code: item.code,
  10694. message: item.message,
  10695. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  10696. severity: OJBetter_monaco.lspSeverityToMonacoSeverity(
  10697. item.severity
  10698. ),
  10699. source: item.source,
  10700. }))
  10701. : null,
  10702. edit: item.edit
  10703. ? OJBetter_monaco.lspEditToMonacoEdit(item.edit)
  10704. : item.arguments
  10705. ? {
  10706. edits: item.arguments.flatMap(
  10707. (item1) => OJBetter_monaco.lspEditToMonacoEdit(item1).edits
  10708. ),
  10709. }
  10710. : null,
  10711. })),
  10712. dispose: () => { },
  10713. };
  10714. pushLSPLogMessage("info", `codeAction ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, codeAction);
  10715.  
  10716. resolve(codeAction);
  10717. });
  10718. });
  10719. },
  10720. });
  10721.  
  10722. // 注册"hover提示"
  10723. monaco.languages.registerHoverProvider(language, {
  10724. provideHover: (model, position) => {
  10725. const request = {
  10726. jsonrpc: "2.0",
  10727. id: id++,
  10728. method: "textDocument/hover",
  10729. params: {
  10730. textDocument: {
  10731. uri: model.uri.toString(),
  10732. },
  10733. position: OJBetter_monaco.MonacoPositionTolspPosition(position),
  10734. },
  10735. };
  10736.  
  10737. return new Promise((resolve, reject) => {
  10738. fetchData(request, (response) => {
  10739. pushLSPLogMessage("info", `Hover ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10740. const result = response.result;
  10741.  
  10742. if (!result) return resolve(null);
  10743. const Hover = {
  10744. range: result.range
  10745. ? OJBetter_monaco.lspRangeToMonacoRange(result.range)
  10746. : new monaco.Range(
  10747. position.lineNumber,
  10748. position.column,
  10749. position.lineNumber,
  10750. position.column
  10751. ),
  10752. contents: Array.isArray(result.contents)
  10753. ? result.contents.map((item) => ({
  10754. value: item.value ? item.value : item,
  10755. }))
  10756. : [
  10757. {
  10758. value: result.contents.value,
  10759. },
  10760. ],
  10761. };
  10762. pushLSPLogMessage("info", `Hover ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, Hover);
  10763. resolve(Hover);
  10764. });
  10765. });
  10766. },
  10767. });
  10768.  
  10769. // 注册"inlay提示"
  10770. if (language == "cpp" || language == "java")
  10771. monaco.languages.registerInlayHintsProvider(language, {
  10772. provideInlayHints: (model, range, token) => {
  10773. return new Promise((resolve, reject) => {
  10774. const request = {
  10775. jsonrpc: "2.0",
  10776. id: id++,
  10777. method: "textDocument/inlayHint",
  10778. params: {
  10779. textDocument: {
  10780. uri: model.uri.toString(),
  10781. },
  10782. range: OJBetter_monaco.MonacoRangeTolspRange(range),
  10783. },
  10784. };
  10785.  
  10786. fetchData(request, (response) => {
  10787. const result = response.result;
  10788. pushLSPLogMessage("info", `Inlay Hints ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10789.  
  10790. if (!result) return resolve(null);
  10791.  
  10792. const inlayHints = {
  10793. hints: result.map((item) => {
  10794. return {
  10795. kind: item.kind,
  10796. label: item.label,
  10797. paddingLeft: item.paddingLeft,
  10798. paddingRight: item.paddingRight,
  10799. position: {
  10800. lineNumber: item.position.line + 1,
  10801. column: item.position.character + 1,
  10802. },
  10803. };
  10804. }),
  10805. };
  10806. pushLSPLogMessage("info", `Inlay Hints ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, inlayHints);
  10807.  
  10808. resolve(inlayHints);
  10809. });
  10810. });
  10811. },
  10812. });
  10813.  
  10814. // 注册"转到定义"
  10815. monaco.languages.registerDefinitionProvider(language, {
  10816. provideDefinition: (model, position) => {
  10817. const request = {
  10818. jsonrpc: "2.0",
  10819. id: id++,
  10820. method: "textDocument/definition",
  10821. params: {
  10822. textDocument: {
  10823. uri: model.uri.toString(),
  10824. },
  10825. position: OJBetter_monaco.MonacoPositionTolspPosition(position),
  10826. },
  10827. };
  10828.  
  10829. return new Promise((resolve, reject) => {
  10830. fetchData(request, (response) => {
  10831. const result = response.result;
  10832. pushLSPLogMessage("info", `definition ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10833.  
  10834. if (result.length == 0) return resolve(null);
  10835. const definition = result.map((item) => ({
  10836. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  10837. uri: monaco.Uri.parse(item.uri), //
  10838. }));
  10839. pushLSPLogMessage("info", `definition ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, definition);
  10840.  
  10841. resolve(definition);
  10842. });
  10843. });
  10844.  
  10845. return null; // 如果没有内容,则返回null
  10846. },
  10847. });
  10848.  
  10849. // 注册"转到引用"
  10850. monaco.languages.registerReferenceProvider(language, {
  10851. provideReferences: (model, position, context) => {
  10852. const request = {
  10853. jsonrpc: "2.0",
  10854. id: id++,
  10855. method: "textDocument/references",
  10856. params: {
  10857. context: context,
  10858. textDocument: {
  10859. uri: model.uri.toString(),
  10860. },
  10861. position: OJBetter_monaco.MonacoPositionTolspPosition(position),
  10862. },
  10863. };
  10864.  
  10865. return new Promise((resolve, reject) => {
  10866. fetchData(request, (response) => {
  10867. const result = response.result;
  10868. pushLSPLogMessage("info", `references ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10869.  
  10870. if (result.length == 0) return resolve([]);
  10871.  
  10872. const references = result.map((item) => ({
  10873. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  10874. uri: monaco.Uri.parse(item.uri), //
  10875. }));
  10876. pushLSPLogMessage("info", `references ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, references);
  10877. resolve(references);
  10878. });
  10879. });
  10880. return []; // 如果没有内容,则返回空数组
  10881. },
  10882. });
  10883.  
  10884. // 注册"符号引用点击高亮"
  10885. monaco.languages.registerDocumentHighlightProvider(language, {
  10886. provideDocumentHighlights: (model, position) => {
  10887. const request = {
  10888. jsonrpc: "2.0",
  10889. id: id++,
  10890. method: "textDocument/documentHighlight",
  10891. params: {
  10892. textDocument: {
  10893. uri: model.uri.toString(),
  10894. },
  10895. position: OJBetter_monaco.MonacoPositionTolspPosition(position),
  10896. },
  10897. };
  10898.  
  10899. return new Promise((resolve, reject) => {
  10900. fetchData(request, (response) => {
  10901. const result = response.result;
  10902. pushLSPLogMessage("info", `documentHighlight ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10903.  
  10904. if (!result || result.length == 0) return resolve([]);
  10905. const highlights = result.map((item) => ({
  10906. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  10907. kind: item.kind,
  10908. }));
  10909. pushLSPLogMessage("info",
  10910. `documentHighlight ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`,
  10911. highlights
  10912. );
  10913.  
  10914. resolve(highlights);
  10915. });
  10916. });
  10917. return []; // 如果没有内容,则返回空数组
  10918. },
  10919. });
  10920.  
  10921. // 注册"文件链接"
  10922. if (language == "cpp" || language == "java")
  10923. monaco.languages.registerLinkProvider(language, {
  10924. provideLinks: (model) => {
  10925. const request = {
  10926. jsonrpc: "2.0",
  10927. id: id++,
  10928. method: "textDocument/documentLink",
  10929. params: {
  10930. textDocument: {
  10931. uri: model.uri.toString(),
  10932. },
  10933. },
  10934. };
  10935.  
  10936. return new Promise((resolve, reject) => {
  10937. fetchData(request, (response) => {
  10938. const result = response.result;
  10939. pushLSPLogMessage("info", `DocumentLink ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10940.  
  10941. if (!result) return resolve(null);
  10942. const links = {
  10943. links: result.map((item) => ({
  10944. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  10945. url: item.target.toString(),
  10946. tooltip: item.tooltip ? item.tooltip : null,
  10947. })),
  10948. };
  10949. pushLSPLogMessage("info", `DocumentLink ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, links);
  10950. resolve(links);
  10951. });
  10952. });
  10953. },
  10954. });
  10955.  
  10956. // 注册"格式化"
  10957. monaco.languages.registerDocumentFormattingEditProvider(language, {
  10958. provideDocumentFormattingEdits: (model, options, token) => {
  10959. const request = {
  10960. jsonrpc: "2.0",
  10961. id: id++,
  10962. method: "textDocument/formatting",
  10963. params: {
  10964. textDocument: {
  10965. uri: model.uri.toString(),
  10966. },
  10967. options: options,
  10968. },
  10969. };
  10970.  
  10971. return new Promise((resolve, reject) => {
  10972. fetchData(request, (response) => {
  10973. const result = response.result;
  10974. pushLSPLogMessage("info", `formatting ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10975.  
  10976. const TextEdit = result.map((edit) => ({
  10977. range: OJBetter_monaco.lspRangeToMonacoRange(edit.range),
  10978. text: edit.newText,
  10979. }));
  10980. pushLSPLogMessage("info", `formatting ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, TextEdit);
  10981. resolve(TextEdit);
  10982. });
  10983. });
  10984. },
  10985. });
  10986.  
  10987. // 注册"部分格式化"
  10988. monaco.languages.registerDocumentRangeFormattingEditProvider(language, {
  10989. provideDocumentRangeFormattingEdits: (model, range, options) => {
  10990. const request = {
  10991. jsonrpc: "2.0",
  10992. id: id++,
  10993. method: "textDocument/rangeFormatting",
  10994. params: {
  10995. textDocument: {
  10996. uri: model.uri.toString(),
  10997. },
  10998. range: OJBetter_monaco.MonacoRangeTolspRange(range),
  10999. options,
  11000. },
  11001. };
  11002.  
  11003. return new Promise((resolve, reject) => {
  11004. fetchData(request, (response) => {
  11005. const result = response.result;
  11006. pushLSPLogMessage("info", `rangeFormatting ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  11007.  
  11008. if (!result || result.length == 0) return resolve([]);
  11009. const edits = result.map((item) => ({
  11010. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  11011. text: item.newText,
  11012. }));
  11013. pushLSPLogMessage("info", `rangeFormatting ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, edits);
  11014. resolve(edits);
  11015. });
  11016. });
  11017. },
  11018. });
  11019.  
  11020. // 注册"重命名"
  11021. monaco.languages.registerRenameProvider(language, {
  11022. provideRenameEdits: (model, position, newName, token) => {
  11023. const request = {
  11024. jsonrpc: "2.0",
  11025. id: id++,
  11026. method: "textDocument/rename",
  11027. params: {
  11028. textDocument: {
  11029. uri: model.uri.toString(),
  11030. },
  11031. position: OJBetter_monaco.MonacoPositionTolspPosition(position),
  11032. newName: newName,
  11033. },
  11034. };
  11035.  
  11036. return new Promise((resolve, reject) => {
  11037. fetchData(request, (response) => {
  11038. const result = response.result;
  11039. pushLSPLogMessage("info", `rename ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  11040.  
  11041. const rename = OJBetter_monaco.lspEditToMonacoEdit(result);
  11042. pushLSPLogMessage("info", `rename ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, rename);
  11043. resolve(rename);
  11044. });
  11045. });
  11046. },
  11047. });
  11048.  
  11049. // 注册"折叠范围分析"
  11050. monaco.languages.registerFoldingRangeProvider(language, {
  11051. provideFoldingRanges: (model) => {
  11052. const request = {
  11053. jsonrpc: "2.0",
  11054. id: id++,
  11055. method: "textDocument/foldingRange",
  11056. params: {
  11057. textDocument: {
  11058. uri: model.uri.toString(),
  11059. },
  11060. },
  11061. };
  11062.  
  11063. return new Promise((resolve, reject) => {
  11064. fetchData(request, (response) => {
  11065. const result = response.result;
  11066. pushLSPLogMessage("info", `FoldingRange ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  11067.  
  11068. if (!result) return resolve([]);
  11069. const foldingRanges = result.map((item) => ({
  11070. start: item.startLine + 1,
  11071. end: item.endLine + 1,
  11072. kind: monaco.languages.FoldingRangeKind.fromValue(item.kind),
  11073. }));
  11074. pushLSPLogMessage("info", `FoldingRange ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, foldingRanges);
  11075. resolve(foldingRanges);
  11076. });
  11077. });
  11078. },
  11079. });
  11080.  
  11081. // 注册"方法签名提示"
  11082. monaco.languages.registerSignatureHelpProvider(language, {
  11083. signatureHelpTriggerCharacters:
  11084. serverInfo.capabilities.signatureHelpProvider.triggerCharacters,
  11085. provideSignatureHelp: (model, position, token, context) => {
  11086. const request = {
  11087. jsonrpc: "2.0",
  11088. id: id++,
  11089. method: "textDocument/signatureHelp",
  11090. params: {
  11091. textDocument: {
  11092. uri: model.uri.toString(),
  11093. },
  11094. position: {
  11095. line: position.lineNumber - 1,
  11096. character: position.column - 1,
  11097. },
  11098. context: {
  11099. triggerKind: context.triggerKind,
  11100. triggerCharacter: context.triggerCharacter,
  11101. isRetrigger: context.isRetrigger,
  11102. activeSignatureHelp: context.activeSignatureHelp,
  11103. },
  11104. },
  11105. };
  11106.  
  11107. return new Promise((resolve, reject) => {
  11108. fetchData(request, (response) => {
  11109. const result = response.result;
  11110.  
  11111. pushLSPLogMessage("info", `signatureHelp ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  11112.  
  11113. if (!result) return resolve(null);
  11114. const SignatureHelpResult = {
  11115. value: {
  11116. activeParameter: result.activeParameter,
  11117. activeSignature: result.activeSignature,
  11118. signatures: result.signatures,
  11119. },
  11120. dispose: () => { },
  11121. };
  11122.  
  11123. pushLSPLogMessage("info",
  11124. `signatureHelp ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`,
  11125. SignatureHelpResult
  11126. );
  11127. resolve(SignatureHelpResult);
  11128. });
  11129. });
  11130. },
  11131. });
  11132.  
  11133. // 注册"渐进式自动格式化" 如果server有这个
  11134. if (serverInfo.capabilities.documentOnTypeFormattingProvider)
  11135. monaco.languages.registerOnTypeFormattingEditProvider(language, {
  11136. autoFormatTriggerCharacters: [
  11137. serverInfo.capabilities.documentOnTypeFormattingProvider
  11138. .firstTriggerCharacter,
  11139. ],
  11140. provideOnTypeFormattingEdits: (model, position, ch, options) => {
  11141. const request = {
  11142. jsonrpc: "2.0",
  11143. id: id++,
  11144. method: "textDocument/onTypeFormatting",
  11145. params: {
  11146. textDocument: {
  11147. uri: model.uri.toString(),
  11148. },
  11149. position: OJBetter_monaco.MonacoPositionTolspPosition(position),
  11150. ch,
  11151. options,
  11152. },
  11153. };
  11154.  
  11155. return new Promise((resolve, reject) => {
  11156. fetchData(request, (response) => {
  11157. const result = response.result;
  11158. pushLSPLogMessage("info", `onTypeFormatting ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  11159.  
  11160. if (!result || result.length == 0) return resolve([]);
  11161.  
  11162. const edits = result.map((item) => ({
  11163. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  11164. text: item.newText,
  11165. }));
  11166. pushLSPLogMessage("info", `onTypeFormatting ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, edits);
  11167. resolve(edits);
  11168. });
  11169. });
  11170. },
  11171. });
  11172. };
  11173.  
  11174. /**
  11175. * 被动式接收处理
  11176. */
  11177. OJBetter_monaco.PassiveReceiveHandler = () => {
  11178.  
  11179. // "实时代码诊断"
  11180. OJBetter_monaco.updateMarkers = function (message) {
  11181. const params = message.params;
  11182. pushLSPLogMessage("info", `Markers ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, message);
  11183.  
  11184. if (!params) return;
  11185. const markers = params.diagnostics.map((item1) => ({
  11186. code: item1.code,
  11187. message: item1.message,
  11188. ...OJBetter_monaco.lspRangeToMonacoRange(item1.range),
  11189. relatedInformation: item1.relatedInformation
  11190. ? item1.relatedInformation.map((item2) => ({
  11191. ...(item2.location.range
  11192. ? OJBetter_monaco.lspRangeToMonacoRange(item2.location.range)
  11193. : OJBetter_monaco.lspRangeToMonacoRange(item2.location)),
  11194. message: item2.message,
  11195. resource: monaco.Uri.parse(item2.location.uri),
  11196. }))
  11197. : null,
  11198. severity: OJBetter_monaco.lspSeverityToMonacoSeverity(item1.severity),
  11199. source: item1.source,
  11200. }));
  11201.  
  11202. pushLSPLogMessage("info", `Markers ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, markers);
  11203. monaco.editor.setModelMarkers(model, "eslint", markers);
  11204.  
  11205. // 更新状态底栏信息
  11206. const nowMarks = monaco.editor.getModelMarkers();
  11207. warningCount = 0;
  11208. errorCount = 0;
  11209. for (const marker of nowMarks) {
  11210. if (marker.severity === monaco.MarkerSeverity.Warning) {
  11211. warningCount++;
  11212. } else if (marker.severity === monaco.MarkerSeverity.Error) {
  11213. errorCount++;
  11214. }
  11215. }
  11216. $('#OJBetter_statusBar').text(`Warnings: ${warningCount}, Errors: ${errorCount}`);
  11217. };
  11218.  
  11219. // "应用服务器推送的更改"(代码修复)
  11220. OJBetter_monaco.applyEdit = function (message) {
  11221. const params = message.params;
  11222. pushLSPLogMessage("info", `applyEdit ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, message);
  11223.  
  11224. if (!params) return;
  11225. const operations = Object.values(params.edit.changes)
  11226. .flat()
  11227. .map((item) => ({
  11228. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  11229. text: item.newText,
  11230. }));
  11231.  
  11232. pushLSPLogMessage("info", `applyEdit ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, operations);
  11233. model.pushEditOperations([], operations, () => null); // 入栈编辑操作
  11234. };
  11235. }
  11236.  
  11237. if (!languageSocketState) await waitForLanguageSocketState();
  11238. OJBetter_monaco.Initialize();
  11239. }
  11240.  
  11241. // 语言更改
  11242. function changeMonacoLanguage(form) {
  11243. let nowSelect = form.selectLang.val();
  11244.  
  11245. // 这里是因为在Chrome上Select2会莫名其妙触发一次不会改变值的change事件,而在其他浏览器中没有,所以贴个补丁
  11246. if (nowSelect === OJBetter.monaco.nowLangSelect) return;
  11247. else OJBetter.monaco.nowLangSelect = nowSelect;
  11248.  
  11249. // 记忆更改
  11250. GM_setValue('compilerSelection', nowSelect);
  11251. // 销毁旧的编辑器
  11252. try {
  11253. if (OJBetter.monaco.editor) OJBetter.monaco.editor.dispose();
  11254. } catch (error) {
  11255. console.warn("Encountered an error while attempting to delete the old editor, but it should not affect your regular usage.", error)
  11256. }
  11257. // 关闭旧的socket
  11258. OJBetter.monaco.lsp.socket.forEach(socket => {
  11259. socket.close();
  11260. });
  11261. // 移除相关元素
  11262. form.topRightDiv.empty();
  11263. $('#LSPLog').remove();
  11264. $('#OJBetter_statusBar').remove();
  11265. // 创建新的编辑器
  11266. if (nowSelect in value_monacoLanguageMap) {
  11267. let language = value_monacoLanguageMap[nowSelect];
  11268. if (language == "python" || language == "cpp") {
  11269. createMonacoEditor(language, form, true);
  11270. } else {
  11271. createMonacoEditor(language, form, false);
  11272. }
  11273. } else {
  11274. createMonacoEditor(null, form, false);
  11275. }
  11276. // 更新在线编译器参数
  11277. changeCompilerArgs(nowSelect);
  11278. }
  11279.  
  11280. // 收集样例数据
  11281. function getTestData() {
  11282. let testData = {};
  11283.  
  11284. /**
  11285. * 从pre中获取文本信息
  11286. * @param {JQuery<HTMLElement>} node 元素
  11287. * @returns {string} 文本信息
  11288. */
  11289. function getTextFromPre(node) {
  11290. let text;
  11291. if (node.find("br").length > 0) {
  11292. text = node.html().replace(/<br>/g, "\n"); // <br>作换行符的情况
  11293. } else {
  11294. text = node.text();
  11295. }
  11296. return text;
  11297. }
  11298.  
  11299. // $('.input').each(function (index) {
  11300. // var inputText = '';
  11301. // if ($(this).find('pre').find('div').length > 0) {
  11302. // $(this).find('pre').find('div').each(function () {
  11303. // inputText += getTextFromPre($(this)) + '\n';
  11304. // });
  11305. // } else {
  11306. // inputText = getTextFromPre($(this).find('pre'));
  11307. // }
  11308. // var outputText = '';
  11309. // if ($('.output').eq(index).find('pre').find('div').length > 0) {
  11310. // $('.output').eq(index).find('pre').find('div').each(function () {
  11311. // inputText += getTextFromPre($(this)) + '\n';
  11312. // });
  11313. // } else {
  11314. // outputText = getTextFromPre($('.output').eq(index).find('pre'));
  11315. // }
  11316.  
  11317. // testData[index + 1] = {
  11318. // input: inputText.trim(),
  11319. // output: outputText.trim()
  11320. // };
  11321. // });
  11322.  
  11323. // 需要过滤重复的样例(因为有日文英文两个页面,样例元素重复了两遍)
  11324. let uniqueTestData = [];
  11325. const filteredPreElements = $('pre').clone().filter((index, element) => element.id.startsWith('pre-sample'));
  11326. for (let i = 0; i < filteredPreElements.length; i += 2) {
  11327. if (i + 1 < filteredPreElements.length) {
  11328. const inputElement = $(filteredPreElements[i]);
  11329. const outputElement = $(filteredPreElements[i + 1]);
  11330.  
  11331. const inputText = getTextFromPre(inputElement).trim();
  11332. const outputText = getTextFromPre(outputElement).trim();
  11333.  
  11334. // 检查是否已经存在相同的样例
  11335. let isDuplicate = uniqueTestData.some(testCase => testCase.input === inputText && testCase.output === outputText);
  11336. if (!isDuplicate) {
  11337. uniqueTestData.push({
  11338. input: inputText,
  11339. output: outputText
  11340. });
  11341. }
  11342. }
  11343. }
  11344.  
  11345. // 把唯一的测试数据赋值给testData,保持原有的索引风格
  11346. uniqueTestData.forEach((testCase, index) => {
  11347. testData[index + 1] = testCase;
  11348. });
  11349.  
  11350. return testData;
  11351. }
  11352.  
  11353. // 初始化自定义测试数据面板
  11354. function CustomTestInit() {
  11355. const url = window.location.href;
  11356.  
  11357. restoreText();
  11358.  
  11359. // 添加
  11360. $('#addCustomTest').click(function () {
  11361. var sampleDiv = $('<div class="sampleDiv">');
  11362. var inputTextarea = $('<p style="padding: 0px 5px;">input</p><textarea class="dynamicTextarea inputTextarea"></textarea>');
  11363. var outputTextarea = $('<p style="padding: 0px 5px;">output</p><textarea class="dynamicTextarea outputTextarea"></textarea>');
  11364. var deleteCustomTest = OJB_safeCreateJQElement(`<button type="button" class="deleteCustomTest">${closeIcon}</button>`);
  11365. sampleDiv.append(deleteCustomTest);
  11366. sampleDiv.append(inputTextarea);
  11367. sampleDiv.append(outputTextarea);
  11368. $('#customTests').append(sampleDiv);
  11369. });
  11370.  
  11371. // 实时保存文本内容到 IndexedDB 中
  11372. $(document).on('input', '.inputTextarea, .outputTextarea', function () {
  11373. OJBetter.common.database.transaction('rw', OJBetter.common.database.samplesData, function () {
  11374. var objectStore = OJBetter.common.database.samplesData;
  11375. var samples = {
  11376. url: url,
  11377. samples: []
  11378. };
  11379. var index = 0;
  11380. $('.sampleDiv').each(function () {
  11381. var $sampleDiv = $(this);
  11382. var inputTextarea = $sampleDiv.find('.inputTextarea');
  11383. var outputTextarea = $sampleDiv.find('.outputTextarea');
  11384. $sampleDiv.attr('data-index', index);
  11385. inputTextarea.attr('id', 'input' + index);
  11386. outputTextarea.attr('id', 'output' + index);
  11387. var sample = {
  11388. id: index,
  11389. input: inputTextarea.val(),
  11390. output: outputTextarea.val()
  11391. };
  11392. samples.samples.push(sample);
  11393. index++;
  11394. });
  11395. objectStore.put(samples);
  11396. });
  11397. });
  11398.  
  11399. // 删除
  11400. $(document).on('click', '.deleteCustomTest', function () {
  11401. var $sampleDiv = $(this).closest('.sampleDiv');
  11402. OJBetter.common.database.transaction('rw', OJBetter.common.database.samplesData, function () {
  11403. var objectStore = OJBetter.common.database.samplesData;
  11404. var index = parseInt($sampleDiv.attr('data-index'));
  11405. if (!isNaN(index)) {
  11406. objectStore.get(url).then(row => {
  11407. let samples = row.samples;
  11408. samples.splice(index, 1); // 移除第index个元素
  11409. objectStore.put({
  11410. url: url,
  11411. samples: samples
  11412. });
  11413. })
  11414. }
  11415. $sampleDiv.remove();
  11416. });
  11417. });
  11418.  
  11419. // 恢复保存的内容
  11420. function restoreText() {
  11421. OJBetter.common.database.transaction('r', OJBetter.common.database.samplesData, function () {
  11422. return OJBetter.common.database.samplesData.get(url);
  11423. }).then(function (data) {
  11424. if (data.samples && data.samples.length > 0) {
  11425. data.samples.forEach(function (item, index) {
  11426. var sampleDiv = $('<div class="sampleDiv">');
  11427. var inputTextarea = OJB_safeCreateJQElement(`<p style="padding: 0px 5px;">input</p><textarea id="input${index}" class="dynamicTextarea inputTextarea"></textarea>`);
  11428. var outputTextarea = OJB_safeCreateJQElement(`<p style="padding: 0px 5px;">output</p><textarea id="output${index}" class="dynamicTextarea outputTextarea"></textarea>`);
  11429. var deleteCustomTest = OJB_safeCreateJQElement(`<button type="button" class="deleteCustomTest">${closeIcon}</button>`);
  11430.  
  11431. inputTextarea.val(item.input);
  11432. outputTextarea.val(item.output);
  11433.  
  11434. sampleDiv.append(deleteCustomTest);
  11435. sampleDiv.append(inputTextarea);
  11436. sampleDiv.append(outputTextarea);
  11437. sampleDiv.attr('data-index', index)
  11438. $('#customTests').append(sampleDiv);
  11439. });
  11440. }
  11441. });
  11442. }
  11443. }
  11444.  
  11445. // 获取自定义测试数据
  11446. function getCustomTestData() {
  11447. const url = window.location.href;
  11448.  
  11449. return new Promise(function (resolve) {
  11450. var customTestData = {};
  11451. OJBetter.common.database.transaction('r', OJBetter.common.database.samplesData, function () {
  11452. return OJBetter.common.database.samplesData.get(url);
  11453. }).then(function (data) {
  11454. if (!data) resolve(customTestData);
  11455. if (data.samples && data.samples.length > 0) {
  11456. data.samples.forEach(function (item, index) {
  11457. customTestData[index + 1] = {
  11458. input: item.input,
  11459. output: item.output
  11460. };
  11461. });
  11462. }
  11463. resolve(customTestData);
  11464. });
  11465. });
  11466. }
  11467.  
  11468. // codeforces编译器参数列表
  11469. let officialLanguage = "";
  11470. function officialCompilerArgsChange(nowSelect) {
  11471. officialLanguage = nowSelect;
  11472. $('#CompilerArgsInput').prop("disabled", true);
  11473. }
  11474.  
  11475. // codeforces编译器通信
  11476. async function officialCompiler(code, input) {
  11477. // const data = new FormData();
  11478. // data.append('csrf_token', OJBetter.common.cf_csrf_token);
  11479. const data = new URLSearchParams();
  11480. data.append('csrf_token', OJBetter.common.at_csrf_token);
  11481. // data.append('source', code);
  11482. // data.append('tabSize', '4');
  11483. // data.append('programTypeId', officialLanguage);
  11484. data.append('data.LanguageId', officialLanguage);
  11485. data.append('input', input);
  11486. // data.append('output', '');
  11487. // data.append('communityCode', '');
  11488. // data.append('action', 'submitSourceCode');
  11489. // data.append('programTypeId', officialLanguage);
  11490. data.append('sourceCode', code);
  11491.  
  11492. const requestOptions = {
  11493. method: 'POST',
  11494. // url: `${OJBetter.common.hostAddress}/data/customtest`,
  11495. url: `${OJBetter.common.hostAddress}/contests/arc172/custom_test/submit/json`,
  11496. data: data,
  11497. headers: {
  11498. // 'X-Csrf-Token': OJBetter.common.cf_csrf_token
  11499. 'Content-Type': 'application/x-www-form-urlencoded'
  11500. }
  11501. };
  11502.  
  11503. const result = {
  11504. Errors: '',
  11505. Result: '',
  11506. Stats: ''
  11507. };
  11508.  
  11509. try {
  11510. const submitResponse = await OJB_GMRequest(requestOptions);
  11511. // if (submitResponse.status !== 200 || !submitResponse.response) {
  11512. // result.Errors = `${i18next.t('compiler.official.pushError', { ns: 'codeEditor' })}`;
  11513. // return result;
  11514. // }
  11515. if (submitResponse.status !== 200) {
  11516. result.Errors = `${i18next.t('compiler.official.pushError', { ns: 'codeEditor' })}`;
  11517. return result;
  11518. }
  11519.  
  11520. // const submitResult = JSON.parse(submitResponse.response);
  11521. // const customTestSubmitId = submitResult.customTestSubmitId;
  11522.  
  11523. const verdictResponse = await OJB_promiseRetryWrapper(
  11524. getOfficialCompilerVerdict,
  11525. {
  11526. maxRetries: 10,
  11527. retryInterval: 500
  11528. },
  11529. // customTestSubmitId
  11530. );
  11531. return verdictResponse;
  11532. } catch (error) {
  11533. result.Errors = error.message;
  11534. return result;
  11535. }
  11536. }
  11537.  
  11538. // 获取codeforces编译器的执行结果
  11539. // async function getOfficialCompilerVerdict(customTestSubmitId) {
  11540. async function getOfficialCompilerVerdict() {
  11541. // const newdata = new FormData();
  11542. // newdata.append('csrf_token', OJBetter.common.cf_csrf_token);
  11543. // newdata.append('action', 'getVerdict');
  11544. // newdata.append('customTestSubmitId', customTestSubmitId);
  11545.  
  11546. // const requestOptions = {
  11547. // method: 'POST',
  11548. // url: `${OJBetter.common.hostAddress}/data/customtest`,
  11549. // data: newdata,
  11550. // headers: {
  11551. // 'X-Csrf-Token': OJBetter.common.cf_csrf_token
  11552. // }
  11553. // };
  11554. const requestOptions = {
  11555. method: 'GET',
  11556. url: `https://atcoder.jp/contests/arc172/custom_test/json?reload=true`,
  11557. };
  11558.  
  11559. const responseDetails = await OJB_GMRequest(requestOptions);
  11560. if (responseDetails.status !== 200 || !responseDetails.response) {
  11561. throw new Error(`${i18next.t('compiler.official.getResultError', { ns: 'codeEditor' })}`);
  11562. }
  11563.  
  11564. const response = JSON.parse(responseDetails.response);
  11565. // if (!response.stat) {
  11566. // throw new Error('Verdict not ready, retrying...');
  11567. // }
  11568. if (response.Interval) {
  11569. throw new Error('Verdict not ready, retrying...');
  11570. }
  11571.  
  11572. // return {
  11573. // Errors: response.verdict === "OK" ? null : response.verdict + '<br>' + response.output,
  11574. // Result: response.output.replace(/\r\n/g, "\n"),
  11575. // Stats: `Status: ${response.stat}`
  11576. // };
  11577. return {
  11578. Errors: response.Result.ExitCode === "0" ? null : response.Stderr,
  11579. Result: response.Stdout.replace(/\r\n/g, "\n"),
  11580. Stats: `Status: ExitCode: ${response.Result.ExitCode} Exec Time: ${response.Result.TimeConsumption} ms Memory: ${response.Result.MemoryConsumption} KB`
  11581. };
  11582. }
  11583.  
  11584. // rextester编译器参数列表
  11585. let rextesterLanguage = "";
  11586. function rextesterCompilerArgsChange(nowSelect) {
  11587. // let LanguageChoiceList = {
  11588. // "4": "9", "6": "8", "7": "5", "9": "1", "13": "13", "19": "42", "20": "21", "28": "30", "31": "24", "32": "20",
  11589. // "34": "17", "36": "4", "43": "6", "45": "7", "46": "4", "50": "7", "51": "9", "52": "27", "54": "7", "55": "23", "60": "4",
  11590. // "61": "7", "65": "1", "67": "12", "70": "5", "73": "7", "74": "4", "75": "46", "77": "43", "79": "1", "80": "27", "83": "43", "87": "4"
  11591. // }
  11592. let LanguageChoiceList = {
  11593. "5001": "7", "5002": "20", "5003": "1", "5005": "4", "5009": "17", "5016": "8", "5037": "13", "5041": "9",
  11594. "5047": "21", "5055": "5", "5058": "17", "5063": "5", "5078": "5", "5082": "5"
  11595. }
  11596.  
  11597. let CompilerArgsList = {
  11598. "6": "-Wall -std=gnu99 -O2 -o a.out source_file.c",
  11599. "7": "-Wall -std=c++14 -O2 -o a.out source_file.cpp",
  11600. "20": "-o a.out source_file.go",
  11601. "27": "-Wall -std=c++14 -stdlib=libc++ -O2 -o a.out source_file.cpp",
  11602. "30": "source_file.d -ofa.out"
  11603. }
  11604. if (nowSelect in LanguageChoiceList) {
  11605. $('#RunTestButton').prop("disabled", false);
  11606. rextesterLanguage = LanguageChoiceList[nowSelect];
  11607. } else {
  11608. $('#RunTestButton').prop("disabled", true);
  11609. }
  11610. if (rextesterLanguage in CompilerArgsList) {
  11611. const rextesterCompilerArgs = CompilerArgsList[rextesterLanguage];
  11612. $('#CompilerArgsInput').val(rextesterCompilerArgs);
  11613. } else {
  11614. $('#CompilerArgsInput').val("");
  11615. }
  11616. }
  11617.  
  11618. // rextester编译器通信
  11619. async function rextesterCompiler(code, input) {
  11620. try {
  11621. const result = await OJB_promiseRetryWrapper(rextesterCompilerRequest, {
  11622. maxRetries: 5,
  11623. retryInterval: 500,
  11624. errorHandler: (err) => ({ Errors: err.message, Result: '', Stats: '' })
  11625. }, code, input);
  11626. return result;
  11627. } catch (error) {
  11628. return { Errors: error.message, Result: '', Stats: '' };
  11629. }
  11630. }
  11631.  
  11632. // rextester编译器请求方法
  11633. async function rextesterCompilerRequest(code, input) {
  11634. const data = new FormData();
  11635. data.append('LanguageChoiceWrapper', rextesterLanguage);
  11636. data.append('EditorChoiceWrapper', '1');
  11637. data.append('LayoutChoiceWrapper', '1');
  11638. data.append('Program', code);
  11639. data.append('CompilerArgs', $('#CompilerArgsInput').val());
  11640. data.append('Input', input);
  11641. data.append('ShowWarnings', 'false');
  11642. data.append('IsInEditMode', 'false');
  11643. data.append('IsLive', 'false');
  11644.  
  11645. const responseDetails = await OJB_GMRequest({
  11646. method: 'POST',
  11647. url: 'https://rextester.com/rundotnet/Run',
  11648. data: data
  11649. });
  11650.  
  11651. if (responseDetails.status !== 200 || !responseDetails.response) {
  11652. throw new Error(`${i18next.t('compiler.common.error', { ns: 'codeEditor' })}`);
  11653. }
  11654.  
  11655. const response = JSON.parse(responseDetails.response);
  11656. return {
  11657. Errors: response.Errors || '',
  11658. Result: response.Result || '',
  11659. Stats: response.Stats || ''
  11660. };
  11661. }
  11662.  
  11663. // wandbox编译器参数列表
  11664. var wandboxlist = JSON.parse(GM_getResourceText("wandboxlist"));
  11665. function wandboxCompilerArgsChange(nowSelect) {
  11666. // let LanguageChoiceList = {
  11667. // "6": "PHP", "7": "Python", "9": "C#", "12": "Haskell", "13": "Perl", "19": "OCaml",
  11668. // "20": "Scala", "28": "D", "31": "Python", "32": "Go", "34": "JavaScript", "36": "Java", "40": "Python", "41": "Python",
  11669. // "43": "C++", "50": "C++", "51": "Pascal", "52": "C++", "54": "C++", "60": "Java", "61": "C++", "65": "C#", "67": "Ruby",
  11670. // "70": "Python", "73": "C++", "74": "Java", "75": "Rust", "79": "C#", "80": "C++", "87": "Java"
  11671. // }
  11672. let LanguageChoiceList = {
  11673. "5001": "C++", "5002": "Go", "5003": "C#", "5005": "Java", "5009": "JavaScript", "5010": "JavaScript",
  11674. "5012": "D", "5013": "D", "5016": "PHP", "5017": "C++", "5018": "Ruby", "5025": "Haskell",
  11675. "5027": "Lua", "5028": "C++", "5031": "C++", "5037": "Perl", "5041": "Pascal", "5042": "C#",
  11676. "5043": "Lua", "5047": "Scala", "5055": "Python", "5056": "Scala", "5059": "OCaml", "5062": "Lisp",
  11677. "5063": "Python", "5077": "D", "5078": "Python", "5081": "OCaml", "5082": "Python"
  11678. }
  11679.  
  11680. // 移除旧的
  11681. $('#CompilerChange').remove();
  11682.  
  11683. if (nowSelect in LanguageChoiceList) {
  11684. $('#RunTestButton').prop("disabled", false);
  11685. const Languagefiltered = wandboxlist.filter(obj => obj.language === LanguageChoiceList[nowSelect]);
  11686.  
  11687. // 创建编译器下拉框
  11688. let CompilerChange = $('<select id="CompilerChange" style="width: 100%;"></select>');
  11689.  
  11690. $('#CompilerSetting').show().append(CompilerChange);
  11691. for (let i = 0; i < Languagefiltered.length; i++) {
  11692. let Compiler = Languagefiltered[i];
  11693. let op = $("<option></option>")
  11694. .val(Compiler.name)
  11695. .text(Compiler["display-name"] + " " + Compiler.version);
  11696. $("#CompilerChange").append(op);
  11697. }
  11698.  
  11699. // 编译器参数刷新
  11700. function refreshCompilerArgs() {
  11701. var flags = '';
  11702. $("#CompilerBox").find("*").each(function () {
  11703. if ($(this).is("input[type='checkbox']")) {
  11704. let flag = $(this).prop("checked") ? $(this).val() : '';
  11705. flags += flag + (flag ? ' ' : '');
  11706. } else if ($(this).is("select") || $(this).is("input") || $(this).is("textarea")) {
  11707. let flag = $(this).val();
  11708. flags += flag + (flag ? ' ' : '');
  11709. }
  11710. });
  11711. $("#CompilerArgsInput").val(flags);
  11712. $("#CompilerArgsInput").prop("readonly", true); // 只读
  11713. }
  11714.  
  11715. // 编译器切换监听
  11716. CompilerChange.change(function () {
  11717. let selectedName = CompilerChange.val();
  11718. let Compiler = Languagefiltered.find(
  11719. (obj) => obj.name === selectedName
  11720. );
  11721.  
  11722. $("#CompilerArgsInput").val(); // 初始化编译器输入框
  11723.  
  11724. $("#CompilerBox").remove();
  11725. let div = $("<div id='CompilerBox'></div>");
  11726.  
  11727. let display_compile_command = OJB_safeCreateJQElement(`<input id='${Compiler.name}' value='${Compiler['display-compile-command']}' style="display:none;"}></input>`);
  11728. div.append(display_compile_command);
  11729.  
  11730. let switches = Compiler.switches;
  11731. for (let i = 0; i < switches.length; i++) {
  11732. let switche = switches[i];
  11733.  
  11734. if (switche.type == "single") {
  11735. let single = OJB_safeCreateJQElement(`
  11736. <div>
  11737. <input type='checkbox' id='${switche.name}' value='${switche['display-flags']}' ${switche.default ? 'checked' : ''}></input>
  11738. <label for='${switche.name}'>${switche['display-name']}</label>
  11739. </div>
  11740. `);
  11741. div.append(single);
  11742. single.find("input").change(function () {
  11743. refreshCompilerArgs();
  11744. });
  11745. } else if (switche.type == "select") {
  11746. let select = OJB_safeCreateJQElement(`<select id='${switche.name}'></select>`);
  11747. select.data('previousValue', switche.options[0]['display-flags']);
  11748. div.append(select);
  11749. for (let i = 0; i < switche.options.length; i++) {
  11750. let option = switche.options[i];
  11751. let op = $("<option></option>")
  11752. .val(option['display-flags'])
  11753. .text(option['display-name']);
  11754. select.append(op);
  11755. }
  11756. select.change(function () {
  11757. refreshCompilerArgs();
  11758. });
  11759. }
  11760. }
  11761.  
  11762. if (Compiler['compiler-option-raw'] == true) {
  11763. let textarea = OJB_safeCreateJQElement(`<textarea id="compiler_option_raw" placeholder="Raw compiler options" style="resize: vertical;"></textarea>`);
  11764. div.append(textarea);
  11765. textarea.on('input', function () {
  11766. refreshCompilerArgs();
  11767. });
  11768. }
  11769. if (Compiler['runtime-option-raw'] == true) {
  11770. let textarea = OJB_safeCreateJQElement(`<textarea id="runtime_option_raw" placeholder="Raw runtime options" style="resize: vertical;"></textarea>`);
  11771. div.append(textarea);
  11772. textarea.on('input', function () {
  11773. refreshCompilerArgs();
  11774. });
  11775. }
  11776. $("#CompilerSetting").append(div);
  11777.  
  11778. refreshCompilerArgs(); // 初始化
  11779. });
  11780.  
  11781. CompilerChange.trigger("change"); // 初始化
  11782. } else {
  11783. $('#RunTestButton').prop("disabled", true);
  11784. }
  11785. }
  11786.  
  11787. // wandbox编译器通信
  11788. async function wandboxCompiler(code, input) {
  11789. try {
  11790. const result = await OJB_promiseRetryWrapper(wandboxCompilerRequest, {
  11791. maxRetries: 5,
  11792. retryInterval: 500,
  11793. errorHandler: (err) => ({ Errors: err.message, Result: '', Stats: '' })
  11794. }, code, input);
  11795. return result;
  11796. } catch (error) {
  11797. return { Errors: error.message, Result: '', Stats: '' };
  11798. }
  11799. }
  11800.  
  11801. // wandbox编译器请求方法
  11802. async function wandboxCompilerRequest(code, input) {
  11803. const data = {
  11804. code: code,
  11805. codes: [],
  11806. compiler: $('#CompilerChange').val().replace($('#compiler_option_raw').val(), '').replace($('#runtime_option_raw').val(), ''),
  11807. 'compiler-option-raw': $('#compiler_option_raw').val(),
  11808. 'runtime-option-raw': $('#runtime_option_raw').val(),
  11809. options: $("#CompilerArgsInput").val(),
  11810. description: '',
  11811. stdin: input,
  11812. title: ''
  11813. };
  11814.  
  11815. const responseDetails = await OJB_GMRequest({
  11816. method: 'POST',
  11817. url: 'https://wandbox.org/api/compile.json',
  11818. data: JSON.stringify(data),
  11819. headers: {
  11820. 'Content-Type': 'application/json'
  11821. }
  11822. });
  11823.  
  11824. if (responseDetails.status !== 200 || !responseDetails.response) {
  11825. throw new Error(`${i18next.t('compiler.common.error', { ns: 'codeEditor' })}`);
  11826. }
  11827.  
  11828. const response = JSON.parse(responseDetails.response);
  11829. return {
  11830. Errors: response.compiler_error === "" ? response.signal : response.compiler_error,
  11831. Result: response.program_output || '',
  11832. Stats: response.status === "0" ? "Finish" : "Error"
  11833. };
  11834. }
  11835.  
  11836. // 更改编译器参数
  11837. function changeCompilerArgs(nowSelect) {
  11838. if (OJBetter.monaco.onlineCompilerChoice == "official") {
  11839. officialCompilerArgsChange(nowSelect);
  11840. } else if (OJBetter.monaco.onlineCompilerChoice == "rextester") {
  11841. rextesterCompilerArgsChange(nowSelect);
  11842. } else if (OJBetter.monaco.onlineCompilerChoice == "wandbox") {
  11843. wandboxCompilerArgsChange(nowSelect);
  11844. }
  11845. }
  11846.  
  11847. // 在线编译器通信
  11848. async function onlineCompilerConnect(code, input) {
  11849. if (OJBetter.monaco.onlineCompilerChoice == "official") {
  11850. return await officialCompiler(code, input);
  11851. } else if (OJBetter.monaco.onlineCompilerChoice == "rextester") {
  11852. return await rextesterCompiler(code, input);
  11853. } else if (OJBetter.monaco.onlineCompilerChoice == "wandbox") {
  11854. return await wandboxCompiler(code, input);
  11855. }
  11856. }
  11857.  
  11858. // 差异对比
  11859. function codeDiff(expectedText, actualText) {
  11860. // 将文本按行拆分
  11861. const expectedLines = expectedText ? expectedText.split('\n') : [];
  11862. const actualLines = actualText ? actualText.split('\n') : [];
  11863.  
  11864. const output = document.createElement('div');
  11865.  
  11866. const createLineElement = (lineNo, contentElement) => {
  11867. const lineDiv = document.createElement('div');
  11868. lineDiv.className = 'diffLine';
  11869.  
  11870. const lineNoDiv = document.createElement('div');
  11871. lineNoDiv.className = 'lineNo';
  11872. lineNoDiv.textContent = lineNo;
  11873.  
  11874. lineDiv.appendChild(lineNoDiv);
  11875. lineDiv.appendChild(contentElement);
  11876.  
  11877. return lineDiv;
  11878. };
  11879.  
  11880. const createContentElement = (isEquals = true, expected = null, removed = null) => {
  11881. const contentDiv = document.createElement('div');
  11882. contentDiv.className = 'lineContent';
  11883.  
  11884. if (isEquals) {
  11885. const span = document.createElement('span');
  11886. span.textContent = expected;
  11887. contentDiv.appendChild(span);
  11888. } else {
  11889. if (removed != null) {
  11890. const removedSpan = document.createElement('span');
  11891. removedSpan.className = 'removed';
  11892. removedSpan.textContent = removed;
  11893. contentDiv.appendChild(removedSpan);
  11894. }
  11895. if (expected != null) {
  11896. const addedSpan = document.createElement('span');
  11897. addedSpan.className = 'added';
  11898. addedSpan.textContent = expected;
  11899. contentDiv.appendChild(addedSpan);
  11900. }
  11901. }
  11902.  
  11903. return contentDiv;
  11904. };
  11905.  
  11906. let index = 1;
  11907.  
  11908. expectedLines.forEach((expectedLine, i) => {
  11909. const actualLine = actualLines[i];
  11910. if (actualLine === undefined) {
  11911. output.appendChild(createLineElement(index++, createContentElement(false, expectedLine)));
  11912. } else if (expectedLine === actualLine) {
  11913. output.appendChild(createLineElement(index++, createContentElement(true, expectedLine)));
  11914. } else {
  11915. output.appendChild(createLineElement(index++, createContentElement(false, expectedLine, actualLine)));
  11916. }
  11917. });
  11918.  
  11919. // 处理多余的 actualLines
  11920. for (let i = expectedLines.length; i < actualLines.length; i++) {
  11921. output.appendChild(createLineElement(index++, createContentElement(false, null, actualLines[i])));
  11922. }
  11923.  
  11924. return output.innerHTML;
  11925. }
  11926.  
  11927. // 内容类型常量
  11928. const TestCaseContentType = {
  11929. TERMINAL: 'terminal',
  11930. DIFF: 'diff',
  11931. NO_DIFF: 'no_diff',
  11932. SUCCESS: 'success'
  11933. };
  11934.  
  11935. // 样例测试状态类
  11936. class TestCaseStatus {
  11937. constructor(item, prefix) {
  11938. this.testCase = OJB_safeCreateJQElement(`<div class="test-case"></div>`);
  11939. this.item = item;
  11940. this.prefix = prefix;
  11941. this.titleElement = OJB_safeCreateJQElement(`<div class="test-case-title">${this.prefix} ${this.item}</div>`);
  11942. this.statusElement = OJB_safeCreateJQElement(`<div class="test-case-status"></div>`);
  11943. this.contentElement = OJB_safeCreateJQElement(`<div class="test-case-content"></div>`);
  11944. this.judgeElement = OJB_safeCreateJQElement(`<div class="test-case-judge"></div>`);
  11945. this.testCase.append(this.titleElement, this.statusElement, this.contentElement, this.judgeElement);
  11946. $('#statePanel').append(this.testCase);
  11947. this.setStatus('Queued', 'queued');
  11948. }
  11949.  
  11950. setTitle(title) {
  11951. this.titleElement.text(title);
  11952. }
  11953.  
  11954. setStatus(text, status) {
  11955. this.statusElement.text(text).removeClass('queued running success error').addClass(status);
  11956. }
  11957.  
  11958. setContent(content, type) {
  11959. // 如果内容类型为SUCCESS,隐藏内容元素并提前返回
  11960. if (type === TestCaseContentType.SUCCESS) {
  11961. this.contentElement.hide();
  11962. return;
  11963. }
  11964.  
  11965. // 根据内容类型创建内容元素
  11966. const createContentElementByType = (content, type) => {
  11967. let contentElement;
  11968. switch (type) {
  11969. case TestCaseContentType.TERMINAL:
  11970. // 为TERMINAL类型创建一个新的终端容器
  11971. contentElement = OJB_safeCreateJQElement(`<div class="terminal-container" style="overflow: auto;"></div>`);
  11972. break;
  11973. case TestCaseContentType.DIFF:
  11974. case TestCaseContentType.NO_DIFF:
  11975. // 为DIFF和NO_DIFF类型创建相应的内容元素,并添加差异说明
  11976. const className = type === TestCaseContentType.DIFF ? "output_diff" : "output_no_diff";
  11977. contentElement = OJB_safeCreateJQElement(`<pre class="${className}">${content}</pre>`);
  11978. appendDiffNote();
  11979. break;
  11980. default:
  11981. throw new Error("Unsupported content type.");
  11982. }
  11983. return contentElement;
  11984. };
  11985.  
  11986. // 初始化终端
  11987. const initializeTerminal = (content, contentElement) => {
  11988. const term = new Terminal({ rows: 10, cols: 150 });
  11989. term.setOption('theme', { background: '#2d2e2c' });
  11990. term.setOption('convertEol', true); // 将换行符\n转换为\r\n
  11991. term.write(content);
  11992. term.open(contentElement.get(0));
  11993. };
  11994.  
  11995. // 添加差异说明
  11996. const appendDiffNote = () => {
  11997. const diffNote = OJB_safeCreateJQElement(`<div class="diff_note">${i18next.t('resultBlock.diffNote', { ns: 'codeEditor' })}</div>`);
  11998. this.testCase.append(diffNote);
  11999. };
  12000.  
  12001. // 创建并追加内容元素
  12002. const contentElement = createContentElementByType(content, type);
  12003. this.contentElement.append(contentElement);
  12004.  
  12005. // 如果内容类型为TERMINAL,初始化并打开终端
  12006. if (type === TestCaseContentType.TERMINAL) {
  12007. initializeTerminal(content, contentElement);
  12008. }
  12009. }
  12010.  
  12011. setJudge(judge) {
  12012. this.judgeElement.text(judge);
  12013. }
  12014. }
  12015.  
  12016. // 样例测试函数
  12017. async function runCode(event, runButton, sourceDiv, submitDiv) {
  12018. event.preventDefault();
  12019. const statePanel = $('#statePanel').show().empty();
  12020. const testData = getTestData();
  12021. const customTestData = await getCustomTestData();
  12022. const totalTests = Object.keys(customTestData).length + Object.keys(testData).length;
  12023.  
  12024. let passedTests = 0;
  12025. let failedTests = 0;
  12026. let hasError = false;
  12027.  
  12028. // 定义一个对象队列,包括创建的样例块实例和对应的样例数据
  12029. const queue = [];
  12030.  
  12031. // 先生成各个样例的块,并显示排队中,将创建的各个对象存到队列中,以便后面更新
  12032. for (const [item, data] of Object.entries(customTestData)) {
  12033. const testCase = new TestCaseStatus(item, i18next.t('resultBlock.title.custom', { ns: 'codeEditor' }));
  12034. queue.push({ testCase, data });
  12035. }
  12036.  
  12037. if (!$('#onlyCustomTest').prop('checked')) {
  12038. for (const [item, data] of Object.entries(testData)) {
  12039. const testCase = new TestCaseStatus(item, i18next.t('resultBlock.title.sample', { ns: 'codeEditor' }));
  12040. queue.push({ testCase, data });
  12041. }
  12042. }
  12043.  
  12044. // 测试函数
  12045. const runTest = async (testCase, data, index) => {
  12046. runButton.setButtonState('running', `${index}/${totalTests}`);
  12047.  
  12048. testCase.setStatus('Running', 'running');
  12049. const result = await onlineCompilerConnect(sourceDiv.val(), data.input);
  12050.  
  12051. if (result.Errors) {
  12052. testCase.setStatus('Compilation error or Time limit', 'error');
  12053. testCase.setContent(result.Errors, TestCaseContentType.TERMINAL);
  12054. hasError = true;
  12055. } else if (result.Result.trim() === data.output.trim()) {
  12056. testCase.setStatus('Accepted', 'success');
  12057. testCase.setContent('The output is correct.', TestCaseContentType.SUCCESS);
  12058. passedTests++;
  12059. } else {
  12060. testCase.setStatus('Wrong Answer', 'error');
  12061. const diffContent = $('#DontShowDiff').prop('checked') ? result.Result.trim() : codeDiff(data.output.trim(), result.Result.trim());
  12062. const contentType = $('#DontShowDiff').prop('checked') ? TestCaseContentType.NO_DIFF : TestCaseContentType.DIFF;
  12063. testCase.setContent(diffContent, contentType);
  12064. failedTests++;
  12065. }
  12066.  
  12067. const judgeStats = `${i18next.t('resultBlock.state', { ns: 'codeEditor' })}${result.Stats}`;
  12068. testCase.setJudge(judgeStats);
  12069.  
  12070. await OJB_delay(500); // 等待500毫秒
  12071. };
  12072.  
  12073. // 对队列中的对象进行测试
  12074. for (let i = 0; i < queue.length; i++) {
  12075. const { testCase, data } = queue[i];
  12076. await runTest(testCase, data, i + 1);
  12077. }
  12078.  
  12079. // 测试完成后更新按钮状态
  12080. if (hasError) {
  12081. runButton.setButtonState('error', i18next.t('runTestButton.error', { ns: 'codeEditor' }));
  12082. } else if (failedTests > 0) {
  12083. runButton.setButtonState('error', `${passedTests}/${totalTests} ` + i18next.t('runTestButton.partial', { ns: 'codeEditor' }));
  12084. } else {
  12085. runButton.setButtonState('success', i18next.t('runTestButton.success', { ns: 'codeEditor' }));
  12086. }
  12087. }
  12088.  
  12089. /**
  12090. * 添加题目页代码编辑器
  12091. * @returns
  12092. */
  12093. async function addProblemPageCodeEditor() {
  12094. // if (typeof ace === 'undefined') {
  12095. // const loadingMessage = new LoadingMessage();
  12096. // loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('error.codeEditor.load', { ns: 'alert' })}`, 'error');
  12097. // return; // 因为Codeforces设定的是未登录时不能访问提交页,也不会加载ace库
  12098. // }
  12099.  
  12100. // 获取提交页链接
  12101. const href = window.location.href;
  12102. let submitUrl = OJBetter.common.hostAddress + $('.form-code-submit').attr('action');
  12103. // if (/\/problemset\//.test(href)) {
  12104. // // problemset
  12105. // submitUrl = OJBetter.common.hostAddress + '/problemset/submit';
  12106. // } else if (/\/gym\//.test(href)) {
  12107. // // gym 题目
  12108. // submitUrl = OJBetter.common.hostAddress + '/gym/' + ((href) => {
  12109. // const regex = /\/gym\/(?<num>[0-9a-zA-Z]*?)\/problem\//;
  12110. // const match = href.match(regex);
  12111. // return match && match.groups.num;
  12112. // })(href) + '/submit';
  12113. // } else if (OJBetter.typeOfPage.is_acmsguru) {
  12114. // // acmsguru 题目
  12115. // submitUrl = href.replace(/\/problemsets[A-Za-z0-9\/#]*/, "/problemsets/acmsguru/submit");
  12116. // } else {
  12117. // submitUrl = href.replace(/\/problem[A-Za-z0-9\/#]*/, "/submit");
  12118. // }
  12119.  
  12120. // // 获取提交页HTML
  12121. // let cloneHTML = await getSubmitHTML(submitUrl);
  12122.  
  12123. // 创建
  12124. // let form = await createCodeEditorForm(submitUrl, cloneHTML);
  12125. let form = await createCodeEditorForm(submitUrl);
  12126. let selectLang = form.selectLang;
  12127. let submitButton = form.submitButton;
  12128. let runButton = form.runButton;
  12129.  
  12130. // 初始化
  12131. CustomTestInit(); // 自定义测试数据面板
  12132. selectLang.val(OJBetter.monaco.compilerSelection); // 恢复上一次的语言选择
  12133.  
  12134. // 设置语言选择change事件监听器
  12135. selectLang.on('change', () => {
  12136. changeMonacoLanguage(form); // 编辑器语言切换监听
  12137. });
  12138. changeMonacoLanguage(form);
  12139.  
  12140. // 样例测试
  12141. runButton.on('click', (event) => runCode(event, runButton, form.sourceDiv, form.submitDiv))
  12142. .setHoverRedo();
  12143.  
  12144. // 提交
  12145. submitButton.on('click', async function (event) {
  12146. event.preventDefault();
  12147. if (OJBetter.monaco.setting.isCodeSubmitDoubleConfirm) {
  12148. const submit = await OJB_createDialog(
  12149. i18next.t('submitCode.title', { ns: 'dialog' }),
  12150. i18next.t('submitCode.content', { ns: 'dialog' }),
  12151. [
  12152. i18next.t('submitCode.buttons.0', { ns: 'dialog' }),
  12153. i18next.t('submitCode.buttons.1', { ns: 'dialog' })
  12154. ]
  12155. ); //提交确认
  12156. if (submit) {
  12157. submitButton.after(`<img class="OJBetter_loding" src="//codeforces.org/s/84141/images/ajax-loading-24x24.gif">`);
  12158. $('#OJBetter_SubmitForm').submit();
  12159. } else {
  12160. submitButton.addClass('disabled');
  12161. setTimeout(function () {
  12162. submitButton.removeClass('disabled');
  12163. }, 300);
  12164. }
  12165. } else {
  12166. $('#OJBetter_SubmitForm').submit();
  12167. }
  12168. });
  12169. }
  12170.  
  12171. /**
  12172. * 获取翻译服务目标语言的对应代码
  12173. * @param {string} serverName 服务名称
  12174. * @returns {string} 目标语言,如果没有对应代码则返回中文
  12175. */
  12176. function getTargetLanguage(serverName) {
  12177. let targetLanguage = OJBetter.supportList.translationSupport[serverName][OJBetter.translation.targetLang];
  12178. if (targetLanguage) return targetLanguage;
  12179. else return OJBetter.supportList.translationSupport[serverName]['zh'];
  12180. }
  12181.  
  12182. /**
  12183. * 将文本中Markdown格式的加粗**转换成HTML格式。
  12184. * @param {string} text 文本
  12185. * @returns {string} 替换后的字符串
  12186. */
  12187. function convertBoldMarkdownToHTML(text) {
  12188. return text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
  12189. }
  12190.  
  12191. /**
  12192. * 将文本中Markdown格式的链接文本转换成HTML格式。
  12193. * @param {string} text 文本
  12194. * @returns {string} 替换后的字符串
  12195. */
  12196. function convertLinksMarkdownToHTML(text) {
  12197. return text.replace(/(?<!!)\[(.*?)\]\(([^"]*?)("(.*?)")*\)/g, '<a href="$2" title="$4">$1</a>');
  12198. }
  12199.  
  12200. /**
  12201. * 将HTML格式的加粗文本转换回Markdown格式。
  12202. * @param {string} text 文本
  12203. * @returns {string} 替换后的字符串
  12204. */
  12205. function convertBoldHTMLToMarkdown(text) {
  12206. return text.replace(/<strong>(.*?)<\/strong>/g, '**$1**');
  12207. }
  12208.  
  12209. /**
  12210. * 将HTML格式的链接文本转换回Markdown格式。
  12211. * @param {string} html - 包含HTML链接标签<a>的字符串。
  12212. * @returns {string} 转换后的字符串,其中HTML链接标签被替换为Markdown的链接语法。
  12213. */
  12214. function convertLinksHTMLToMarkdown(html) {
  12215. return html.replace(/<a href="([^"]*)"( title="([^"]*)")*>([^<]+)<\/a>/g, '[$4]($1 "$3")');
  12216. }
  12217.  
  12218. /**
  12219. * DeepL翻译
  12220. * @param {string} raw 原文
  12221. * @returns {Promise<TransRawData>} 翻译结果对象
  12222. */
  12223. async function translate_deepl(raw) {
  12224. const id = (Math.floor(Math.random() * 99999) + 100000) * 1000;
  12225. const data = {
  12226. jsonrpc: '2.0',
  12227. method: 'LMT_handle_texts',
  12228. id,
  12229. params: {
  12230. splitting: 'newlines',
  12231. lang: {
  12232. source_lang_user_selected: 'auto',
  12233. target_lang: getTargetLanguage('deepl'),
  12234. },
  12235. texts: [{
  12236. text: raw,
  12237. requestAlternatives: 3
  12238. }],
  12239. timestamp: getTimeStamp(raw.split('i').length - 1)
  12240. }
  12241. }
  12242. let postData = JSON.stringify(data);
  12243. if ((id + 5) % 29 === 0 || (id + 3) % 13 === 0) {
  12244. postData = postData.replace('"method":"', '"method" : "');
  12245. } else {
  12246. postData = postData.replace('"method":"', '"method": "');
  12247. }
  12248. const options = {
  12249. method: 'POST',
  12250. url: 'https://www2.deepl.com/jsonrpc',
  12251. data: postData,
  12252. headers: {
  12253. 'Content-Type': 'application/json',
  12254. 'Host': 'www2.deepl.com',
  12255. 'Origin': 'https://www.deepl.com',
  12256. 'Referer': 'https://www.deepl.com/',
  12257. },
  12258. anonymous: true,
  12259. nocache: true,
  12260. }
  12261.  
  12262. return await BaseTranslate(options, res => JSON.parse(res)?.result?.texts?.[0]?.text || res, res => {
  12263. const resObj = {
  12264. status: true,
  12265. message: 'ok'
  12266. };
  12267. if (res.includes('"message":"Too many requests"')) {
  12268. resObj.status = false;
  12269. resObj.message = i18next.t('error.deepl429', { ns: 'translator' }); // Too many requests 提示
  12270. return resObj;
  12271. };
  12272. return resObj;
  12273. });
  12274. }
  12275.  
  12276. /**
  12277. * 使用 DeepL Free API 进行翻译
  12278. * @param {string} raw 原文
  12279. * @returns {Promise<TransRawData>} 翻译结果对象
  12280. */
  12281. async function translate_deepl_api_free(raw) {
  12282. const data = JSON.stringify({
  12283. text: [raw],
  12284. target_lang: getTargetLanguage('deepl'),
  12285. split_sentences: '1',
  12286. ...(OJBetter.deepl.enableEmphasisProtection || OJBetter.deepl.enableLinkProtection ? { tag_handling: 'html' } : {}),
  12287. ...Object.assign({}, ...OJBetter.deepl.config.data)
  12288. });
  12289.  
  12290. const options = {
  12291. method: "POST",
  12292. url: OJBetter.deepl.config.proxy || "https://api-free.deepl.com/v2/translate",
  12293. headers: {
  12294. "Authorization": `DeepL-Auth-Key ${OJBetter.deepl.config.key}`,
  12295. "Content-Type": "application/json",
  12296. ...Object.assign({}, ...OJBetter.deepl.config.header)
  12297. },
  12298. data: data,
  12299. onload: response => response.responseText,
  12300. onerror: error => console.error(error)
  12301. };
  12302.  
  12303. return await BaseTranslate(options, res => JSON.parse(res).translations[0].text);
  12304. }
  12305.  
  12306. /**
  12307. * 使用 DeepL Pro API 进行翻译
  12308. * @param {string} raw 原文
  12309. * @returns {Promise<TransRawData>} 翻译结果对象
  12310. */
  12311. async function translate_deepl_api_pro(raw) {
  12312. const data = JSON.stringify({
  12313. text: [raw],
  12314. target_lang: getTargetLanguage('deepl'),
  12315. split_sentences: '1',
  12316. ...(OJBetter.deepl.enableEmphasisProtection || OJBetter.deepl.enableLinkProtection ? { tag_handling: 'html' } : {}),
  12317. ...Object.assign({}, ...OJBetter.deepl.config.data)
  12318. });
  12319.  
  12320. const options = {
  12321. method: "POST",
  12322. url: OJBetter.deepl.config.proxy || "https://api.deepl.com/v2/translate",
  12323. headers: {
  12324. "Authorization": `DeepL-Auth-Key ${OJBetter.deepl.config.key}`,
  12325. "Content-Type": "application/json",
  12326. ...Object.assign({}, ...OJBetter.deepl.config.header)
  12327. },
  12328. data: data,
  12329. onload: response => response.responseText,
  12330. onerror: error => console.error(error)
  12331. };
  12332.  
  12333. return await BaseTranslate(options, res => JSON.parse(res).translations[0].text);
  12334. }
  12335.  
  12336. /**
  12337. * 使用 DeepLX 进行翻译
  12338. * @param {String} text 原文
  12339. * @returns {Promise<TransRawData>} 翻译结果对象
  12340. */
  12341. async function translate_deeplx(text) {
  12342. const options = {
  12343. method: "POST",
  12344. url: OJBetter.deepl.config.proxy || 'https://api.deeplx.org/translate',
  12345. data: JSON.stringify({
  12346. "text": text,
  12347. "source_lang": "EN",
  12348. "target_lang": getTargetLanguage('deepl'),
  12349. }),
  12350. headers: {
  12351. 'Content-Type': 'application/json',
  12352. ...(OJBetter.deepl.config.key ? { Authorization: `Bearer ${OJBetter.deepl.config.key}` } : {})
  12353. },
  12354. responseType: "json",
  12355. };
  12356.  
  12357. return await BaseTranslate(options, res => {
  12358. const parsedResponse = JSON.parse(res);
  12359. if (parsedResponse.code === 200 && parsedResponse.data) {
  12360. return parsedResponse.data;
  12361. } else {
  12362. throw new Error('Translation failed or invalid response format.');
  12363. }
  12364. });
  12365. }
  12366.  
  12367. function getTimeStamp(iCount) {
  12368. const ts = Date.now();
  12369. if (iCount !== 0) {
  12370. iCount = iCount + 1;
  12371. return ts - (ts % iCount) + iCount;
  12372. } else {
  12373. return ts;
  12374. }
  12375. }
  12376.  
  12377. /**
  12378. * 讯飞听见翻译
  12379. * @param {String} text 要翻译的文本
  12380. * @returns {Promise<TransRawData>} 翻译结果对象
  12381. */
  12382. async function translate_iflyrec(text) {
  12383. const options = {
  12384. method: "POST",
  12385. url: 'https://www.iflyrec.com/TranslationService/v1/textTranslation',
  12386. data: JSON.stringify({
  12387. "from": "2",
  12388. "to": getTargetLanguage('iflyrec'),
  12389. "contents": [{
  12390. "text": text,
  12391. "frontBlankLine": 0
  12392. }]
  12393. }),
  12394. anonymous: true,
  12395. headers: {
  12396. 'Content-Type': 'application/json',
  12397. 'Origin': 'https://www.iflyrec.com',
  12398. },
  12399. responseType: "json",
  12400. };
  12401. return await BaseTranslate(options, res => JSON.parse(res).biz[0].translateResult.replace(/\\n/g, "\n\n"));
  12402. }
  12403.  
  12404. /**
  12405. * 有道翻译
  12406. * @param {string} raw 原文
  12407. * @returns {Promise<TransRawData>} 翻译结果对象
  12408. */
  12409. async function translate_youdao_mobile(raw) {
  12410. const options = {
  12411. method: "POST",
  12412. url: 'http://m.youdao.com/translate',
  12413. data: "inputtext=" + encodeURIComponent(raw) + "&type=" + getTargetLanguage('youdao'),
  12414. anonymous: true,
  12415. headers: {
  12416. "Content-Type": "application/x-www-form-urlencoded",
  12417. 'Host': 'm.youdao.com',
  12418. 'Origin': 'http://m.youdao.com',
  12419. 'Referer': 'http://m.youdao.com/translate',
  12420. }
  12421. }
  12422. return await BaseTranslate(options,
  12423. res => {
  12424. const array = /id="translateResult">\s*?<li>([\s\S]*?)<\/li>\s*?<\/ul/.exec(res);
  12425. if (array && array.length > 1) {
  12426. return array[1];
  12427. } else {
  12428. return res;
  12429. }
  12430. },
  12431. res => {
  12432. const resObj = {
  12433. status: true,
  12434. message: 'ok'
  12435. };
  12436. if (res.includes('<title>413 Request Entity Too Large</title>')) {
  12437. resObj.status = false;
  12438. resObj.message = i18next.t('error.youdao413', { ns: 'translator' }); // Request Entity Too Large 提示
  12439. return resObj;
  12440. };
  12441. return resObj;
  12442. })
  12443. }
  12444.  
  12445. /**
  12446. * google翻译
  12447. * @param {string} raw 原文
  12448. * @returns {Promise<TransRawData>} 翻译结果对象
  12449. */
  12450. async function translate_gg(raw) {
  12451. const params = `tl=${getTargetLanguage('google')}&q=${encodeURIComponent(raw)}`;
  12452. const options = {
  12453. method: "GET",
  12454. url: `https://translate.google.com/m?${params}`,
  12455. }
  12456. return await BaseTranslate(options,
  12457. res => $(res).filter('.result-container').text() || $(res).find('.result-container').text());
  12458. }
  12459.  
  12460. /**
  12461. * 彩云翻译
  12462. * @param {string} raw 原文
  12463. * @returns {Promise<TransRawData>} 翻译结果对象
  12464. */
  12465. async function translate_caiyun(raw) {
  12466. const source = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm";
  12467. const dic = [..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"].reduce((dic, current, index) => { dic[current] = source[index]; return dic }, {});
  12468. const browser_id = CryptoJS.MD5(Math.random().toString()).toString();
  12469. const caiyun_jwt = await (async () => {
  12470. const options = {
  12471. method: "POST",
  12472. url: 'https://api.interpreter.caiyunai.com/v1/user/jwt/generate',
  12473. headers: {
  12474. "content-type": "application/json",
  12475. "x-authorization": "token:qgemv4jr1y38jyq6vhvi",
  12476. "origin": "https://fanyi.caiyunapp.com",
  12477. },
  12478. data: JSON.stringify({ browser_id }),
  12479. }
  12480. const res = await OJB_GMRequest(options);
  12481. return JSON.parse(res.responseText).jwt;
  12482. })();
  12483.  
  12484. // 解码
  12485. const decodeUnicode = str => {
  12486. const decoder = new TextDecoder();
  12487. const data = Uint8Array.from(atob(str), c => c.charCodeAt(0));
  12488. return decoder.decode(data);
  12489. };
  12490. const decoder = line => decodeUnicode([...line].map(i => dic[i] || i).join(""));
  12491.  
  12492. const options = {
  12493. method: "POST",
  12494. url: 'https://api.interpreter.caiyunai.com/v1/translator',
  12495. data: JSON.stringify({
  12496. "source": raw.split('\n'),
  12497. "browser_id": browser_id,
  12498. "trans_type": getTargetLanguage('caiyun'),
  12499. "request_id": "web_fanyi",
  12500. "media": "text",
  12501. "os_type": "web",
  12502. "dict": true,
  12503. "cached": true,
  12504. "replaced": true,
  12505. "style": "formal",
  12506. "model": "",
  12507. "detect": true,
  12508. }),
  12509. headers: {
  12510. "content-type": "application/json;charset=UTF-8",
  12511. "x-authorization": "token:qgemv4jr1y38jyq6vhvi",
  12512. "t-authorization": caiyun_jwt
  12513. }
  12514. }
  12515. return await BaseTranslate(options, res => JSON.parse(res).target.map(decoder).join('\n'))
  12516. }
  12517.  
  12518. /**
  12519. * ChatGPT
  12520. * @param {string} raw 原文
  12521. * @returns {Promise<TransRawData>} 翻译结果对象
  12522. */
  12523. async function translate_openai(raw) {
  12524. const modelDefault = 'gpt-3.5-turbo';
  12525. const lang = getTargetLanguage('openai');
  12526. const prompt = `
  12527. As a professional English translator, your task is to accurately translate a segment of an algorithm programming competition question into ${lang}.
  12528. The translation should use professional terms and maintain the text format, including ${OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru
  12529. ? "keeping the LaTeX equations unchanged."
  12530. : "keeping the brackets【】, HTML tags, and their content unchanged."
  12531. }
  12532. After translation, please ensure that the ${lang} version conforms to normal expression habits.
  12533. What I need is a carefully polished ${lang} translation of my question segment, The segment to be translated is as follows: "
  12534. ${raw}
  12535. "`;
  12536. const data = {
  12537. model: OJBetter.chatgpt.config.model || modelDefault,
  12538. messages: [{
  12539. role: "assistant",
  12540. content: prompt
  12541. }],
  12542. temperature: 0.7,
  12543. ...Object.assign({}, ...OJBetter.chatgpt.config.data)
  12544. }
  12545. const options = {
  12546. method: "POST",
  12547. url: OJBetter.chatgpt.config.proxy || 'https://api.openai.com/v1/chat/completions',
  12548. data: JSON.stringify(data),
  12549. responseType: 'json',
  12550. headers: {
  12551. 'Content-Type': 'application/json',
  12552. 'Authorization': 'Bearer ' + OJBetter.chatgpt.config.key,
  12553. ...Object.assign({}, ...OJBetter.chatgpt.config.header)
  12554. }
  12555. }
  12556. return await BaseTranslate(options,
  12557. res => res,
  12558. undefined,
  12559. response => response.response.choices[0].message.content);
  12560. }
  12561.  
  12562. /**
  12563. * ChatGPT 流式传输
  12564. * @param {string} raw 原文
  12565. * @param {TranslateDiv} translateDiv 翻译结果面板
  12566. * @returns {Promise<TransRawData>} 翻译结果对象
  12567. */
  12568. async function translate_openai_stream(raw, translateDiv) {
  12569. const result = {
  12570. done: true,
  12571. checkPassed: null,
  12572. response: null,
  12573. responseText: null,
  12574. text: "",
  12575. error: null,
  12576. message: null
  12577. };
  12578. const helpText = i18next.t('error.basic', { ns: 'translator' }); // 基本帮助提示信息
  12579. try {
  12580. for await (const delta of openai_stream(raw)) {
  12581. result.text += delta;
  12582. // 翻译结果面板更新
  12583. translateDiv.updateTranslateDiv(result.text, !(OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru), false);
  12584. }
  12585. return result;
  12586. } catch (err) {
  12587. console.warn(err);
  12588. result.error = {
  12589. message: err.message || null,
  12590. stack: err.stack ? err.stack.replace(/\n/g, '<br>').replace(/\s/g, '&nbsp;') : null,
  12591. enumerable: err,
  12592. source: 'openai_stream'
  12593. };
  12594. result.message = `${i18next.t('error.GMRequest', { ns: 'translator' })}${helpText}`;
  12595. }
  12596.  
  12597. return result;
  12598. }
  12599.  
  12600. /**
  12601. * 流式传输
  12602. * @param {string} raw 原文
  12603. * @returns {AsyncGenerator<string>} 返回 AsyncGenerator
  12604. */
  12605. async function* openai_stream(raw) {
  12606. const modelDefault = 'gpt-3.5-turbo';
  12607. const lang = getTargetLanguage('openai');
  12608. const prompt = `
  12609. I hope you can act as a professional English translator to help me translate a segment of an algorithm programming competition question into ${lang}.
  12610. During the translation process, I would like you to use more professional terms and maintain the text format, ${OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru
  12611. ? "keeping the LaTeX equations unchanged."
  12612. : "keeping the brackets【】, HTML tags, and their content unchanged."
  12613. }
  12614. After completing the translation, please polish the ${lang} version to ensure it conforms to normal expression habits.
  12615. What I need is a carefully polished ${lang} translation of my question segment, which is as follows:
  12616. "
  12617. ${raw}
  12618. "`;
  12619. const data = {
  12620. model: OJBetter.chatgpt.config.model || modelDefault,
  12621. messages: [{
  12622. role: "assistant",
  12623. content: prompt
  12624. }],
  12625. temperature: 0.7,
  12626. stream: true,
  12627. ...Object.assign({}, ...OJBetter.chatgpt.config.data)
  12628. }
  12629. const options = {
  12630. method: "POST",
  12631. url: OJBetter.chatgpt.config.proxy || 'https://api.openai.com/v1/chat/completions',
  12632. data: JSON.stringify(data),
  12633. responseType: 'stream',
  12634. headers: {
  12635. 'Content-Type': 'application/json',
  12636. 'Authorization': 'Bearer ' + OJBetter.chatgpt.config.key,
  12637. ...Object.assign({}, ...OJBetter.chatgpt.config.header)
  12638. }
  12639. }
  12640. const response = await OJB_GMRequest(options, true);
  12641. const reader = response.response.getReader();
  12642. const decoder = new TextDecoder();
  12643. let buffer = ''; // 用于累积数据片段的缓冲区
  12644.  
  12645. while (true) {
  12646. const { done, value } = await reader.read();
  12647. if (done) break;
  12648. buffer += decoder.decode(value, { stream: true }); // 将新的数据片段追加到缓冲区
  12649. let lines = buffer.split("\n\n"); // 处理累积的数据
  12650.  
  12651. // 缓冲区的最后一行可能还未完整接收,保留在缓冲区中,-1
  12652. for (let i = 0; i < lines.length - 1; i++) {
  12653. let line = lines[i];
  12654. line = line.substring(5); // 移除 'data:' 前缀
  12655. if (line.includes('[DONE]')) {
  12656. return; // End
  12657. }
  12658. try {
  12659. let data = JSON.parse(line);
  12660. let delta = data['choices'][0]['delta'];
  12661. let content = delta['content'] ? delta['content'] : "";
  12662. yield content; // 传递数据给调用者
  12663. } catch (error) {
  12664. console.warn(`Error parsing JSON: ${error}\n\nError data: ${line}`);
  12665. }
  12666. }
  12667.  
  12668. // 保留最后一行在缓冲区中
  12669. buffer = lines.slice(-1);
  12670. }
  12671.  
  12672. return buffer;
  12673. }
  12674.  
  12675. /**
  12676. * @typedef {Object} CheckResponseResult
  12677. * @property {boolean} status 检查是否通过
  12678. * @property {string} message 检查失败时的消息
  12679. */
  12680.  
  12681. /**
  12682. * @typedef {Object} ErrorResponse
  12683. * @property {Object} message 错误消息
  12684. * @property {Object} stack 错误堆栈
  12685. * @property {Object} enumerable 可枚举的错误属性
  12686. * @property {string} source 错误来源
  12687. */
  12688.  
  12689. /**
  12690. * @typedef {Object} TransRawData
  12691. * @property {boolean} done 操作是否完成
  12692. * @property {CheckResponseResult|null} checkPassed 检查是否通过的结果
  12693. * @property {Object|null} response 响应对象
  12694. * @property {string|null} text 处理后的文本
  12695. * @property {ErrorResponse} error 错误列表
  12696. * @property {string|null} message 可能的消息
  12697. */
  12698.  
  12699. /**
  12700. * 通用翻译函数
  12701. * @param {Object} options GM_xmlhttpRequest 的参数
  12702. * @param {Function} processer 响应再处理函数,它接收响应文本,并应返回处理后的文本。
  12703. * @param {Function} checkResponse 检查文本是否符合预期的函数,它接收文本,并返回一个Object,包含状态和信息。默认为返回 { status: true, message: 'ok' }
  12704. * @param {Function} getResponseText 重写响应文本获取函数,它接收response,并返回响应文本。 默认为 response.responseText
  12705. * @returns {Promise<TransRawData>} 返回 Promise,其解析值为翻译结果对象
  12706. */
  12707. async function BaseTranslate(options, processer, checkResponse = () => { return { status: true, message: 'ok' } }, getResponseText = (response) => response.responseText) {
  12708. const result = {
  12709. done: false,
  12710. checkPassed: null,
  12711. response: null,
  12712. responseText: null,
  12713. text: "",
  12714. error: null,
  12715. message: null
  12716. };
  12717. const helpText = i18next.t('error.basic', { ns: 'translator' }); // 基本帮助提示信息
  12718. const toDo = async () => {
  12719. try {
  12720. result.response = await OJB_GMRequest(options);
  12721. result.responseText = result.response.responseText;
  12722. result.text = getResponseText(result.response);
  12723. } catch (err) {
  12724. console.warn(err);
  12725. result.error = {
  12726. message: err.message || null,
  12727. stack: err.stack ? err.stack.replace(/\n/g, '<br>').replace(/\s/g, '&nbsp;') : null,
  12728. enumerable: err,
  12729. source: 'GMRequest'
  12730. };
  12731. result.message = `${i18next.t('error.GMRequest', { ns: 'translator' })}${helpText}`;
  12732. throw result;
  12733. }
  12734. try {
  12735. result.text = processer(result.text);
  12736. } catch (err) {
  12737. console.warn(err);
  12738. result.error = {
  12739. message: err.message || null,
  12740. stack: err.stack ? err.stack.replace(/\n/g, '<br>').replace(/\s/g, '&nbsp;') : null,
  12741. enumerable: err,
  12742. source: 'processer'
  12743. };
  12744. result.message = `${i18next.t('error.processer', { ns: 'translator' })}${helpText}`;
  12745. throw result;
  12746. }
  12747. try {
  12748. result.checkPassed = checkResponse(result.text);
  12749. if (result.checkPassed.status) result.done = true;
  12750. else result.message = result.checkPassed.message;
  12751. return result;
  12752. } catch (err) {
  12753. console.warn(err);
  12754. result.error = {
  12755. message: err.message || null,
  12756. stack: err.stack ? err.stack.replace(/\n/g, '<br>').replace(/\s/g, '&nbsp;') : null,
  12757. enumerable: err,
  12758. source: 'checkResponse'
  12759. };
  12760. result.message = `${i18next.t('error.checkResponse', { ns: 'translator' })}${helpText}`;
  12761. throw result;
  12762. }
  12763. };
  12764.  
  12765. return await OJB_promiseRetryWrapper(toDo, {
  12766. maxRetries: 3,
  12767. errorHandler: (err, maxRetries, attemptsLeft) => {
  12768. const detailedError = {
  12769. maxRetries: maxRetries,
  12770. attemptsLeft: attemptsLeft,
  12771. ...err
  12772. };
  12773. return detailedError;
  12774. }
  12775. });
  12776. }
  12777.  
  12778. /**
  12779. * 查询服务余额
  12780. * @param {Object} quotaConfig - 配额配置对象
  12781. * @returns {Promise} 返回包含余额信息的 Promise
  12782. */
  12783. async function queryServerBalance(quotaConfig) {
  12784. // 确保传入了有效的配置对象
  12785. if (!quotaConfig || !quotaConfig.url) {
  12786. return Promise.reject(new Error('Quota configuration is missing.'));
  12787. }
  12788.  
  12789. // 准备请求选项
  12790. const requestOptions = {
  12791. method: quotaConfig.method || 'GET',
  12792. url: quotaConfig.url,
  12793. headers: {
  12794. ...Object.assign({}, ...quotaConfig.header)
  12795. },
  12796. data: JSON.stringify({ ...Object.assign({}, ...quotaConfig.data) })
  12797. };
  12798.  
  12799. // 发送请求并返回 Promise
  12800. return OJB_GMRequest(requestOptions).then(response => {
  12801. try {
  12802. const responseData = JSON.parse(response.responseText);
  12803. // 从响应数据中提取余额
  12804. const surplusPath = quotaConfig.surplus;
  12805. const surplusValue = OJB_evaluatePathOrExpression(responseData, surplusPath);
  12806. return surplusValue;
  12807. } catch (error) {
  12808. return Promise.reject(new Error('Failed to parse balance response.'));
  12809. }
  12810. }).catch(error => {
  12811. console.warn('Error querying balance:', error);
  12812. return Promise.reject(error);
  12813. });
  12814. }
  12815.  
  12816. /**
  12817. * 确认 jQuery 已加载
  12818. * @param {number} retryDelay 重试延迟(毫秒)
  12819. * @returns {Promise<void>}
  12820. */
  12821. async function ensureJQueryIsLoaded(retryDelay = 50) {
  12822. while (typeof jQuery === 'undefined') {
  12823. console.warn(`JQuery is not loaded. Retry after ${retryDelay} ms.`);
  12824. await OJB_delay(retryDelay);
  12825. retryDelay = Math.min(retryDelay * 2, 2000);
  12826. }
  12827. }
  12828.  
  12829. /**
  12830. * 加载必须的函数
  12831. * @returns {Promise} 加载提示信息
  12832. */
  12833. async function loadRequiredFunctions() {
  12834. await initVar();// 初始化全局变量
  12835. return Promise.allSettled([
  12836. initDB(), // 连接数据库
  12837. initI18next(), // i18next初始化
  12838. initButtonFunc(), // 加载按钮相关函数
  12839. checkScriptVersion(), // 更新检查
  12840. // ...(OJBetter.typeOfPage.is_acmsguru ? [acmsguruReblock()] : []) // 为acmsguru题面重新划分div
  12841. ]);
  12842. }
  12843.  
  12844. /**
  12845. * DOM加载后即可执行
  12846. */
  12847. function initOnDOMReady() {
  12848. showAnnounce(); // 显示公告
  12849. showWarnMessage(); // 显示警告消息
  12850. initSettingsPanel(); // 加载设置按钮面板
  12851. localizeWebsite(); // 网站本地化替换
  12852. addDependencyStyles(); // 添加一些依赖库的样式
  12853. addI18nStyles(); // 添加包含i18n内容的样式
  12854. // if (OJBetter.basic.expandFoldingblocks) ExpandFoldingblocks(); // 折叠块展开
  12855. // if (OJBetter.basic.renderPerfOpt) RenderPerfOpt(); // 折叠块渲染优化
  12856. if (OJBetter.typeOfPage.is_problem) {
  12857. const problemPageLinkbar = new ProblemPageLinkbar(); // 创建题目页相关链接栏
  12858. if (OJBetter.basic.showCF2vjudge) CF2vjudge(problemPageLinkbar); // 跳转到Vjudge按钮
  12859. if (OJBetter.basic.showJumpToLuogu) CF2luogu(problemPageLinkbar); // 跳转到洛谷按钮
  12860. if (OJBetter.clist.enabled.problem) showRatingByClist_problem(problemPageLinkbar); // problem页显示Rating
  12861. }
  12862. if (OJBetter.typeOfPage.is_contest) {
  12863. if (OJBetter.clist.enabled.contest) showRatingByClist_contest(); // contest页显示Rating
  12864. }
  12865. // if (OJBetter.typeOfPage.is_problemset) {
  12866. // if (OJBetter.clist.enabled.problemset) showRatingByClist_problemset(); // problemset页显示Rating
  12867. // }
  12868. if (OJBetter.typeOfPage.is_problem && OJBetter.monaco.enableOnProblemPage) {
  12869. addProblemPageCodeEditor(); // 添加题目页代码编辑器
  12870. }
  12871. }
  12872.  
  12873. /**
  12874. * 需要在页面资源完全加载后执行的函数
  12875. */
  12876. function onResourcesReady(loadingMessage) {
  12877. if (OJBetter.preference.showLoading) loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('loadFunc', { ns: 'alert' })}`);
  12878. initializeInParallel(loadingMessage);
  12879. initializeSequentially(loadingMessage);
  12880. }
  12881.  
  12882. /**
  12883. * 可以异步并行的函数
  12884. */
  12885. function initializeInParallel(loadingMessage) {
  12886. if (OJBetter.basic.darkMode == "dark") darkModeStyleAdjustment(); // 黑暗模式额外的处理事件
  12887. // if (OJBetter.basic.commentPaging) CommentPagination(); // 评论区分页
  12888. if (OJBetter.translation.comment.transMode == "2") multiChoiceTranslation(); // 选段翻译支持
  12889. if (OJBetter.monaco.beautifyPreBlocks) beautifyPreBlocksWithMonaco(); // 美化Pre代码块
  12890. }
  12891.  
  12892. /**
  12893. * 必须按序执行的函数
  12894. */
  12895. async function initializeSequentially(loadingMessage) {
  12896. await addConversionButton(); // 添加MD/复制/翻译按钮
  12897. if ((OJBetter.typeOfPage.is_problem || OJBetter.typeOfPage.is_completeProblemset) && OJBetter.translation.memory.enabled) {
  12898. await initTransResultsRecover(); // 翻译结果恢复功能初始化
  12899. }
  12900. // if (OJBetter.translation.auto.enabled) {
  12901. // await initTransWhenViewable(); // 自动翻译
  12902. // }
  12903. // if (OJBetter.basic.standingsRecolor && OJBetter.typeOfPage.is_cfStandings) {
  12904. // await recolorStandings(); // cf赛制榜单重新着色
  12905. // }
  12906. if (OJBetter.preference.showLoading) loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('loadSuccess', { ns: 'alert' })}`, 'success', 3000);
  12907. }
  12908.  
  12909. /**
  12910. * 主方法
  12911. */
  12912. async function main() {
  12913. await ensureJQueryIsLoaded(); // 等待jQuery加载
  12914. const loadingMessage = new LoadingMessage();
  12915. await loadRequiredFunctions(); // 加载必须的函数
  12916. initOnDOMReady(); // DOM加载后即可执行的函数
  12917. if (OJBetter.preference.showLoading) loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('onload', { ns: 'alert' })}`);
  12918.  
  12919. // 检查页面资源是否已经完全加载
  12920. if (OJBetter.state.notWaiteLoaded) {
  12921. onResourcesReady(loadingMessage);
  12922. } else {
  12923. if (document.readyState === 'complete') {
  12924. onResourcesReady(loadingMessage);
  12925. } else {
  12926. window.addEventListener('load', () => onResourcesReady(loadingMessage));
  12927. }
  12928. }
  12929. };
  12930.  
  12931. // ------------------------------
  12932. // 脚本加载入口
  12933. if (document.readyState === 'loading') {
  12934. document.addEventListener("DOMContentLoaded", main);
  12935. } else {
  12936. main(); // 如果DOMContentLoaded已经触发,立即执行
  12937. }
  12938. // ------------------------------
  12939.  
  12940. // ------------------------------
  12941. // 配置自动迁移代码(将在10个小版本后移除-1.19)
  12942. // ------------------------------
  12943.  
  12944. if (GM_getValue("openai_key") || GM_getValue("api2d_key")) {
  12945. const newConfig = { "choice": -1, "configurations": [] };
  12946. if (GM_getValue("openai_key")) {
  12947. let config1 = {
  12948. "note": "我的配置1",
  12949. "model": GM_getValue("openai_model"),
  12950. "key": GM_getValue("openai_key"),
  12951. "proxy": GM_getValue("openai_proxy"),
  12952. "_header": "",
  12953. "_data": ""
  12954. }
  12955. if (GM_getValue("translation") === "openai") newConfig.choice = 0;
  12956. newConfig.configurations.push(config1);
  12957. }
  12958. if (GM_getValue("api2d_key")) {
  12959. let config2 = {
  12960. "note": "api2d",
  12961. "model": GM_getValue("api2d_model"),
  12962. "key": GM_getValue("api2d_key"),
  12963. "proxy": GM_getValue("api2d_request_entry") + '/v1/chat/completions',
  12964. "_header": GM_getValue("x_api2d_no_cache") ? "" : " x-api2d-no-cache : 1",
  12965. "_data": ""
  12966. }
  12967. if (GM_getValue("translation") === "api2d") {
  12968. if (GM_getValue("openai_key")) newConfig.choice = 1;
  12969. else newConfig.choice = 0;
  12970. }
  12971. newConfig.configurations.push(config2);
  12972. }
  12973. GM_setValue("chatgpt-config", newConfig);
  12974. const keysToDelete = ["openai_key", "openai_model", "openai_proxy", "api2d_key", "api2d_model", "api2d_request_entry", "x_api2d_no_cache", "showOpneAiAdvanced"];
  12975. keysToDelete.forEach(key => {
  12976. if (GM_getValue(key) != undefined) GM_deleteValue(key);
  12977. });
  12978. if (GM_getValue("translation") === "api2d") GM_setValue("translation", "openai");
  12979. location.reload();
  12980. }
  12981.  
  12982.  
  12983. // ------------------------------
  12984. // 配置自动迁移代码(将在10个小版本后移除-1.23)
  12985. // ------------------------------
  12986.  
  12987. {
  12988. let bottomZh_CN = GM_getValue("bottomZh_CN");
  12989. if (bottomZh_CN !== undefined) {
  12990. if (bottomZh_CN == true) {
  12991. GM_setValue("localizationLanguage", "zh");
  12992. } else {
  12993. GM_setValue("localizationLanguage", "initial");
  12994. }
  12995. GM_deleteValue("bottomZh_CN");
  12996. location.reload();
  12997. }
  12998. }
  12999. {
  13000. let config = GM_getValue("chatgpt-config");
  13001. if (config && config !== undefined) {
  13002. let index = parseInt(config.choice, 10);
  13003. if (index == -1) config.choice = "";
  13004. else config.choice = config.configurations[index].note;
  13005. config.configurations.forEach(function (item) {
  13006. item.name = item.note;
  13007. delete item.note;
  13008. });
  13009. GM_deleteValue("chatgpt-config");
  13010. GM_setValue("chatgpt_config", config);
  13011. location.reload();
  13012. }
  13013. }
  13014.  
  13015. // ------------------------------
  13016. // 配置自动迁移代码(将在10个小版本后移除-1.24)
  13017. // ------------------------------
  13018.  
  13019. {
  13020. let config = GM_getValue("compilerSelection");
  13021. if (config !== undefined) {
  13022. if (config === "61") {
  13023. GM_setValue("compilerSelection", "5001");
  13024. location.reload();
  13025. }
  13026. }
  13027. }