Codeforces Better!

一個適用於 Codeforces 的 Tampermonkey 腳本,增強功能與界面。

目前為 2024-02-20 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name Codeforces Better!
  3. // @name:zh-TW Codeforces Better!
  4. // @name:en Codeforces Better!
  5. // @name:de Codeforces Better!
  6. // @name:fr Codeforces Better!
  7. // @name:ko Codeforces Better!
  8. // @name:pt Codeforces Better!
  9. // @name:ja Codeforces Better!
  10. // @name:es Codeforces Better!
  11. // @name:it Codeforces Better!
  12. // @name:hi Codeforces Better!
  13. // @namespace https://gf.qytechs.cn/users/747162
  14. // @version 1.73.0
  15. // @description 一个适用于 Codeforces 的 Tampermonkey 脚本,增强功能与界面。
  16. // @description:zh-TW 一個適用於 Codeforces 的 Tampermonkey 腳本,增強功能與界面。
  17. // @description:en A Tampermonkey script for Codeforces that enhances functionality and interface.
  18. // @description:de Ein Tampermonkey-Skript für Codeforces, das Funktionalität und Benutzeroberfläche verbessert.
  19. // @description:fr Un script Tampermonkey pour Codeforces qui améliore les fonctionnalités et l'interface.
  20. // @description:ko Codeforces를 위한 Tampermonkey 스크립트로 기능과 인터페이스를 개선합니다.
  21. // @description:pt Um script Tampermonkey para Codeforces que aprimora a funcionalidade e a interface.
  22. // @description:ja Codeforces用のTampermonkeyスクリプトで機能とインターフェースを強化します。
  23. // @description:es Un script Tampermonkey para Codeforces que mejora la funcionalidad y la interfaz.
  24. // @description:it Uno script Tampermonkey per Codeforces che migliora la funzionalità e l'interfaccia.
  25. // @description:hi Codeforces के लिए एक Tampermonkey स्क्रिप्ट जो कार्यक्षमता और इंटरफ़ेस को बेहतर बनाता है।
  26. // @author 北极小狐
  27. // @match *://*.codeforces.com/*
  28. // @match *://*.codeforc.es/*
  29. // @run-at document-start
  30. // @connect www2.deepl.com
  31. // @connect api-free.deepl.com
  32. // @connect api.deepl.com
  33. // @connect api.deeplx.org
  34. // @connect www.iflyrec.com
  35. // @connect m.youdao.com
  36. // @connect api.interpreter.caiyunai.com
  37. // @connect translate.google.com
  38. // @connect openai.api2d.net
  39. // @connect api.openai.com
  40. // @connect www.luogu.com.cn
  41. // @connect clist.by
  42. // @connect gf.qytechs.cn
  43. // @connect rextester.com
  44. // @connect wandbox.org
  45. // @connect staticfile.org
  46. // @connect aowuucdn.oss-cn-beijing.aliyuncs.com
  47. // @connect aowuucdn.oss-accelerate.aliyuncs.com
  48. // @connect 127.0.0.1
  49. // @connect *
  50. // @grant GM_xmlhttpRequest
  51. // @grant GM_info
  52. // @grant GM_setValue
  53. // @grant GM_getValue
  54. // @grant GM_listValues
  55. // @grant GM_deleteValue
  56. // @grant GM_addStyle
  57. // @grant GM_setClipboard
  58. // @grant GM_getResourceText
  59. // @icon https://aowuucdn.oss-accelerate.aliyuncs.com/codeforces.png
  60. // @require https://cdn.staticfile.org/turndown/7.1.2/turndown.min.js
  61. // @require https://cdn.staticfile.org/markdown-it/13.0.1/markdown-it.min.js
  62. // @require https://cdn.bootcdn.net/ajax/libs/crypto-js/4.1.1/crypto-js.min.js
  63. // @require https://cdn.staticfile.org/chroma-js/2.4.2/chroma.min.js
  64. // @require https://cdn.staticfile.org/xterm/3.9.2/xterm.min.js
  65. // @require https://cdn.staticfile.org/dexie/3.2.4/dexie.min.js
  66. // @require https://cdn.staticfile.org/i18next/23.5.1/i18next.min.js
  67. // @require https://cdn.staticfile.org/i18next-http-backend/2.2.2/i18nextHttpBackend.min.js
  68. // @require https://cdn.staticfile.org/jquery-i18next/1.2.1/jquery-i18next.min.js
  69. // @require https://update.gf.qytechs.cn/scripts/484742/1311040/i18nextChainedBackendjs.js
  70. // @require https://update.gf.qytechs.cn/scripts/484743/1311041/i18next-localstorage-backendjs.js
  71. // @resource acwing_cpp_code_completer https://aowuucdn.oss-accelerate.aliyuncs.com/acwing_cpp_code_completer-0.0.11.json
  72. // @resource wandboxlist https://wandbox.org/api/list.json
  73. // @resource xtermcss https://cdn.staticfile.org/xterm/3.9.2/xterm.min.css
  74. // @license GPL3
  75. // @compatible Chrome
  76. // @compatible Firefox
  77. // @compatible Edge
  78. // @incompatible safari
  79. // @supportURL https://github.com/beijixiaohu/OJBetter/issues
  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. version: GM_info.script.version,
  98. /** @type {boolean?} 是否跳过页面加载等待 */
  99. notWaiteLoaded: undefined,
  100. /** @type {string} 最后公告版本,用于标识版本更新完成提示 */
  101. lastAnnounceVer: undefined,
  102. /** @type {string} 最后读取的有效公告版本 */
  103. lastReadAnnounceVer: undefined,
  104. /** @type {number} 当前已打开的模态对话框数量*/
  105. openDialogCount: 0
  106. };
  107.  
  108. /**
  109. * @namespace common
  110. * @desc 通用设置和属性。
  111. * @memberof OJBetter
  112. */
  113. OJBetter.common = {
  114. /** @type {string} 网站的主机地址 */
  115. hostAddress: location.origin,
  116. /** @type {string?} Codeforces的CSRF令牌 */
  117. cf_csrf_token: undefined,
  118. /** @type {Array?} 任务队列 */
  119. taskQueue: undefined,
  120. /** @type {object} CFBetter数据库连接实例*/
  121. database: undefined
  122. };
  123.  
  124. /**
  125. * @namespace basic
  126. * @desc 基本的用户界面设置。
  127. * @memberof OJBetter
  128. */
  129. OJBetter.basic = {
  130. /** @type {string} 黑暗模式设置 */
  131. darkMode: undefined,
  132. /** @type {boolean?} 是否展开折叠块 */
  133. expandFoldingblocks: undefined,
  134. /** @type {boolean?} 是否开启折叠块渲染性能优化 */
  135. renderPerfOpt: undefined,
  136. /** @type {boolean?} 评论区分页 */
  137. commentPaging: undefined,
  138. /** @type {boolean?} 显示跳转到Luogu按钮 */
  139. showJumpToLuogu: undefined,
  140. /** @type {boolean?} 比赛排行榜重新着色 */
  141. standingsRecolor: undefined
  142. };
  143.  
  144. /**
  145. * @namespace typeOfPage
  146. * @desc 页面类型判断。
  147. * @memberof OJBetter
  148. */
  149. OJBetter.typeOfPage = {
  150. /** @type {boolean?} 是否是轻量站 */
  151. is_mSite: undefined,
  152. /** @type {boolean?} 是否是acmsguru页面 */
  153. is_acmsguru: undefined,
  154. /** @type {boolean?} 是否是旧版LaTeX页面 */
  155. is_oldLatex: undefined,
  156. /** @type {boolean?} 是否是比赛页面 */
  157. is_contest: undefined,
  158. /** @type {boolean?} 是否是题目页面 */
  159. is_problem: undefined,
  160. /** @type {boolean?} 是否是完整的问题集页面 */
  161. is_completeProblemset: undefined,
  162. /** @type {boolean?} 是否是问题集中的问题页面 */
  163. is_problemset_problem: undefined,
  164. /** @type {boolean?} 是否是问题集页面 */
  165. is_problemset: undefined,
  166. /** @type {boolean?} 是否是Codeforces排名页面 */
  167. is_cfStandings: undefined,
  168. /** @type {boolean?} 是否是提交页面 */
  169. is_submitPage: undefined
  170. };
  171.  
  172. /**
  173. * @namespace localization
  174. * @desc 本地化设置。
  175. * @memberof OJBetter
  176. */
  177. OJBetter.localization = {
  178. /** @type {string?} 网站语言 */
  179. websiteLang: undefined,
  180. /** @type {string?} 脚本语言 */
  181. scriptLang: undefined
  182. };
  183.  
  184. /**
  185. * @namespace translation
  186. * @desc 翻译设置。
  187. * @memberof OJBetter
  188. */
  189. OJBetter.translation = {
  190. /** @type {string?} 翻译服务选择 */
  191. choice: undefined,
  192. /** @type {string?} 目标语言 */
  193. targetLang: undefined,
  194. comment: {
  195. /** @type {string?} 评论翻译服务选择 */
  196. choice: undefined,
  197. /** @type {string?} 评论翻译模式 */
  198. transMode: undefined
  199. },
  200. auto: {
  201. /** @type {boolean?} 自动翻译开关 */
  202. enabled: undefined,
  203. /** @type {number?} 短文本长度限制 */
  204. shortTextLength: undefined,
  205. mixTrans: {
  206. /** @type {boolean?} 混合翻译开关 */
  207. enabled: undefined,
  208. /** @type {Array?} 混合翻译服务列表 */
  209. servers: undefined
  210. }
  211. },
  212. memory: {
  213. /** @type {boolean?} 翻译记忆开关 */
  214. enabled: undefined,
  215. /** @type {Object?} 翻译记忆树 */
  216. ttTree: undefined
  217. },
  218. /** @type {string?} 重翻译时的行为 */
  219. retransAction: undefined,
  220. /** @type {number?} 等待时间 */
  221. waitTime: undefined,
  222. /** @type {boolean?} 替换符 */
  223. replaceSymbol: undefined,
  224. /** @type {boolean?} 过滤文本中的*号 */
  225. filterTextWithoutEmphasis: undefined
  226. };
  227.  
  228. /**
  229. * @namespace clist
  230. * @desc Clist相关设置。
  231. * @memberof OJBetter
  232. */
  233. OJBetter.clist = {
  234. enabled: {
  235. /** @type {boolean?} 比赛页面开关 */
  236. contest: undefined,
  237. /** @type {boolean?} 问题页面开关 */
  238. problem: undefined,
  239. /** @type {boolean?} 问题集页面开关 */
  240. problemset: undefined
  241. },
  242. /** @type {boolean?} Rating数据防剧透 */
  243. ratingHidden: undefined,
  244. /** @type {string?} Clist key */
  245. authorization: undefined
  246. };
  247.  
  248. /**
  249. * @namespace monaco
  250. * @desc Monaco编辑器配置。
  251. * @memberof OJBetter
  252. */
  253. OJBetter.monaco = {
  254. /** @type {boolean?} 在问题页面上启用Monaco编辑器 */
  255. enableOnProblemPage: undefined,
  256. /** @type {boolean} Monaco编辑器加载完成标志 */
  257. loaderOnload: false,
  258. lsp: {
  259. /** @type {Array?} LSP套接字数组 */
  260. socket: [],
  261. /** @type {boolean?} 是否启用LSP */
  262. enabled: undefined,
  263. /** @type {string?} 工作路径 */
  264. workUri: undefined,
  265. /** @type {string?} 套接字URL */
  266. socketUrl: undefined
  267. },
  268. complet: {
  269. /** @type {boolean?} 是否启用C++代码补全模板 */
  270. cppCodeTemplate: undefined,
  271. /** @type {Object?} 自定义配置 */
  272. customConfig: undefined
  273. },
  274. /** @type {Object?} Monaco编辑器实例 */
  275. editor: null,
  276. /** @type {string?} 在线编译器选择 */
  277. onlineCompilerChoice: undefined,
  278. /** @type {string?} 编译器选择 */
  279. compilerSelection: undefined,
  280. setting: {
  281. /** @type {Array?} 语言设置数组 */
  282. language: [],
  283. /** @type {string?} 位置 */
  284. position: undefined,
  285. /** @type {boolean} 位置初始化标志 */
  286. position_initialized: false,
  287. /** @type {number?} 字体大小 */
  288. fontsize: undefined,
  289. /** @type {boolean?} 鼠标滚动锁定 */
  290. alwaysConsumeMouseWheel: undefined,
  291. /** @type {boolean?} 提交代码二次确认 */
  292. isCodeSubmitDoubleConfirm: undefined,
  293. /** @type {string?} 提交按钮位置 */
  294. submitButtonPosition: undefined
  295. }
  296. };
  297.  
  298. /**
  299. * @namespace deepl
  300. * @desc DeepL翻译服务配置。
  301. * @memberof OJBetter
  302. */
  303. OJBetter.deepl = {
  304. /** @type {Object?} DeepL配置对象 */
  305. configs: undefined,
  306. config: {
  307. /** @type {string?} 类型 */
  308. type: undefined,
  309. /** @type {string?} 名称 */
  310. name: undefined,
  311. /** @type {string?} API类型 */
  312. apiGenre: undefined,
  313. /** @type {string?} API密钥 */
  314. key: undefined,
  315. /** @type {string?} 代理 */
  316. proxy: undefined,
  317. /** @type {Object?} 额外请求头 */
  318. header: undefined,
  319. /** @type {Object?} 额外请求数据 */
  320. data: undefined,
  321. quota: {
  322. /** @type {string?} 余额URL */
  323. url: undefined,
  324. /** @type {string?} 余额请求方法 */
  325. method: undefined,
  326. /** @type {Object?} 余额请求头 */
  327. header: undefined,
  328. /** @type {Object?} 余额请求数据 */
  329. data: undefined,
  330. /** @type {number?} 剩余配额 */
  331. surplus: undefined
  332. }
  333. },
  334. /** @type {boolean?} 启用重点保护 */
  335. enableEmphasisProtection: undefined,
  336. /** @type {boolean?} 启用链接保护 */
  337. enableLinkProtection: undefined
  338. };
  339.  
  340. /**
  341. * @namespace chatgpt
  342. * @desc ChatGPT服务配置。
  343. * @memberof OJBetter
  344. */
  345. OJBetter.chatgpt = {
  346. /** @type {Object?} ChatGPT配置对象 */
  347. configs: undefined,
  348. config: {
  349. /** @type {string?} 名称 */
  350. name: undefined,
  351. /** @type {string?} 模型 */
  352. model: undefined,
  353. /** @type {string?} API密钥 */
  354. key: undefined,
  355. /** @type {string?} 代理 */
  356. proxy: undefined,
  357. /** @type {Object?} 额外请求头 */
  358. header: undefined,
  359. /** @type {Object?} 额外请求数据 */
  360. data: undefined,
  361. quota: {
  362. /** @type {string?} 余额URL */
  363. url: undefined,
  364. /** @type {string?} 余额请求方法 */
  365. method: undefined,
  366. /** @type {Object?} 余额请求头 */
  367. header: undefined,
  368. /** @type {Object?} 余额请求数据 */
  369. data: undefined,
  370. /** @type {number?} 剩余配额 */
  371. surplus: undefined
  372. }
  373. },
  374. /** @type {boolean?} 是否为流式传输 */
  375. isStream: undefined
  376. };
  377.  
  378. /**
  379. * @namespace preference
  380. * @desc 偏好设置
  381. * @memberof OJBetter
  382. */
  383. OJBetter.preference = {
  384. /** @type {boolean?} 是否显示加载动画 */
  385. showLoading: undefined,
  386. /** @type {boolean?} 是否显示悬停目标区域 */
  387. hoverTargetAreaDisplay: undefined,
  388. /** @type {string?} 按钮图标大小 */
  389. iconButtonSize: undefined,
  390. };
  391.  
  392. /**
  393. * @namespace about
  394. * @desc 关于页信息
  395. * @memberof OJBetter
  396. */
  397. OJBetter.about = {
  398. /** @type {string?} 更新通道 */
  399. updateChannel: undefined,
  400. /** @type {string?} 更新源 */
  401. updateSource: undefined
  402. };
  403.  
  404. /**
  405. * @namespace supportList
  406. * @desc 支持列表
  407. * @memberof OJBetter
  408. */
  409. OJBetter.supportList = {
  410. /** @type {object} 翻译支持列表和对应语言代码*/
  411. translationSupport: {
  412. 'deepl': { 'zh': 'ZH', 'de': 'DE', 'fr': 'FR', 'ko': 'KO', 'pt': 'PT', 'ja': 'JA', 'es': 'ES', 'it': 'IT' },
  413. 'iflyrec': { 'zh': '1' },
  414. 'youdao': { 'zh': 'AUTO' },
  415. 'google': { 'zh': 'zh-CN', 'zh-Hant': 'zh-TW', 'de': 'de', 'fr': 'fr', 'ko': 'ko', 'pt': 'pt', 'ja': 'ja', 'es': 'es', 'it': 'it', 'hi': 'hi' },
  416. 'caiyun': { 'zh': 'auto2zh', 'ja': 'auto2ja', 'ko': 'auto2ko', 'es': 'auto2es', 'fr': 'auto2fr' },
  417. 'openai': { 'zh': '中文', 'zh-Hant': '繁體中文', 'de': 'Deutsch', 'fr': 'Français', 'ko': '한국어', 'pt': 'Português', 'ja': '日本語', 'es': 'Español', 'it': 'Italiano', 'hi': 'हिन्दी' }
  418. },
  419. /** @type {object} 更新源支持列表*/
  420. updateSourceSupportList: {
  421. 'greasyfork': {
  422. 'release': true,
  423. 'dev': false
  424. },
  425. 'github': {
  426. 'release': true,
  427. 'dev': true
  428. },
  429. 'aliyunoss': {
  430. 'release': true,
  431. 'dev': true
  432. }
  433. }
  434. }
  435.  
  436. // ------------------------------
  437. // 一些工具函数
  438. // ------------------------------
  439.  
  440. /**
  441. * 将数字或者字符串解析为数字。
  442. * @memberof OJBetter.common
  443. * @param {string} val 要解析的字符串
  444. * @param {boolean} [strict=false] 是否进行严格类型检查
  445. * @returns {number} 解析结果
  446. * @throws {Error} 如果解析失败,则抛出错误
  447. */
  448. const OJB_parseNumber = (val, strict = false) => {
  449. const num = Number(val);
  450. if (isNaN(num) || (strict && val.toString() !== num.toString())) {
  451. throw new Error('Invalid number');
  452. }
  453. return num;
  454. };
  455.  
  456. /**
  457. * 将字符串解析为布尔值
  458. * @param {string} val - 要解析的字符串
  459. * @param {boolean} strict - 是否进行严格类型检查
  460. * @returns {boolean} - 解析结果
  461. * @throws {Error} - 如果解析失败,则抛出错误
  462. */
  463. const OJB_parseBoolean = (val, strict) => {
  464. if (strict) {
  465. if (val === true || val === false) return val;
  466. throw new Error('Invalid boolean');
  467. }
  468. return val === 'true' ? true : val === 'false' ? false : val;
  469. };
  470.  
  471. /**
  472. * 将字符串解析为对象
  473. * @param {string} val - 要解析的字符串
  474. * @returns {Object} - 解析结果
  475. * @throws {Error} - 如果解析失败,则抛出错误
  476. */
  477. const OJB_parseObject = val => {
  478. try {
  479. return JSON.parse(val);
  480. } catch {
  481. throw new Error('Invalid JSON');
  482. }
  483. };
  484.  
  485. /**
  486. * 将字符串解析为键值对数组
  487. * @param {string} val - 要解析的字符串
  488. * @returns {Object[]} - 解析结果
  489. * @throws {Error} - 如果解析失败,则抛出错误
  490. */
  491. const OJB_parseLinePairArray = val => {
  492. if (typeof val !== 'string' || val.trim() === '') return [];
  493. return val.split("\n").filter(line => line.trim() !== '').map(line => {
  494. const indexOfFirstColon = line.indexOf(":");
  495. if (indexOfFirstColon === -1) throw new Error('Invalid LinePairArray format: ":" is missing');
  496. const key = line.substring(0, indexOfFirstColon).trim();
  497. const value = line.substring(indexOfFirstColon + 1).trim();
  498. return { [key]: value };
  499. });
  500. };
  501.  
  502. /**
  503. * 获取对象中指定路径表达式的值
  504. * @param {Object} obj - 要计算的对象
  505. * @param {string} pathOrExpression - 要计算的路径表达式
  506. * @returns {any} - 计算结果
  507. * @example
  508. * const obj = {
  509. * "a": {
  510. * "b": 1
  511. * },
  512. * "c": 2
  513. * };
  514. * evaluatePathOrExpression(obj, "a.b"); // 1
  515. * evaluatePathOrExpression(obj, "a.b + c"); // 3
  516. * evaluatePathOrExpression(obj, "a.b + a.c"); // 1
  517. */
  518. function OJB_evaluatePathOrExpression(obj, pathOrExpression) {
  519. const hasOperator = /[\+\-\*\/]/.test(pathOrExpression);
  520. const getPathValue = (obj, path) => {
  521. return path.split('.').reduce((acc, part) => {
  522. return acc !== undefined && acc !== null && acc.hasOwnProperty(part) ? acc[part] : undefined;
  523. }, obj);
  524. };
  525. const evaluateExpression = (obj, expression) => {
  526. const tokens = expression.split(/([\+\-\*\/])/).map(token => token.trim());
  527. const values = tokens.map(token => {
  528. if (/[\+\-\*\/]/.test(token)) {
  529. return token;
  530. } else {
  531. const value = getPathValue(obj, token);
  532. return value !== undefined ? value : 0;
  533. }
  534. });
  535. const evaluatedExpression = values.join(' ');
  536. try {
  537. return Function(`'use strict'; return (${evaluatedExpression});`)();
  538. } catch (e) {
  539. console.error('Expression evaluation error:', e);
  540. return undefined;
  541. }
  542. };
  543. return hasOperator ? evaluateExpression(obj, pathOrExpression) : getPathValue(obj, pathOrExpression);
  544. }
  545.  
  546. /**
  547. * 获取 GM 存储的值并根据类型进行处理
  548. * @param {string} key - 要检索的值的键。
  549. * @param {any} defaultValue - 如果值未找到,则返回的默认值。
  550. * @param {Object} [options={}] - 配置选项对象。
  551. * @param {string} [options.type='string'] - 期望的值的类型。可选值:'string', 'number', 'boolean', 'object', 'array', 'linePairArray'。
  552. * @param {boolean} [options.strict=false] - 用于数字和布尔类型,表示是否进行严格类型检查。
  553. * @param {string} [options.pathOrExpression=''] - 用于对象或数组类型,表示路径表达式或获取元素的索引。
  554. * @returns {any} - 检索到的值。
  555. */
  556. const OJB_getGMValue = (key, defaultValue, { type = 'string', strict = false, pathOrExpression = '' } = {}) => {
  557. let value = GM_getValue(key);
  558. if (value === undefined || value === null || value === "") {
  559. GM_setValue?.(key, defaultValue);
  560. return defaultValue;
  561. }
  562.  
  563. const parsers = {
  564. string: val => val,
  565. number: (val) => OJB_parseNumber(val, strict),
  566. boolean: (val) => OJB_parseBoolean(val, strict),
  567. object: OJB_parseObject,
  568. array: OJB_parseObject,
  569. linePairArray: OJB_parseLinePairArray
  570. };
  571.  
  572. if (!(type in parsers)) {
  573. console.error(`Unsupported type: ${type}`);
  574. return defaultValue;
  575. }
  576.  
  577. try {
  578. value = parsers[type](value);
  579. } catch (e) {
  580. console.error('Error:', e.message);
  581. return defaultValue;
  582. }
  583.  
  584. // The pathOrExpression processing is not applicable to linePairArray type
  585. if ((type === 'object' || type === 'array') && pathOrExpression) {
  586. const evaluated = OJB_evaluatePathOrExpression(value, pathOrExpression);
  587. if (evaluated === undefined) {
  588. console.error('Path or expression evaluation returned undefined');
  589. return defaultValue;
  590. }
  591. value = evaluated;
  592. }
  593.  
  594. return value;
  595. };
  596.  
  597. /**
  598. * 版本号比较方法
  599. * @param {string} version1 版本号1
  600. * @param {string} version2 版本号2
  601. * @returns {number} -1: version1 < version2, 0: version1 = version2, 1: version1 > version2
  602. */
  603. const OJB_compareVersions = function (version1 = "0", version2 = "0") {
  604. const v1Array = version1.split(".").map(Number);
  605. const v2Array = version2.split(".").map(Number);
  606. const length = Math.max(v1Array.length, v2Array.length);
  607. for (let i = 0; i < length; i++) {
  608. const diff = (v1Array[i] || 0) - (v2Array[i] || 0);
  609. if (diff) return Math.sign(diff);
  610. }
  611. return 0;
  612. }
  613.  
  614. /**
  615. * 获取上一个主版本号
  616. * @param {string} currentVersion 当前版本号
  617. * @returns {string} 上一个主版本号
  618. */
  619. const OJB_getPreviousVersion = function (currentVersion) {
  620. const versionArray = currentVersion.split(".").map(Number);
  621. let lastNonZeroIndex = versionArray.length - 1;
  622. while (lastNonZeroIndex >= 0 && versionArray[lastNonZeroIndex] === 0) {
  623. lastNonZeroIndex--;
  624. }
  625. if (lastNonZeroIndex >= 0) {
  626. versionArray[lastNonZeroIndex]--;
  627. for (let i = lastNonZeroIndex + 1; i < versionArray.length; i++) {
  628. versionArray[i] = 0;
  629. }
  630. }
  631. return versionArray.join(".");
  632. };
  633.  
  634. /**
  635. * 初始化全局变量
  636. */
  637. async function initVar() {
  638. const { hostname, href } = window.location;
  639. OJBetter.state.lastAnnounceVer = OJB_getGMValue("lastAnnounceVer", "0");
  640. OJBetter.state.lastReadAnnounceVer = OJB_getGMValue("lastReadAnnounceVer", "0");
  641. OJBetter.typeOfPage.is_mSite = /^m[0-9]/.test(hostname);
  642. OJBetter.typeOfPage.is_oldLatex = $('.tex-span').length;
  643. OJBetter.typeOfPage.is_acmsguru = href.includes("acmsguru") && href.includes('/problem/');
  644. OJBetter.typeOfPage.is_contest = /\/contest\/[\d\/\s]+$/.test(href) && !href.includes('/problem/');
  645. OJBetter.typeOfPage.is_problem = href.includes('/problem/');
  646. OJBetter.typeOfPage.is_completeProblemset = /problems\/?$/.test(href);
  647. OJBetter.typeOfPage.is_problemset_problem = href.includes('/problemset/') && href.includes('/problem/');
  648. OJBetter.typeOfPage.is_problemset = href.includes('/problemset') && !href.includes('/problem/');
  649. OJBetter.typeOfPage.is_submitPage = href.includes('/submit');
  650. OJBetter.typeOfPage.is_cfStandings = href.includes('/standings') &&
  651. $('.standings tr:first th:nth-child(n+5)')
  652. .map(function () {
  653. return $(this).find('span').text();
  654. })
  655. .get()
  656. .every(score => /^[0-9]+$/.test(score));
  657. OJBetter.localization.websiteLang = OJB_getGMValue("localizationLanguage", "zh");
  658. OJBetter.localization.scriptLang = OJB_getGMValue("scriptL10nLanguage", "zh");
  659. OJBetter.basic.renderPerfOpt = OJB_getGMValue("renderPerfOpt", false);
  660. OJBetter.basic.commentPaging = OJB_getGMValue("commentPaging", true);
  661. OJBetter.basic.showJumpToLuogu = OJB_getGMValue("showJumpToLuogu", true);
  662. OJBetter.basic.standingsRecolor = OJB_getGMValue("standingsRecolor", true);
  663. OJBetter.state.notWaiteLoaded = OJB_getGMValue("notWaiteLoaded", false);
  664. OJBetter.translation.targetLang = OJB_getGMValue("transTargetLang", "zh");
  665. OJBetter.translation.choice = OJB_getGMValue("translation", "deepl");
  666. OJBetter.translation.comment.transMode = OJB_getGMValue("commentTranslationMode", "0");
  667. OJBetter.translation.comment.choice = OJB_getGMValue("commentTranslationChoice", "0");
  668. OJBetter.translation.memory.enabled = OJB_getGMValue("memoryTranslateHistory", true);
  669. OJBetter.translation.auto.enabled = OJB_getGMValue("autoTranslation", false);
  670. OJBetter.translation.auto.shortTextLength = OJB_getGMValue("shortTextLength", "2000");
  671. OJBetter.translation.retransAction = OJB_getGMValue("retransAction", "0");
  672. OJBetter.translation.waitTime = OJB_getGMValue("transWaitTime", "200");
  673. OJBetter.translation.auto.mixTrans.enabled = OJB_getGMValue("allowMixTrans", true);
  674. OJBetter.translation.auto.mixTrans.servers = OJB_getGMValue("mixedTranslation", ['deepl', 'iflyrec', 'youdao', 'caiyun']);
  675. OJBetter.common.taskQueue = new TaskQueue();
  676. OJBetter.translation.replaceSymbol = OJB_getGMValue("replaceSymbol", "2");
  677. OJBetter.translation.filterTextWithoutEmphasis = OJB_getGMValue("filterTextWithoutEmphasis", false);
  678. OJBetter.clist.enabled.contest = OJB_getGMValue("showClistRating_contest", false);
  679. OJBetter.clist.enabled.problem = OJB_getGMValue("showClistRating_problem", false);
  680. OJBetter.clist.enabled.problemset = OJB_getGMValue("showClistRating_problemset", false);
  681. OJBetter.clist.ratingHidden = OJB_getGMValue("RatingHidden", false);
  682. OJBetter.clist.authorization = OJB_getGMValue("clist_Authorization", "");
  683. //deepl
  684. OJBetter.deepl.config.type = OJB_getGMValue("deepl_type", "free");
  685. OJBetter.deepl.configs = OJB_getGMValue("deepl_config", {
  686. "choice": "",
  687. "configurations": []
  688. });
  689. if (OJBetter.deepl.configs.choice !== "" && OJBetter.deepl.configs.configurations.length !== 0) {
  690. const choice = OJBetter.deepl.configs.choice;
  691. const configuration = OJBetter.deepl.configs.configurations.find(obj => obj.name === choice);;
  692. if (configuration == undefined) {
  693. let existingConfig = GM_getValue('deepl_config');
  694. existingConfig.choice = "";
  695. GM_setValue('deepl_config', existingConfig);
  696. location.reload();
  697. }
  698. OJBetter.deepl.config.name = configuration.name;
  699. OJBetter.deepl.config.apiGenre = configuration.apiGenre;
  700. OJBetter.deepl.config.key = configuration.key;
  701. OJBetter.deepl.config.proxy = configuration.proxy;
  702. OJBetter.deepl.config.header = OJB_parseLinePairArray(configuration._header);
  703. OJBetter.deepl.config.data = OJB_parseLinePairArray(configuration._data);
  704. OJBetter.deepl.config.quota.url = configuration.quota_url;
  705. OJBetter.deepl.config.quota.method = configuration.quota_method;
  706. OJBetter.deepl.config.quota.header = OJB_parseLinePairArray(configuration.quota_header);
  707. OJBetter.deepl.config.quota.data = OJB_parseLinePairArray(configuration.quota_data);
  708. OJBetter.deepl.config.quota.surplus = configuration.quota_surplus;
  709. }
  710. OJBetter.deepl.enableEmphasisProtection = OJB_getGMValue("enableEmphasisProtection", true);
  711. OJBetter.deepl.enableLinkProtection = OJB_getGMValue("enableLinkProtection", true);
  712. //openai
  713. OJBetter.chatgpt.isStream = OJB_getGMValue("openai_isStream", true);
  714. OJBetter.chatgpt.configs = OJB_getGMValue("chatgpt_config", {
  715. "choice": "",
  716. "configurations": []
  717. });
  718. if (OJBetter.chatgpt.configs.choice !== "" && OJBetter.chatgpt.configs.configurations.length !== 0) {
  719. const choice = OJBetter.chatgpt.configs.choice;
  720. const configuration = OJBetter.chatgpt.configs.configurations.find(obj => obj.name === choice);;
  721. if (configuration == undefined) {
  722. let existingConfig = GM_getValue('chatgpt_config');
  723. existingConfig.choice = "";
  724. GM_setValue('chatgpt_config', existingConfig);
  725. location.reload();
  726. }
  727. OJBetter.chatgpt.config.name = configuration.name;
  728. OJBetter.chatgpt.config.model = configuration.model;
  729. OJBetter.chatgpt.config.key = configuration.key;
  730. OJBetter.chatgpt.config.proxy = configuration.proxy;
  731. OJBetter.chatgpt.config.header = OJB_parseLinePairArray(configuration._header);
  732. OJBetter.chatgpt.config.data = OJB_parseLinePairArray(configuration._data);
  733. OJBetter.chatgpt.config.quota.url = configuration.quota_url;
  734. OJBetter.chatgpt.config.quota.method = configuration.quota_method;
  735. OJBetter.chatgpt.config.quota.header = OJB_parseLinePairArray(configuration.quota_header);
  736. OJBetter.chatgpt.config.quota.data = OJB_parseLinePairArray(configuration.quota_data);
  737. OJBetter.chatgpt.config.quota.surplus = configuration.quota_surplus;
  738. }
  739. // 编辑器
  740. if (!OJBetter.typeOfPage.is_mSite) OJBetter.common.cf_csrf_token = Codeforces.getCsrfToken();
  741. else OJBetter.common.cf_csrf_token = "";
  742. OJBetter.monaco.compilerSelection = OJB_getGMValue("compilerSelection", "61");
  743. OJBetter.monaco.setting.fontsize = OJB_getGMValue("editorFontSize", "15");
  744. OJBetter.monaco.enableOnProblemPage = OJB_getGMValue("problemPageCodeEditor", true);
  745. OJBetter.monaco.complet.cppCodeTemplate = OJB_getGMValue("cppCodeTemplateComplete", true);
  746. OJBetter.monaco.onlineCompilerChoice = OJB_getGMValue("onlineCompilerChoice", "official");
  747. OJBetter.monaco.setting.isCodeSubmitDoubleConfirm = OJB_getGMValue("isCodeSubmitConfirm", true);
  748. OJBetter.monaco.setting.alwaysConsumeMouseWheel = OJB_getGMValue("alwaysConsumeMouseWheel", true);
  749. OJBetter.monaco.setting.submitButtonPosition = OJB_getGMValue("submitButtonPosition", "bottom");
  750. //自定义补全
  751. OJBetter.monaco.complet.customConfig = OJB_getGMValue("Complet_config", {
  752. "choice": -1,
  753. "configurations": []
  754. });
  755. /**
  756. * 加载monaco编辑器资源
  757. */
  758. OJBetter.monaco.lsp.enabled = OJB_getGMValue("useLSP", false);
  759. OJBetter.monaco.setting.position = OJB_getGMValue("monacoEditor_position", "initial");
  760. OJBetter.monaco.lsp.workUri = OJB_getGMValue("OJBetter_Bridge_WorkUri", "C:/OJBetter_Bridge");
  761. OJBetter.monaco.lsp.socketUrl = OJB_getGMValue("OJBetter_Bridge_SocketUrl", "ws://127.0.0.1:2323/");
  762. if (OJBetter.monaco.enableOnProblemPage) {
  763. let monacoLoader = document.createElement("script");
  764. monacoLoader.src = "https://cdn.staticfile.org/monaco-editor/0.44.0/min/vs/loader.min.js";
  765. document.head.prepend(monacoLoader);
  766. monacoLoader.onload = () => {
  767. require.config({
  768. paths: { vs: "https://cdn.staticfile.org/monaco-editor/0.44.0/min/vs" },
  769. "vs/nls": { availableLanguages: { "*": "zh-cn" } },
  770. });
  771. require(["vs/editor/editor.main"], () => {
  772. OJBetter.monaco.loaderOnload = true;
  773. });
  774. }
  775. }
  776. OJBetter.preference.showLoading = OJB_getGMValue("showLoading", true);
  777. OJBetter.preference.hoverTargetAreaDisplay = OJB_getGMValue("hoverTargetAreaDisplay", false);
  778. OJBetter.basic.expandFoldingblocks = OJB_getGMValue("expandFoldingblocks", true);
  779. OJBetter.preference.iconButtonSize = OJB_getGMValue("iconButtonSize", "16");
  780. OJBetter.about.updateChannel = OJB_getGMValue("updateChannel", "release");
  781. OJBetter.about.updateSource = OJB_getGMValue("updateSource", "greasyfork");
  782. }
  783.  
  784. /**
  785. * 显示警告消息
  786. */
  787. function showWarnMessage() {
  788. if (OJBetter.typeOfPage.is_oldLatex) {
  789. const loadingMessage = new LoadingMessage();
  790. loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('warning.is_oldLatex', { ns: 'alert' })}`, 'warning');
  791. }
  792. if (OJBetter.typeOfPage.is_acmsguru) {
  793. const loadingMessage = new LoadingMessage();
  794. loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('warning.is_acmsguru', { ns: 'alert' })}`, 'warning');
  795. }
  796. if (OJBetter.translation.comment.transMode == "1") {
  797. const loadingMessage = new LoadingMessage();
  798. loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('warning.trans_segment', { ns: 'alert' })}`, 'warning');
  799. }
  800. if (OJBetter.translation.comment.transMode == "2") {
  801. const loadingMessage = new LoadingMessage();
  802. loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('warning.trans_select', { ns: 'alert' })}`, 'warning');
  803. }
  804. if (OJBetter.typeOfPage.is_submitPage && OJBetter.monaco.enableOnProblemPage) {
  805. const loadingMessage = new LoadingMessage();
  806. loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('warning.is_submitPage', { ns: 'alert' })}`, 'warning');
  807. }
  808. }
  809.  
  810. // 常量
  811. 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>';
  812. 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>`;
  813. 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
  814. 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>`;
  815. 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" />
  816. <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" />
  817. <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>`;
  818.  
  819. /**
  820. * 连接数据库
  821. */
  822. async function initDB() {
  823. OJBetter.common.database = new Dexie('CFBetterDB');
  824. OJBetter.common.database.version(3).stores({
  825. samplesData: '&url',
  826. editorCode: '&url',
  827. translateData: '&url',
  828. localizeSubsData: '&lang'
  829. });
  830.  
  831. // 等待数据库打开
  832. await OJBetter.common.database.open();
  833. }
  834.  
  835. /**
  836. * 清空数据库
  837. */
  838. async function clearDatabase() {
  839. const isConfirmed = await OJB_createDialog(
  840. i18next.t('isClearDatabase.title', { ns: 'dialog' }),
  841. i18next.t('isClearDatabase.content', { ns: 'dialog' }),
  842. [
  843. i18next.t('isClearDatabase.buttons.0', { ns: 'dialog' }),
  844. i18next.t('isClearDatabase.buttons.1', { ns: 'dialog' })
  845. ]
  846. );
  847. if (!isConfirmed) {
  848. try {
  849. // 开启一个读写事务,包含数据库中的所有表
  850. await OJBetter.common.database.transaction('rw', OJBetter.common.database.tables, async () => {
  851. // 遍历所有表
  852. for (const table of OJBetter.common.database.tables) {
  853. // 清空当前表
  854. await table.clear();
  855. }
  856. });
  857. console.log("All tables in the database have been cleared.");
  858. alert("All tables in the database have been cleared.");
  859. } catch (error) {
  860. console.error("Error clearing the database:", error);
  861. }
  862. }
  863. }
  864.  
  865. /**
  866. * 导出数据库
  867. * @returns {Promise<string>} 数据库的JSON字符串
  868. */
  869. async function exportDatabase() {
  870. try {
  871. // 创建一个存储数据的对象
  872. const exportData = {};
  873. // 获取数据库中所有表的名称
  874. const tableNames = OJBetter.common.database.tables.map(table => table.name);
  875.  
  876. // 遍历每一个表,获取数据
  877. for (const tableName of tableNames) {
  878. const tableData = await OJBetter.common.database.table(tableName).toArray();
  879. exportData[tableName] = tableData;
  880. }
  881.  
  882. // 将数据对象转换为JSON字符串
  883. const jsonData = JSON.stringify(exportData, null, 4);
  884. return jsonData;
  885. } catch (error) {
  886. console.error("Error exporting database:", error);
  887. }
  888. }
  889.  
  890. /**
  891. * 导入数据库
  892. * @param {string} jsonData 数据库的JSON字符串
  893. */
  894. async function importDatabase(jsonData) {
  895. const isConfirmed = await OJB_createDialog(
  896. i18next.t('isImportDatabase.title', { ns: 'dialog' }),
  897. i18next.t('isImportDatabase.content', { ns: 'dialog' }),
  898. [
  899. i18next.t('isImportDatabase.buttons.0', { ns: 'dialog' }),
  900. i18next.t('isImportDatabase.buttons.1', { ns: 'dialog' })
  901. ]
  902. );
  903. if (!isConfirmed) {
  904. try {
  905. // 将JSON字符串解析为对象
  906. const importData = JSON.parse(jsonData);
  907.  
  908. // 开启一个事务,并清空现有数据
  909. await OJBetter.common.database.transaction('rw', OJBetter.common.database.tables, async () => {
  910. // 清空所有表的数据
  911. for (const tableName of OJBetter.common.database.tables.map(table => table.name)) {
  912. await OJBetter.common.database.table(tableName).clear();
  913. }
  914.  
  915. // 插入新数据
  916. for (const [tableName, rows] of Object.entries(importData)) {
  917. await OJBetter.common.database.table(tableName).bulkAdd(rows);
  918. }
  919. });
  920. alert("Data imported successfully");
  921. } catch (error) {
  922. console.error("Error importing database:", error);
  923. }
  924. }
  925. }
  926.  
  927. /**
  928. * 将数据下载为文件
  929. * @param {string} data 数据
  930. * @param {string} filename 文件名,默认为'export.json'
  931. * @param {string} fileType 文件MIME类型,默认为'application/json'
  932. * @returns {void}
  933. */
  934. function downloadDataAsFile(data, filename = 'export.json', fileType = 'application/json') {
  935. // 创建一个blob对象,指定文件类型
  936. const blob = new Blob([data], { type: fileType });
  937. const url = URL.createObjectURL(blob);
  938.  
  939. // 创建一个隐藏的a标签,模拟点击进行下载
  940. const a = document.createElement('a');
  941. a.href = url;
  942. a.download = filename;
  943. document.body.appendChild(a);
  944. a.click();
  945.  
  946. // 清理
  947. document.body.removeChild(a);
  948. URL.revokeObjectURL(url);
  949. }
  950.  
  951.  
  952. /**
  953. * 从文件中读取数据
  954. * @param {Function} callback 回调函数
  955. * @returns {void}
  956. */
  957. function readFileInput(callback) {
  958. const fileInput = document.createElement('input');
  959. fileInput.type = 'file';
  960. fileInput.accept = '.json';
  961. fileInput.style.display = 'none'; // 隐藏input元素
  962.  
  963. fileInput.onchange = (e) => {
  964. const file = e.target.files[0];
  965. if (file) {
  966. const reader = new FileReader();
  967. reader.onload = (e) => {
  968. const fileContent = e.target.result;
  969. if (callback && typeof callback === 'function') {
  970. callback(fileContent); // 调用回调函数,传入文件内容
  971. }
  972. };
  973. reader.readAsText(file);
  974. }
  975. };
  976.  
  977. document.body.appendChild(fileInput);
  978. fileInput.click();
  979. document.body.removeChild(fileInput);
  980. }
  981.  
  982. /**
  983. * 删除所有设置
  984. */
  985. async function deleteAllConfigSettings() {
  986. const isConfirmed = await OJB_createDialog(
  987. i18next.t('isDeleteAllConfigSettings.title', { ns: 'dialog' }),
  988. i18next.t('isDeleteAllConfigSettings.content', { ns: 'dialog' }),
  989. [
  990. i18next.t('isDeleteAllConfigSettings.buttons.0', { ns: 'dialog' }),
  991. i18next.t('isDeleteAllConfigSettings.buttons.1', { ns: 'dialog' })
  992. ]
  993. );
  994. if (!isConfirmed) {
  995. const keys = GM_listValues();
  996.  
  997. keys.forEach(key => {
  998. GM_deleteValue(key);
  999. });
  1000.  
  1001. alert('All settings have been deleted.');
  1002. window.location.reload();
  1003. }
  1004. }
  1005.  
  1006. /**
  1007. * 导出设置到JSON
  1008. * @returns {string} JSON字符串
  1009. */
  1010. function exportSettingsToJSON() {
  1011. const keys = GM_listValues();
  1012. let settings = {};
  1013.  
  1014. keys.forEach(key => {
  1015. settings[key] = GM_getValue(key);
  1016. });
  1017.  
  1018. return JSON.stringify(settings, null, 4);
  1019. }
  1020.  
  1021. /**
  1022. * 从JSON导入设置
  1023. * @param {string} jsonData JSON字符串
  1024. * @returns {void}
  1025. */
  1026. async function importSettingsFromJSON(jsonData) {
  1027. const isConfirmed = await OJB_createDialog(
  1028. i18next.t('isImportSettings.title', { ns: 'dialog' }),
  1029. i18next.t('isImportSettings.content', { ns: 'dialog' }),
  1030. [
  1031. i18next.t('isImportSettings.buttons.0', { ns: 'dialog' }),
  1032. i18next.t('isImportSettings.buttons.1', { ns: 'dialog' })
  1033. ]
  1034. );
  1035. if (!isConfirmed) {
  1036. let settings;
  1037. try {
  1038. settings = JSON.parse(jsonData);
  1039. } catch (e) {
  1040. console.error('JSON parsing error:', e);
  1041. return;
  1042. }
  1043.  
  1044. Object.keys(settings).forEach(key => {
  1045. GM_setValue(key, settings[key]);
  1046. });
  1047.  
  1048. alert('Settings imported successfully!');
  1049. window.location.reload();
  1050. }
  1051. }
  1052.  
  1053. /**
  1054. * 加载元素本地化语言数据
  1055. * @param {JQuery} element jQuery元素
  1056. * @param {number} [retries=10] 重试次数
  1057. * @param {number} [interval=50] 重试间隔
  1058. */
  1059. function elementLocalize(element, retries = 10, interval = 50) {
  1060. if ($.isFunction(element.localize)) {
  1061. element.localize();
  1062. } else if (retries > 0) {
  1063. setTimeout(elementLocalize, interval, element, retries - 1, interval);
  1064. } else {
  1065. console.error('Unable to localize', element);
  1066. }
  1067. }
  1068.  
  1069. // 切换系统黑暗监听
  1070. const mediaQueryList = window.matchMedia('(prefers-color-scheme: dark)');
  1071. const changeEventListeners = [];
  1072. function handleColorSchemeChange(event) {
  1073. event.matches ? $('html').attr('data-theme', 'dark') : $('html').attr('data-theme', 'light');
  1074. if (!event.matches) {
  1075. var originalColor = $(this).data("original-color");
  1076. $(this).css("background-color", originalColor);
  1077. if (OJBetter.monaco.editor) {
  1078. monaco.editor.setTheme('vs');
  1079. }
  1080. } else {
  1081. if (OJBetter.monaco.editor) {
  1082. monaco.editor.setTheme('vs-dark');
  1083. }
  1084. }
  1085. }
  1086.  
  1087. /**
  1088. * 黑暗模式
  1089. */
  1090. (function setDark() {
  1091. /**
  1092. * 初始化
  1093. */
  1094. function setDarkTheme() {
  1095. const htmlElement = document.querySelector('html');
  1096. if (htmlElement) {
  1097. htmlElement.setAttribute('data-theme', 'dark');
  1098. } else {
  1099. setTimeout(setDarkTheme, 100);
  1100. }
  1101. }
  1102. OJBetter.basic.darkMode = OJB_getGMValue("darkMode", "follow")
  1103. if (OJBetter.basic.darkMode == "dark") {
  1104. setDarkTheme();
  1105. } else if (OJBetter.basic.darkMode == "follow") {
  1106. // 添加事件监听器
  1107. changeEventListeners.push(handleColorSchemeChange);
  1108. mediaQueryList.addEventListener('change', handleColorSchemeChange);
  1109.  
  1110. if (window.matchMedia('(prefers-color-scheme: dark)').matches) setDarkTheme();
  1111. }
  1112.  
  1113. GM_addStyle(`
  1114. /* 黑暗支持 */
  1115. html[data-theme=dark]:root {
  1116. color-scheme: light dark;
  1117. }
  1118. /* 文字颜色1 */
  1119. html[data-theme=dark] .title,html[data-theme=dark] .problem-statement,
  1120. html[data-theme=dark] .ttypography, html[data-theme=dark] .roundbox, html[data-theme=dark] .info,
  1121. html[data-theme=dark] .ttypography .bordertable, html[data-theme=dark] .ttypography .bordertable thead th,
  1122. html[data-theme=dark] .ttypography h1, html[data-theme=dark] .ttypography h2, html[data-theme=dark] .ttypography h3,
  1123. html[data-theme=dark] .ttypography h4, html[data-theme=dark] .ttypography h5, html[data-theme=dark] .ttypography h6
  1124. html[data-theme=dark] .datatable table, html[data-theme=dark] .problem-statement .sample-tests pre,
  1125. html[data-theme=dark] .alert-success, html[data-theme=dark] .alert-info, html[data-theme=dark] .alert-error,
  1126. html[data-theme=dark] .alert-warning, html[data-theme=dark] .markItUpEditor, html[data-theme=dark] #pageContent,
  1127. html[data-theme=dark] .ace-chrome .ace_gutter, html[data-theme=dark] .translate-problem-statement,
  1128. html[data-theme=dark] .setting-name, html[data-theme=dark] .OJBetter_setting_menu, html[data-theme=dark] .help_tip .tip_text,
  1129. html[data-theme=dark] textarea, html[data-theme=dark] .user-black, html[data-theme=dark] .comments label.show-archived,
  1130. html[data-theme=dark] .comments label.show-archived *, html[data-theme=dark] table,
  1131. html[data-theme=dark] #items-per-page, html[data-theme=dark] #pagBar, html[data-theme=dark] .OJBetter_setting_sidebar li a:link,
  1132. html[data-theme=dark] .popup .content{
  1133. color: #a0adb9 !important;
  1134. }
  1135. html[data-theme=dark] h1 a, html[data-theme=dark] h2 a, html[data-theme=dark] h3 a, html[data-theme=dark] h4 a{
  1136. color: #adbac7;
  1137. }
  1138. /* 文字颜色2 */
  1139. html[data-theme=dark] .contest-state-phase, html[data-theme=dark] .legendary-user-first-letter,
  1140. html[data-theme=dark] .lang-chooser,
  1141. html[data-theme=dark] .second-level-menu-list li a, html[data-theme=dark] #footer,
  1142. html[data-theme=dark] .ttypography .tt, html[data-theme=dark] select,
  1143. html[data-theme=dark] .roundbox .caption, html[data-theme=dark] .topic .title *,
  1144. html[data-theme=dark] .user-admin, html[data-theme=dark] .ojb_btn:hover,
  1145. html[data-theme=dark] .OJBetter_modal button, html[data-theme=dark] #OJBetter_statusBar,
  1146. html[data-theme=dark] #RunTestButton, html[data-theme=dark] #programTypeId, html[data-theme=dark] #addCustomTest,
  1147. html[data-theme=dark] #customTestBlock, html[data-theme=dark] .OJBetter_setting_list.alert_info{
  1148. color: #9099a3 !important;
  1149. }
  1150. /* 文字颜色3 */
  1151. html[data-theme=dark] .ojb_btn, html[data-theme=dark] #program-source-text-copy{
  1152. color: #6385a6;
  1153. }
  1154. html[data-theme=dark] input{
  1155. color: #6385a6 !important;
  1156. }
  1157. /* 文字颜色4 */
  1158. html[data-theme=dark] .ttypography .MathJax, html[data-theme=dark] .MathJax span{
  1159. color: #cbd6e2 !important;
  1160. }
  1161. /* 文字颜色 浅绿 */
  1162. html[data-theme=dark] #SubmitButton{
  1163. color: #43A047;
  1164. }
  1165. /* 链接颜色 */
  1166. html[data-theme=dark] a:link {
  1167. color: #3989c9;
  1168. }
  1169. html[data-theme=dark] a:visited {
  1170. color: #8590a6;
  1171. }
  1172. html[data-theme=dark] .menu-box a, html[data-theme=dark] .sidebox th a{
  1173. color: #9099a3 !important;
  1174. }
  1175. /* 按钮 */
  1176. html[data-theme=dark] .second-level-menu-list li.backLava {
  1177. border-radius: 6px;
  1178. overflow: hidden;
  1179. filter: invert(1) hue-rotate(.5turn);
  1180. }
  1181. html[data-theme=dark] input:hover{
  1182. background-color: #22272e !important;
  1183. }
  1184. /* 背景层次1 */
  1185. html[data-theme=dark] body, html[data-theme=dark] .ttypography .bordertable thead th,
  1186. html[data-theme=dark] .datatable table, html[data-theme=dark] .datatable .dark, html[data-theme=dark] li#add_button,
  1187. html[data-theme=dark] .problem-statement .sample-tests pre, html[data-theme=dark] .markItUpEditor,
  1188. html[data-theme=dark] .SumoSelect>.CaptionCont, html[data-theme=dark] .SumoSelect>.optWrapper,
  1189. html[data-theme=dark] .SumoSelect>.optWrapper.multiple>.options li.opt span i, html[data-theme=dark] .ace_scroller,
  1190. html[data-theme=dark] .OJBetter_setting_menu, html[data-theme=dark] .help_tip .tip_text, html[data-theme=dark] li#add_button:hover,
  1191. html[data-theme=dark] textarea, html[data-theme=dark] .state, html[data-theme=dark] .ace-chrome .ace_gutter-active-line,
  1192. html[data-theme=dark] .sidebar-menu ul li:hover, html[data-theme=dark] .sidebar-menu ul li.active,
  1193. html[data-theme=dark] .ojb_btn:hover,
  1194. html[data-theme=dark] .OJBetter_setting_sidebar li a.active, html[data-theme=dark] .OJBetter_setting_sidebar li,
  1195. html[data-theme=dark] .OJBetter_setting_menu::-webkit-scrollbar-track, html[data-theme=dark] .OJBetter_setting_content::-webkit-scrollbar-track,
  1196. html[data-theme=dark] .OJBetter_modal, html[data-theme=dark] .OJBetter_modal button:hover,
  1197. html[data-theme=dark] .popup .content, html[data-theme=dark] .file.input-view .text, html[data-theme=dark] .file.output-view .text,
  1198. html[data-theme=dark] .file.answer-view .text, html[data-theme=dark] .file.checker-comment-view .text,
  1199. html[data-theme=dark] .config_bar_list, html[data-theme=dark] #LSPLog,
  1200. html[data-theme=dark] .OJBetter_setting_menu .OJBetter_checkboxs,
  1201. html[data-theme=dark] .OJBetter_setting_menu .OJBetter_checkboxs input[type="checkbox"]::before,
  1202. html[data-theme=dark] .OJBetter_setting_menu a, html[data-theme=dark] .OJBetter_setting_menu .OJBetter_setting_list button:hover{
  1203. background-color: #22272e !important;
  1204. background-image: none;
  1205. }
  1206. /* 背景层次2 */
  1207. html[data-theme=dark] .roundbox, html[data-theme=dark] .roundbox .dark, html[data-theme=dark] .bottom-links,
  1208. html[data-theme=dark] .ojb_btn, html[data-theme=dark] .spoiler-content, html[data-theme=dark] input,
  1209. html[data-theme=dark] .problem-statement .test-example-line-even, html[data-theme=dark] .highlight-blue,
  1210. html[data-theme=dark] .ttypography .tt, html[data-theme=dark] select,
  1211. html[data-theme=dark] .alert-success, html[data-theme=dark] .alert-info, html[data-theme=dark] .alert-error,
  1212. html[data-theme=dark] .alert-warning, html[data-theme=dark] .SumoSelect>.optWrapper>.options li.opt:hover,
  1213. html[data-theme=dark] .translate-problem-statement-panel,
  1214. html[data-theme=dark] .aceEditorTd, html[data-theme=dark] .ace-chrome .ace_gutter,
  1215. html[data-theme=dark] .translate-problem-statement, html[data-theme=dark] .datatable,
  1216. html[data-theme=dark] .OJBetter_setting_list,
  1217. html[data-theme=dark] .OJBetter_setting_menu hr,
  1218. html[data-theme=dark] .highlighted-row td, html[data-theme=dark] .highlighted-row th,
  1219. html[data-theme=dark] .pagination span.active, html[data-theme=dark] .OJBetter_setting_sidebar li a,
  1220. html[data-theme=dark] .OJBetter_setting_menu::-webkit-scrollbar-thumb, html[data-theme=dark] .OJBetter_setting_content::-webkit-scrollbar-thumb,
  1221. html[data-theme=dark] .OJBetter_modal button, html[data-theme=dark] .test-for-popup pre,
  1222. html[data-theme=dark] .popup .content pre, html[data-theme=dark] .popup .content pre code,
  1223. html[data-theme=dark] ul.config_bar_ul::-webkit-scrollbar-thumb, html[data-theme=dark] #OJBetter_statusBar,
  1224. html[data-theme=dark] #RunTestButton, html[data-theme=dark] #programTypeId, html[data-theme=dark] .sampleDiv,
  1225. html[data-theme=dark] #addCustomTest, html[data-theme=dark] #LSPLog li:nth-child(odd),
  1226. html[data-theme=dark] .OJBetter_setting_menu .OJBetter_checkboxs input[type="checkbox"]:checked::before,
  1227. html[data-theme=dark] .config::before, html[data-theme=dark] .config li.tempConfig_add_button:hover,
  1228. html[data-theme=dark] .OJBetter_setting_menu details, html[data-theme=dark] #config_bar_menu,
  1229. html[data-theme=dark] .OJBetter_setting_menu .OJBetter_setting_list button{
  1230. background-color: #2d333b !important;
  1231. }
  1232. /* 实线边框颜色-圆角 */
  1233. html[data-theme=dark] .roundbox, html[data-theme=dark] .roundbox .rtable td,
  1234. html[data-theme=dark] .ojb_btn, html[data-theme=dark] .sidebar-menu ul li,
  1235. html[data-theme=dark] input, html[data-theme=dark] .ttypography .tt, html[data-theme=dark] #items-per-page,
  1236. html[data-theme=dark] .datatable td, html[data-theme=dark] .datatable th,
  1237. html[data-theme=dark] .alert-success, html[data-theme=dark] .alert-info, html[data-theme=dark] .alert-error,
  1238. html[data-theme=dark] .alert-warning, html[data-theme=dark] .translate-problem-statement,
  1239. html[data-theme=dark] textarea, html[data-theme=dark] .input-output-copier{
  1240. border: 1px solid #424b56 !important;
  1241. border-radius: 2px;
  1242. }
  1243. /* 实线边框颜色-无圆角 */
  1244. html[data-theme=dark] .OJBetter_setting_list, html[data-theme=dark] .config_bar_list,
  1245. html[data-theme=dark] label.config_bar_ul_li_text, html[data-theme=dark] .problem-statement .sample-tests .input,
  1246. html[data-theme=dark] .problem-statement .sample-tests .output, html[data-theme=dark] .pagination span.active,
  1247. html[data-theme=dark] .OJBetter_setting_sidebar li, html[data-theme=dark] .OJBetter_setting_menu select,
  1248. html[data-theme=dark] .translate-problem-statement-panel, html[data-theme=dark] .OJBetter_modal button,
  1249. html[data-theme=dark] .test-for-popup pre, html[data-theme=dark] #OJBetter_editor, html[data-theme=dark] #OJBetter_statusBar,
  1250. html[data-theme=dark] #RunTestButton, html[data-theme=dark] #programTypeId, html[data-theme=dark] #customTestBlock,
  1251. html[data-theme=dark] #addCustomTest,
  1252. html[data-theme=dark] #CompilerSetting select, html[data-theme=dark] #CompilerSetting textarea, html[data-theme=dark] #CompilerBox,
  1253. html[data-theme=dark] .OJBetter_setting_menu .OJBetter_checkboxs, html[data-theme=dark] .OJBetter_setting_menu a,
  1254. html[data-theme=dark] .help_tip .tip_text, html[data-theme=dark] .config::before,
  1255. html[data-theme=dark] #statePanel, html[data-theme=dark] .test-case{
  1256. border: 1px solid #424b56 !important;
  1257. }
  1258. html[data-theme=dark] .roundbox .titled, html[data-theme=dark] .roundbox .rtable th {
  1259. border-bottom: 1px solid #424b56 !important;
  1260. }
  1261. html[data-theme=dark] .roundbox .bottom-links, html[data-theme=dark] #footer, html[data-theme=dark] #customTestBlock #customTests{
  1262. border-top: 1px solid #424b56 !important;
  1263. }
  1264. html[data-theme=dark] .topic .content {
  1265. border-left: 4px solid #424b56 !important;
  1266. }
  1267. html[data-theme=dark] .OJBetter_setting_sidebar {
  1268. border-right: 1px solid #424b56 !important;
  1269. }
  1270. html[data-theme=dark] hr {
  1271. border-color: #424b56 !important;
  1272. }
  1273. /* 虚线边框颜色 */
  1274. html[data-theme=dark] .comment-table, html[data-theme=dark] li#add_button,
  1275. html[data-theme=dark] .OJBetter_setting_menu_label_text{
  1276. border: 1px dashed #424b56 !important;
  1277. }
  1278. html[data-theme=dark] li#add_button:hover{
  1279. border: 1px dashed #03A9F4 !important;
  1280. background-color: #2d333b !important;
  1281. color: #03A9F4 !important;
  1282. }
  1283. /* 无边框 */
  1284. html[data-theme=dark] .translate-problem-statement-panel .ojb_btn{
  1285. border: none !important;
  1286. }
  1287. /* input-output-copier特殊处理 */
  1288. html[data-theme=dark] .html2md-panel.input-output-copier,
  1289. html[data-theme=dark] .translateDiv.input-output-copier,
  1290. html[data-theme=dark] #OJBetter_SubmitForm.input-output-copier{
  1291. border: none !important;
  1292. }
  1293. html[data-theme=dark] .html2md-panel.input-output-copier:hover,
  1294. html[data-theme=dark] #OJBetter_SubmitForm.input-output-copier:hover{
  1295. background-color: #ffffff00 !important;
  1296. }
  1297. /* focus-visible */
  1298. html[data-theme=dark] input:focus-visible, html[data-theme=dark] textarea, html[data-theme=dark] select{
  1299. border-width: 1.5px !important;
  1300. outline: none;
  1301. }
  1302. /* 图片-亮度 */
  1303. html[data-theme=dark] img, html[data-theme=dark] #facebox .popup a{
  1304. opacity: .75;
  1305. }
  1306. /* 反转 */
  1307. html[data-theme=dark] .SumoSelect>.CaptionCont>label>i, html[data-theme=dark] .delete-resource-link,
  1308. html[data-theme=dark] #program-source-text, html[data-theme=dark] .spoiler-content pre,
  1309. html[data-theme=dark] .popup .content pre code{
  1310. filter: invert(1) hue-rotate(.5turn);
  1311. }
  1312. /* 区域遮罩 */
  1313. html[data-theme=dark] .overlay::before {
  1314. background: repeating-linear-gradient(135deg, #49525f6e, #49525f6e 30px, #49525f29 0px, #49525f29 55px);
  1315. color: #9099a3;
  1316. text-shadow: 0px 0px 2px #000000;
  1317. }
  1318. /* 阴影 */
  1319. html[data-theme=dark] .translate-problem-statement-panel, html[data-theme=dark] .translate-problem-statement{
  1320. box-shadow: 0px 0px 0.5px 0.5px #30353b;
  1321. }
  1322. /* 图标按钮状态样式 */
  1323. html[data-theme=dark] .ojb_btn_popover.success i:before, html[data-theme=dark] .ojb_btn_popover.success i {
  1324. color: #2e7d32;
  1325. }
  1326. html[data-theme=dark] .ojb_btn_popover i:before {
  1327. text-shadow: 1px 1px 0px #2d333b, 1px -1px 0px #2d333b, -1px -1px 0px #2d333b, -1px 1px 0px #2d333b;
  1328. }
  1329. /* 其他样式 */
  1330. html[data-theme=dark] .rated-user{
  1331. display: initial;
  1332. }
  1333. html[data-theme=dark] .datatable .ilt, html[data-theme=dark] .datatable .irt,
  1334. html[data-theme=dark] .datatable .ilb, html[data-theme=dark] .datatable .irb,
  1335. html[data-theme=dark] .datatable .lt, html[data-theme=dark] .datatable .rt,
  1336. html[data-theme=dark] .datatable .lb, html[data-theme=dark] .datatable .rb{
  1337. background: none;
  1338. }
  1339. html[data-theme=dark] .problems .accepted-problem td.id{
  1340. border-left: 6px solid #47837d !important;
  1341. }
  1342. html[data-theme=dark] .problems .rejected-problem td.id{
  1343. border-left: 6px solid #ef9a9a !important;
  1344. }
  1345. html[data-theme=dark] .problems .accepted-problem td.act {
  1346. background-color: #47837d !important;
  1347. border-radius: 0px;
  1348. }
  1349. html[data-theme=dark] .problems .rejected-problem td.act{
  1350. background-color: #ef9a9a !important;
  1351. border-radius: 0px;
  1352. }
  1353. html[data-theme=dark] .OJBetter_setting_menu, html[data-theme=dark] .OJBetter_modal{
  1354. box-shadow: 0px 0px 0px 4px #2d333b;
  1355. border: 1px solid #2d333b;
  1356. }
  1357. html[data-theme=dark] .collapsible-topic.collapsed .content .collapsible-topic-options:before{
  1358. background-image: linear-gradient(#22272e00, #22272e);
  1359. }
  1360. html[data-theme=dark] .alert{
  1361. text-shadow: none;
  1362. }
  1363. html[data-theme=dark] input[type="radio"]:checked+.OJBetter_setting_menu_label_text {
  1364. color: #a0adb9 !important;
  1365. border: 1px solid #326154 !important;
  1366. }
  1367. /* 评测状态文字颜色 */
  1368. html[data-theme=dark] .verdict-accepted, html[data-theme=dark] .verdict-accepted-challenged,
  1369. html[data-theme=dark] .verdict-successful-challenge{
  1370. color: #0a0 !important;
  1371. }
  1372. html[data-theme=dark] .verdict-failed, html[data-theme=dark] .verdict-challenged{
  1373. color: red !important;
  1374. }
  1375. html[data-theme=dark] .verdict-rejected, html[data-theme=dark] .verdict-unsuccessful-challenge{
  1376. color: #673ab7 !important;
  1377. }
  1378. html[data-theme=dark] .verdict-waiting {
  1379. color: gray !important;
  1380. }
  1381. /* 样例hover样式 */
  1382. html[data-theme=dark] .problem-statement .darkhighlight {
  1383. background-color: #455a64 !important;
  1384. }
  1385. `);
  1386. })()
  1387.  
  1388. /**
  1389. * 黑暗模式额外的处理事件
  1390. */
  1391. function darkModeStyleAdjustment() {
  1392. $(".test-example-line").off("mouseenter mouseleave"); // 移除上面原本的事件
  1393. // 为奇数行添加悬停效果
  1394. $('.test-example-line-odd').hover(
  1395. function () {
  1396. $(this).addClass('darkhighlight');
  1397. $(this).prevUntil(':not(.test-example-line-odd)').addClass('darkhighlight');
  1398. $(this).nextUntil(':not(.test-example-line-odd)').addClass('darkhighlight');
  1399. },
  1400. function () {
  1401. $(this).removeClass('darkhighlight');
  1402. $(this).prevUntil(':not(.test-example-line-odd)').removeClass('darkhighlight');
  1403. $(this).nextUntil(':not(.test-example-line-odd)').removeClass('darkhighlight');
  1404. }
  1405. );
  1406.  
  1407. // 为偶数行添加悬停效果
  1408. $('.test-example-line-even').hover(
  1409. function () {
  1410. $(this).addClass('darkhighlight');
  1411. $(this).prevUntil(':not(.test-example-line-even)').addClass('darkhighlight');
  1412. $(this).nextUntil(':not(.test-example-line-even)').addClass('darkhighlight');
  1413. },
  1414. function () {
  1415. $(this).removeClass('darkhighlight');
  1416. $(this).prevUntil(':not(.test-example-line-even)').removeClass('darkhighlight');
  1417. $(this).nextUntil(':not(.test-example-line-even)').removeClass('darkhighlight');
  1418. }
  1419. );
  1420. }
  1421.  
  1422. // 样式
  1423. GM_addStyle(`
  1424. /*动画*/
  1425. @keyframes shake {
  1426. 0% { transform: translateX(-5px); }
  1427. 100% { transform: translateX(5px); }
  1428. }
  1429. @keyframes rotate {
  1430. from {
  1431. transform: rotate(0deg);
  1432. }
  1433.  
  1434. to {
  1435. transform: rotate(360deg);
  1436. }
  1437. }
  1438. @keyframes rippleout {
  1439. 0% {
  1440. box-shadow: 0 0 0 0 rgba(96, 98, 102, 0.2);
  1441. }
  1442.  
  1443. 100% {
  1444. box-shadow: 0 0 0 6px rgba(0, 0, 0, 0);
  1445. }
  1446. }
  1447. @keyframes bounce-in {
  1448. 20%,40%,60%,80%,from,to {
  1449. animation-timing-function: cubic-bezier(.215,.61,.355,1);
  1450. }
  1451.  
  1452. 0% {
  1453. opacity: 0;
  1454. transform: scale3d(.995,.995,.995);
  1455. }
  1456.  
  1457. 20% {
  1458. opacity: 1;
  1459. transform: scale3d(1.005,1.005,1.005);
  1460. }
  1461.  
  1462. 40% {
  1463. transform: scale3d(.998,.998,.998);
  1464. }
  1465.  
  1466. 60% {
  1467. transform: scale3d(1.002,1.002,1.002);
  1468. }
  1469.  
  1470. 80% {
  1471. transform: scale3d(.995,.995,.995);
  1472. }
  1473.  
  1474. to {
  1475. opacity: 1;
  1476. transform: scale3d(1,1,1);
  1477. }
  1478. }
  1479. /*iconfont图标*/
  1480. .iconfont {
  1481. font-family: "iconfont" !important;
  1482. font-size: 16px;
  1483. font-style: normal !important;
  1484. -webkit-font-smoothing: antialiased;
  1485. -moz-osx-font-smoothing: grayscale;
  1486. }
  1487. @font-face {
  1488. font-family: 'iconfont'; /* Project id 4284341 */
  1489. src: url('//aowuucdn.oss-accelerate.aliyuncs.com/iconfont/iconfont.woff2') format('woff2'),
  1490. url('//aowuucdn.oss-accelerate.aliyuncs.com/iconfont/iconfont.woff2.ttf') format('truetype');
  1491. }
  1492. html {
  1493. scroll-behavior: smooth;
  1494. }
  1495. :root {
  1496. --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";
  1497. }
  1498. span.mdViewContent {
  1499. white-space: pre-wrap;
  1500. }
  1501.  
  1502. /* 特殊处理,加上input-output-copier类, 让convertStatementToText方法忽略该元素 */
  1503. .translateDiv.input-output-copier, .html2md-panel.input-output-copier, #OJBetter_SubmitForm.input-output-copier {
  1504. font-size: initial;
  1505. float: initial;
  1506. color: initial;
  1507. cursor: initial;
  1508. border: none;
  1509. padding: 0px;
  1510. margin: 0px;
  1511. line-height: initial;
  1512. text-transform: none;
  1513. }
  1514. .translateDiv.input-output-copier:hover, .html2md-panel.input-output-copier:hover, #OJBetter_SubmitForm.input-output-copier:hover {
  1515. background-color: #ffffff00;
  1516. }
  1517.  
  1518. /* dialog */
  1519. dialog {
  1520. margin: 0px;
  1521. }
  1522. dialog::backdrop {
  1523. background-color: rgba(0, 0, 0, 0.4);
  1524. }
  1525.  
  1526. /*题目页链接栏样式*/
  1527. #problemToolbar {
  1528. display: flex;
  1529. flex-wrap: wrap;
  1530. justify-content: flex-end;
  1531. overflow: auto;
  1532. height: 100%;
  1533. margin: 0.5em;
  1534. }
  1535.  
  1536. /*html2md面板*/
  1537. .html2md-panel {
  1538. display: flex;
  1539. justify-content: flex-end;
  1540. align-items: center;
  1541. }
  1542. .html2md-panel a {
  1543. text-decoration: none;
  1544. }
  1545. .html2md-panel > button {
  1546. margin: 5px;
  1547. }
  1548. .html2md-panel.is_simple {
  1549. position: absolute;
  1550. right: 2%;
  1551. }
  1552.  
  1553. /*通用按钮*/
  1554. .ojb_btn {
  1555. display: flex;
  1556. align-items: center;
  1557. justify-content: center;
  1558. cursor: pointer;
  1559. background-color: #ffffff;
  1560. color: #606266;
  1561. width: auto;
  1562. font-size: 13px;
  1563. border-radius: 0.3rem;
  1564. padding: 2px 5px;
  1565. margin: 0px 5px;
  1566. border: 1px solid #dcdfe6;
  1567. }
  1568. .ojb_btn[disabled] {
  1569. cursor: not-allowed !important;
  1570. color: rgb(168, 171, 178) !important;
  1571. border: 1px solid rgb(228, 231, 237) !important;
  1572. background-color: rgb(255, 255, 255) !important;
  1573. }
  1574. .ojb_btn:hover {
  1575. color: #409eff;
  1576. border-color: #409eff;
  1577. background-color: #f1f8ff;
  1578. z-index: 150;
  1579. }
  1580. .ojb_btn.primary {
  1581. color: #ffffff;
  1582. border: 1px solid #409eff;
  1583. background-color: #409eff;
  1584. }
  1585. .ojb_btn.primary:hover {
  1586. color: #ffffff;
  1587. border: 1px solid #79bbff;
  1588. background-color: #79bbff;
  1589. }
  1590. .ojb_btn.success {
  1591. color: #4caf50;
  1592. border: 1px solid #C8E6C9;
  1593. background-color: #f0f9eb;
  1594. }
  1595. .ojb_btn.warning {
  1596. color: #e6a23c;
  1597. border: 1px solid #f3d19e;
  1598. background-color: #fdf6ec;
  1599. }
  1600. .ojb_btn.error {
  1601. color: #f56c6c;
  1602. border: 1px solid #fab6b6;
  1603. background-color: #fef0f0;
  1604. }
  1605. .ojb_btn.enabled {
  1606. color: #42A5F5;
  1607. border: 1px solid #90CAF9;
  1608. background-color: #fafbff;
  1609. }
  1610. .ojb_btn.active {
  1611. animation: rippleout 0.5s ease-in-out;
  1612. }
  1613. a.ojb_btn {
  1614. text-decoration: none;
  1615. }
  1616. a.ojb_btn:link {
  1617. color: #606266;
  1618. }
  1619. a.ojb_btn span {
  1620. margin-left: 2px;
  1621. }
  1622. /*按钮图标和popover*/
  1623. .ojb_btn_popover {
  1624. display: flex;
  1625. justify-content: center;
  1626. position: relative;
  1627. outline: none;
  1628. appearance: none;
  1629. }
  1630. .ojb_btn_popover:hover span {
  1631. opacity: 1;
  1632. visibility: visible;
  1633. }
  1634. .ojb_btn_popover i:before {
  1635. position: absolute;
  1636. text-shadow: 1px 1px 0px #ffffff, 1px -1px 0px #ffffff, -1px -1px 0px #ffffff, -1px 1px 0px #ffffff;
  1637. }
  1638. .ojb_btn_popover span {
  1639. cursor: initial;
  1640. position: absolute;
  1641. left: 50%;
  1642. opacity: 0;
  1643. visibility: hidden;
  1644. padding: 4px 8px;
  1645. background-color: rgba(33, 33, 33, 0.8);
  1646. color: rgba(255, 255, 255, 0.9019607843);
  1647. font-size: 12px;
  1648. border-radius: 6px;
  1649. line-height: 1.6;
  1650. text-align: left;
  1651. white-space: nowrap;
  1652. transition: all 0.15s ease-in-out;
  1653. z-index: 999;
  1654. }
  1655. .ojb_btn_popover span:hover {
  1656. opacity: 0;
  1657. visibility: hidden;
  1658. }
  1659. .ojb_btn_popover.top:hover span {
  1660. transform: translate(-50%, 0);
  1661. }
  1662. .ojb_btn_popover.top span {
  1663. bottom: 100%;
  1664. transform: translate(-50%, -20%);
  1665. margin-bottom: 4px;
  1666. }
  1667. .ojb_btn_popover.top span:hover {
  1668. transform: translate(-50%, -20%);
  1669. }
  1670. .ojb_btn_popover.bottom:hover span {
  1671. transform: translate(-50%, 105%);
  1672. }
  1673. .ojb_btn_popover.bottom span {
  1674. bottom: -2%;
  1675. transform: translate(-50%, 100%);
  1676. margin-top: 4px;
  1677. }
  1678. .ojb_btn_popover.bottom span:hover {
  1679. transform: translate(-50%, 50%);
  1680. }
  1681. .ojb_btn_popover.loading i {
  1682. color: rgba(33, 33, 33, 0.1);
  1683. }
  1684. .ojb_btn_popover.loading i:before {
  1685. content: "\\e640";
  1686. color: rgb(168, 171, 178);
  1687. animation: rotate 2s cubic-bezier(0.65, 0.05, 0.36, 1) infinite;
  1688. }
  1689. .ojb_btn_popover.running i {
  1690. color: rgba(33, 33, 33, 0.1);
  1691. }
  1692. .ojb_btn_popover.running i:before {
  1693. content: "\\e600";
  1694. color: rgb(168, 171, 178);
  1695. animation: rotate 1s linear infinite;
  1696. }
  1697. .ojb_btn_popover.warning i {
  1698. color: rgba(230, 162, 61, 0.8);
  1699. }
  1700. .ojb_btn_popover.warning i:before {
  1701. content: "\\e68b";
  1702. font-size: 15px;
  1703. left: 10px;
  1704. bottom: 0%;
  1705. color: #ff9800;
  1706. }
  1707. .ojb_btn_popover.error i {
  1708. color: rgba(245, 108, 108, 0.8);
  1709. }
  1710. .ojb_btn_popover.error i:before {
  1711. content: "\\e651";
  1712. font-size: 15px;
  1713. left: 10px;
  1714. bottom: 0%;
  1715. color: #F44336;
  1716. }
  1717. .ojb_btn_popover.success i {
  1718. color: rgba(76, 175, 80, 0.9);
  1719. }
  1720. .ojb_btn_popover.success i:before {
  1721. content: "\\e61e";
  1722. font-size: 15px;
  1723. left: 10px;
  1724. bottom: 0%;
  1725. color: #4caf50;
  1726. }
  1727. .ojb_btn_popover.enabled i {
  1728. color: rgba(33, 150, 243, 0.6);
  1729. }
  1730. .ojb_btn_popover.enabled i:before {
  1731. content: "\\e6f4";
  1732. font-size: 15px;
  1733. left: 10px;
  1734. bottom: 0%;
  1735. color: #2196F3;
  1736. }
  1737. .ojb_btn_popover.redo i {
  1738. color: rgba(33, 33, 33, 0.1);
  1739. }
  1740. .ojb_btn_popover.redo i:before {
  1741. content: "\\e831";
  1742. color: #616161;
  1743. }
  1744. .ojb_btn_popover.reverse i {
  1745. transform: rotate(180deg);
  1746. }
  1747.  
  1748. /*translateDiv样式*/
  1749. .translateDiv .topText {
  1750. display: flex;
  1751. margin-left: 5px;
  1752. color: #9e9e9e;
  1753. font-size: 13px;
  1754. align-items: center;
  1755. }
  1756. .translateDiv .borderlessButton{
  1757. display: flex;
  1758. align-items: center;
  1759. margin: 2.5px 7px;
  1760. fill: #9E9E9E;
  1761. }
  1762. .translateDiv .borderlessButton:hover{
  1763. cursor: pointer;
  1764. fill: #059669;
  1765. }
  1766. .translateDiv.bounce-in {
  1767. animation: bounce-in 1s forwards;
  1768. }
  1769. html:not([data-theme='dark']) .translateDiv {
  1770. box-shadow: 0px 0px 0.5px 0.5px #defdf378;
  1771. }
  1772. .translate-problem-statement {
  1773. justify-items: start;
  1774. letter-spacing: 1.8px;
  1775. color: #059669;
  1776. background-color: #f9f9fa;
  1777. border: 1px solid #c5ebdf;
  1778. border-radius: 0rem 0rem 0.3rem 0.3rem;
  1779. padding: 5px;
  1780. margin: -5px 0px 6px 0px;
  1781. width: 100%;
  1782. box-sizing: border-box;
  1783. font-size: 13px;
  1784. }
  1785. .translate-problem-statement-panel{
  1786. display: flex;
  1787. justify-content: space-between;
  1788. background-color: #f9f9fa;
  1789. border: 1px solid #c5ebdf;
  1790. border-radius: 0.3rem;
  1791. margin: 4px 0px;
  1792. }
  1793. .translate-problem-statement-panel .ojb_btn {
  1794. background: none;
  1795. border: none;
  1796. color: #9e9e9e;
  1797. }
  1798. .translate-problem-statement-panel.error, .translate-problem-statement.error {
  1799. color: red;
  1800. border-color: red;
  1801. }
  1802. .translate-problem-statement a, .translate-problem-statement a:link {
  1803. color: #10b981;
  1804. font-weight: 600;
  1805. background: 0 0;
  1806. text-decoration: none;
  1807. }
  1808. .translate-problem-statement ol, .translate-problem-statement ul {
  1809. display: grid;
  1810. margin-inline-start: 0.8em;
  1811. margin-block-start: 0em;
  1812. margin: 0.5em 0 0 3em;
  1813. }
  1814. .translate-problem-statement li {
  1815. display: list-item;
  1816. height: auto;
  1817. word-wrap: break-word;
  1818. }
  1819. .translate-problem-statement ol li {
  1820. list-style-type: auto;
  1821. }
  1822. .translate-problem-statement ul li {
  1823. list-style-type: disc;
  1824. }
  1825. .translate-problem-statement img {
  1826. max-width: 100.0%;
  1827. max-height: 100.0%;
  1828. }
  1829. .ttypography .translate-problem-statement .MathJax {
  1830. color: #059669!important;
  1831. }
  1832. .translate-problem-statement span.math {
  1833. margin: 0px 2.5px !important;
  1834. }
  1835. .translate-problem-statement a:hover {
  1836. background-color: #800;
  1837. color: #fff;
  1838. text-decoration: none;
  1839. }
  1840. .translate-problem-statement table {
  1841. border: 1px #ccc solid !important;
  1842. margin: 1.5em 0 !important;
  1843. color: #059669 !important;
  1844. }
  1845. .translate-problem-statement table thead th {
  1846. border: 1px #ccc solid !important;
  1847. color: #059669 !important;
  1848. }
  1849. .translate-problem-statement table td {
  1850. border-right: 1px solid #ccc;
  1851. border-top: 1px solid #ccc;
  1852. padding: 0.7143em 0.5em;
  1853. }
  1854. .translate-problem-statement table th {
  1855. padding: 0.7143em 0.5em;
  1856. }
  1857. .translate-problem-statement p:not(:first-child) {
  1858. margin: 1.5em 0 0;
  1859. }
  1860. .translate-problem-statement p {
  1861. line-height: 20px !important;
  1862. word-wrap: break-word;
  1863. }
  1864. .problem-statement p:last-child {
  1865. margin-bottom: 0px !important;
  1866. }
  1867.  
  1868. /*设置按钮*/
  1869. header .enter-or-register-box, header .languages {
  1870. position: absolute;
  1871. right: 170px;
  1872. }
  1873. .ojb_btn.OJBetter_setting {
  1874. float: right;
  1875. height: 30px;
  1876. background: #60a5fa;
  1877. color: white;
  1878. margin: 10px;
  1879. border: 1px solid #60a5fa;
  1880. }
  1881. .ojb_btn.OJBetter_setting.open {
  1882. background-color: #e6e6e6;
  1883. color: #727378;
  1884. cursor: not-allowed;
  1885. }
  1886.  
  1887. /*设置面板*/
  1888. .OJBetter_setting_menu {
  1889. box-shadow: 0px 0px 0px 4px #ffffff;
  1890. position: fixed;
  1891. top: 50%;
  1892. left: 50%;
  1893. width: 600px;
  1894. min-height: 600px;
  1895. transform: translate(-50%, -50%);
  1896. border-radius: 6px;
  1897. background-color: #f0f4f9;
  1898. border-collapse: collapse;
  1899. border: 1px solid #ffffff;
  1900. color: #697e91;
  1901. font-family: var(--vp-font-family-base);
  1902. padding: 10px 20px 20px 10px;
  1903. box-sizing: content-box;
  1904. }
  1905. .OJBetter_setting_menu h3 {
  1906. margin-top: 10px;
  1907. }
  1908. .OJBetter_setting_menu h4 {
  1909. margin: 15px 0px 10px 0px;
  1910. }
  1911. .OJBetter_setting_menu h4,.OJBetter_setting_menu h5 {
  1912. font-weight: 600;
  1913. }
  1914. .OJBetter_setting_menu hr {
  1915. border: none;
  1916. height: 1px;
  1917. background-color: #ccc;
  1918. margin: 10px 0;
  1919. }
  1920. .OJBetter_setting_menu details {
  1921. padding: 10px;
  1922. margin-bottom: 5px;
  1923. background-color: #ffffff;
  1924. border-bottom: 1px solid #c9c6c696;
  1925. border-radius: 8px;
  1926. }
  1927. .OJBetter_setting_menu .badge {
  1928. border-radius: 4px;
  1929. border: 1px solid #009688;
  1930. color: #009688;
  1931. font-size: 12px;
  1932. padding: 0.5px 4px;
  1933. margin-left: 5px;
  1934. margin-right: auto;
  1935. }
  1936. .OJBetter_setting_menu .missing {
  1937. box-shadow: inset 0px 0px 1px 1px red;
  1938. }
  1939. /* 页面切换 */
  1940. .OJBetter_setting_menu .settings-page {
  1941. display: none;
  1942. }
  1943. .OJBetter_setting_menu .settings-page.active {
  1944. display: block;
  1945. }
  1946. .OJBetter_setting_container {
  1947. display: flex;
  1948. }
  1949. .OJBetter_setting_sidebar {
  1950. flex: 0 0 auto;
  1951. min-width: 110px;
  1952. padding: 6px 10px 6px 6px;
  1953. margin: 20px 0px;
  1954. border-right: 1px solid #d4d8e9;
  1955. }
  1956. .OJBetter_setting_content {
  1957. flex-grow: 1;
  1958. margin: 20px 0px 0px 12px;
  1959. padding-right: 10px;
  1960. max-height: 580px;
  1961. overflow-y: auto;
  1962. box-sizing: border-box;
  1963. }
  1964. .OJBetter_setting_sidebar h3 {
  1965. margin-top: 0;
  1966. }
  1967. .OJBetter_setting_sidebar hr {
  1968. margin-top: 10px;
  1969. margin-bottom: 10px;
  1970. border: none;
  1971. border-top: 1px solid #DADCE0;
  1972. }
  1973. .OJBetter_setting_sidebar ul {
  1974. list-style-type: none;
  1975. margin: 0;
  1976. padding: 0;
  1977. }
  1978. .OJBetter_setting_sidebar li {
  1979. margin: 5px 0px;
  1980. background-color: #ffffff;
  1981. border: 1px solid #d4d8e9;
  1982. border-radius: 4px;
  1983. font-size: 16px;
  1984. }
  1985. .OJBetter_setting_sidebar li a {
  1986. text-decoration: none;
  1987. display: flex;
  1988. width: 100%;
  1989. font-size: 16px;
  1990. color: gray;
  1991. background-color: #ffffff;
  1992. border: none;
  1993. letter-spacing: 2px;
  1994. padding: 7px;
  1995. margin: 0px;
  1996. border-radius: 4px;
  1997. align-items: center;
  1998. -webkit-box-sizing: border-box;
  1999. -moz-box-sizing: border-box;
  2000. box-sizing: border-box;
  2001. }
  2002. .OJBetter_setting_sidebar li a.active {
  2003. background-color: #eceff1c7;
  2004. }
  2005. /* 链接样式 */
  2006. .OJBetter_setting_menu a {
  2007. font-size: 13px;
  2008. color: #009688;
  2009. background-color: #E0F2F1;
  2010. border: 1px solid #009688;
  2011. border-radius: 4px;
  2012. padding: 0px 5px;
  2013. margin: 0px 5px;
  2014. text-decoration: none;
  2015. }
  2016. /* 下拉选择框 */
  2017. .OJBetter_setting_menu select {
  2018. appearance: none;
  2019. padding: 5px 10px;
  2020. margin: -5px 0px;
  2021. border-radius: 6px;
  2022. border-style: solid;
  2023. border: 1px solid #ced4da;
  2024. color: #009688;
  2025. font-size: 15px;
  2026. }
  2027. .OJBetter_setting_menu select:focus-visible {
  2028. outline: none;
  2029. }
  2030. .OJBetter_setting_menu select option:disabled {
  2031. color: #EEEEEE;
  2032. }
  2033. /* 数值输入框 */
  2034. .OJBetter_setting_menu input[type="number"] {
  2035. width: 40px;
  2036. color: #009688;
  2037. font-size: 15px;
  2038. appearance: none;
  2039. padding: 5px 10px;
  2040. margin: -5px 3px;
  2041. border-radius: 6px;
  2042. border-style: solid;
  2043. border: 1px solid #ced4da;
  2044. }
  2045. .OJBetter_setting_menu input[type="number"]:focus-visible {
  2046. outline: none;
  2047. }
  2048. .OJBetter_setting_menu input[type="number"]::-webkit-inner-spin-button,
  2049. .OJBetter_setting_menu input[type="number"]::-webkit-outer-spin-button {
  2050. -webkit-appearance: none;
  2051. margin: 0;
  2052. }
  2053. /*设置面板-滚动条*/
  2054. .OJBetter_setting_menu::-webkit-scrollbar, .OJBetter_setting_content::-webkit-scrollbar,
  2055. .OJBetter_modal .content::-webkit-scrollbar {
  2056. width: 5px;
  2057. height: 7px;
  2058. background-color: #aaa;
  2059. }
  2060. .OJBetter_setting_menu::-webkit-scrollbar-thumb, .OJBetter_setting_content::-webkit-scrollbar-thumb,
  2061. .OJBetter_modal .content::-webkit-scrollbar-thumb {
  2062. background-clip: padding-box;
  2063. background-color: #d7d9e4;
  2064. }
  2065. .OJBetter_setting_menu::-webkit-scrollbar-track, .OJBetter_setting_content::-webkit-scrollbar-track,
  2066. .OJBetter_modal .content::-webkit-scrollbar-track {
  2067. background-color: #f1f1f1;
  2068. }
  2069. /*设置面板-关闭按钮*/
  2070. .OJBetter_setting_menu .tool-box {
  2071. position: absolute;
  2072. width: 20px;
  2073. height: 20px;
  2074. top: 3px;
  2075. right: 3px;
  2076. }
  2077. .OJBetter_setting_menu .btn-close {
  2078. cursor: pointer;
  2079. width: 20px;
  2080. height: 20px;
  2081. border-radius: 50%;
  2082. border: none;
  2083. margin: 0px;
  2084. padding: 0px;
  2085. background-color: #ff000080;
  2086. transition: .15s ease all;
  2087. box-sizing: border-box;
  2088. text-align: center;
  2089. color: transparent;
  2090. font-size: 17px;
  2091. }
  2092. .OJBetter_setting_menu .btn-close:hover {
  2093. color: #ffffff;
  2094. background-color: #ff0000cc;
  2095. box-shadow: 0 5px 5px 0 #00000026;
  2096. }
  2097. .OJBetter_setting_menu .btn-close:active {
  2098. color: #ffffffde;
  2099. background-color: #ff000080;
  2100. }
  2101. /*设置面板-checkbox*/
  2102. .OJBetter_setting_menu input[type=checkbox]:focus {
  2103. outline: 0px;
  2104. }
  2105. .OJBetter_setting_menu .OJBetter_setting_list input[type="checkbox"] {
  2106. margin: 0px;
  2107. appearance: none;
  2108. -webkit-appearance: none;
  2109. width: 40px;
  2110. height: 20px;
  2111. border: 1.5px solid #D7CCC8;
  2112. padding: 0px !important;
  2113. border-radius: 20px;
  2114. background: #efebe978;
  2115. position: relative;
  2116. box-sizing: border-box;
  2117. }
  2118. .OJBetter_setting_menu .OJBetter_setting_list input[type="checkbox"]::before {
  2119. content: "";
  2120. width: 17px;
  2121. height: 17px;
  2122. background: #D7CCC8;
  2123. border: 1.5px solid #BCAAA4;
  2124. border-radius: 50%;
  2125. position: absolute;
  2126. top: 0;
  2127. left: 0;
  2128. transform: translate(2%, 2%);
  2129. transition: all 0.3s ease-in-out;
  2130. box-sizing: border-box;
  2131. }
  2132. .OJBetter_setting_menu .OJBetter_setting_list input[type="checkbox"]::after {
  2133. 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");
  2134. position: absolute;
  2135. top: 0;
  2136. left: 24px;
  2137. }
  2138. .OJBetter_setting_menu .OJBetter_setting_list input[type="checkbox"]:checked {
  2139. border: 1.5px solid #C5CAE9;
  2140. background: #E8EAF6;
  2141. }
  2142. .OJBetter_setting_menu .OJBetter_setting_list input[type="checkbox"]:checked::before {
  2143. background: #C5CAE9;
  2144. border: 1.5px solid #7986CB;
  2145. transform: translate(122%, 2%);
  2146. transition: all 0.3s ease-in-out;
  2147. }
  2148. .OJBetter_setting_menu .OJBetter_setting_list input[type="checkbox"]:checked::after {
  2149. 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");
  2150. position: absolute;
  2151. top: 1.5px;
  2152. left: 4.5px;
  2153. }
  2154. .OJBetter_setting_menu .OJBetter_setting_list button {
  2155. cursor: pointer;
  2156. color: #7986cb;
  2157. background-color: #e8eaf6;
  2158. border: 1px solid #7986cb;
  2159. border-radius: 6px;
  2160. width: 100px;
  2161. margin: -5px 2px;
  2162. padding: 5px 10px;
  2163. }
  2164. .OJBetter_setting_menu .OJBetter_setting_list button:hover {
  2165. color: #e8eaf6;
  2166. background-color: #7986cb;
  2167. border: 1px solid #7986cb;
  2168. }
  2169. .OJBetter_setting_menu label, #darkMode_span, #loaded_span {
  2170. font-size: 16px;
  2171. }
  2172. .OJBetter_setting_list {
  2173. display: flex;
  2174. flex-wrap: wrap;
  2175. align-items: center;
  2176. padding: 10px;
  2177. margin: 5px 0px;
  2178. background-color: #ffffff;
  2179. border: 1px solid #c9c6c642;
  2180. border-bottom-color: #c9c6c696;
  2181. border-radius: 8px;
  2182. justify-content: space-between;
  2183. }
  2184. .OJBetter_setting_list.alert_danger {
  2185. color: #F44336;
  2186. background-color: #FFEBEE;
  2187. border: 1px solid #F44336;
  2188. margin: 10px 0px;
  2189. }
  2190. .OJBetter_setting_list.alert_warn {
  2191. color: #E65100;
  2192. background-color: #FFF3E0;
  2193. border: 1px solid #FF9800;
  2194. margin: 10px 0px;
  2195. }
  2196. .OJBetter_setting_list.alert_tip {
  2197. color: #009688;
  2198. background-color: #E0F2F1;
  2199. border: 1px solid #009688;
  2200. margin: 10px 0px;
  2201. }
  2202. .OJBetter_setting_list.alert_info {
  2203. color: #ffffff;
  2204. background-color: #009688;
  2205. margin: 10px 0px;
  2206. box-shadow: rgba(0, 0, 0, 0.06) 0px 2px 4px 0px inset;
  2207. }
  2208. .OJBetter_setting_list p:not(:last-child) {
  2209. margin-bottom: 10px;
  2210. }
  2211. .OJBetter_setting_list p:not(:first-child) {
  2212. margin-top: 10px;
  2213. }
  2214. /*设置面板-checkboxs*/
  2215. .OJBetter_setting_menu .OJBetter_checkboxs {
  2216. flex-basis: 100%;
  2217. display: flex;
  2218. padding: 8px;
  2219. margin: 10px 0px 0px 0px;
  2220. border-bottom: 1px solid #c9c6c696;
  2221. border-radius: 8px;
  2222. border: 1px solid #c5cae9;
  2223. background-color: #f0f8ff;
  2224. }
  2225. .OJBetter_setting_menu .OJBetter_checkboxs label {
  2226. font-size: 13px;
  2227. margin: 0px 6px 0px 3px;
  2228. }
  2229. .OJBetter_setting_menu .OJBetter_checkboxs input[type=checkbox]:checked+label{
  2230. color: #7986cb;
  2231. }
  2232. .OJBetter_setting_menu .OJBetter_checkboxs input[type="checkbox"] {
  2233. border: none;
  2234. width: 16px;
  2235. height: 16px;
  2236. }
  2237. .OJBetter_setting_menu .OJBetter_checkboxs input[type="checkbox"]::before{
  2238. background: #ffffff;
  2239. transform: none;
  2240. width: 16px;
  2241. height: 16px;
  2242. }
  2243. .OJBetter_setting_menu .OJBetter_checkboxs input[type="checkbox"]:checked {
  2244. background: none;
  2245. border: none;
  2246. }
  2247. .OJBetter_setting_menu .OJBetter_checkboxs input[type="checkbox"]:checked::before {
  2248. border: 1.5px solid #95a2de;
  2249. background: #e8eaf6;
  2250. transform: none;
  2251. }
  2252. .OJBetter_setting_menu .OJBetter_checkboxs input[type="checkbox"]:checked::after {
  2253. 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");
  2254. top: 0px;
  2255. left: 3.5px;
  2256. }
  2257. .OJBetter_setting_menu .OJBetter_checkboxs input[type="checkbox"]:disabled+label {
  2258. color: #BDBDBD;
  2259. }
  2260. /*设置面板-radio*/
  2261. .OJBetter_setting_menu label {
  2262. list-style-type: none;
  2263. padding-inline-start: 0px;
  2264. overflow-x: auto;
  2265. max-width: 100%;
  2266. margin: 3px 0px;
  2267. overflow-x: visible;
  2268. }
  2269. .OJBetter_setting_menu_label_text {
  2270. display: flex;
  2271. border: 1px dashed #00aeeccc;
  2272. height: 35px;
  2273. width: 100%;
  2274. color: #6e6e6e;
  2275. font-weight: 300;
  2276. font-size: 14px;
  2277. letter-spacing: 2px;
  2278. padding: 7px;
  2279. margin-bottom: 4px;
  2280. align-items: center;
  2281. -webkit-box-sizing: border-box;
  2282. -moz-box-sizing: border-box;
  2283. box-sizing: border-box;
  2284. }
  2285. input[type="radio"]:checked+.OJBetter_setting_menu_label_text {
  2286. background: #41e49930;
  2287. border: 1px solid green;
  2288. color: green;
  2289. text-shadow: 0px 0px 0.5px green;
  2290. }
  2291. input[type="radio"]:disabled+.OJBetter_setting_menu_label_text {
  2292. background: #fafafa00;
  2293. border: 1px solid #e0e0e07a;
  2294. color: #e0e0e0;
  2295. }
  2296. .OJBetter_setting_menu label input[type="radio"], .OJBetter_contextmenu label input[type="radio"]{
  2297. appearance: none;
  2298. list-style: none;
  2299. padding: 0px !important;
  2300. margin: 0px;
  2301. clip: rect(0 0 0 0);
  2302. -webkit-clip-path: inset(100%);
  2303. clip-path: inset(100%);
  2304. height: 1px;
  2305. overflow: hidden;
  2306. position: absolute;
  2307. white-space: nowrap;
  2308. width: 1px;
  2309. }
  2310. /*设置面板-文本输入框*/
  2311. .OJBetter_setting_menu input[type="text"] {
  2312. display: block;
  2313. height: 25px !important;
  2314. width: 100%;
  2315. background-color: #ffffff;
  2316. color: #727378;
  2317. font-size: 12px;
  2318. border-radius: 0.3rem;
  2319. padding: 1px 5px !important;
  2320. box-sizing: border-box;
  2321. margin: 5px 0px 5px 0px;
  2322. border: 1px solid #00aeeccc;
  2323. box-shadow: 0 0 1px #0000004d;
  2324. }
  2325. .OJBetter_setting_menu .OJBetter_setting_list input[type="text"] {
  2326. margin-left: 5px;
  2327. }
  2328. .OJBetter_setting_menu input[type="text"]:focus-visible{
  2329. border-style: solid;
  2330. border-color: #3f51b5;
  2331. outline: none;
  2332. }
  2333. .OJBetter_setting_menu_config_box {
  2334. width: 100%;
  2335. display: grid;
  2336. margin-top: 5px;
  2337. -webkit-box-sizing: border-box;
  2338. -moz-box-sizing: border-box;
  2339. box-sizing: border-box;
  2340. }
  2341. .OJBetter_setting_menu input::placeholder {
  2342. color: #727378;
  2343. }
  2344. .OJBetter_setting_menu input.no_default::placeholder{
  2345. color: #BDBDBD;
  2346. }
  2347. .OJBetter_setting_menu input.is_null::placeholder{
  2348. color: red;
  2349. border-width: 1.5px;
  2350. }
  2351. .OJBetter_setting_menu input.is_null{
  2352. border-color: red;
  2353. }
  2354. .OJBetter_setting_menu textarea {
  2355. resize: vertical;
  2356. display: block;
  2357. width: 100%;
  2358. height: 60px;
  2359. background-color: #ffffff;
  2360. color: #727378;
  2361. font-size: 12px;
  2362. padding: 1px 5px !important;
  2363. box-sizing: border-box;
  2364. margin: 5px 0px 5px 0px;
  2365. border: 1px solid #00aeeccc;
  2366. box-shadow: 0 0 1px #0000004d;
  2367. }
  2368. .OJBetter_setting_menu textarea:focus-visible{
  2369. border-style: solid;
  2370. border-color: #3f51b5;
  2371. outline: none;
  2372. }
  2373. .OJBetter_setting_menu textarea::placeholder{
  2374. color: #BDBDBD;
  2375. font-size: 14px;
  2376. }
  2377. .OJBetter_setting_menu #tempConfig_save {
  2378. cursor: pointer;
  2379. display: inline-flex;
  2380. padding: 5px;
  2381. background-color: #1aa06d;
  2382. color: #ffffff;
  2383. font-size: 14px;
  2384. line-height: 1.5rem;
  2385. font-weight: 500;
  2386. justify-content: center;
  2387. width: 100%;
  2388. border-radius: 0.375rem;
  2389. border: none;
  2390. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  2391. margin-top: 20px
  2392. }
  2393. .OJBetter_setting_menu button#debug_button.debug_button {
  2394. width: 18%;
  2395. }
  2396. .OJBetter_setting_menu span.tip {
  2397. color: #999;
  2398. font-size: 12px;
  2399. font-weight: 500;
  2400. padding: 5px 0px;
  2401. }
  2402. /*设置面板-tip*/
  2403. .help_tip {
  2404. margin-right: auto;
  2405. }
  2406. span.input_label {
  2407. font-size: 14px;
  2408. }
  2409. .help_tip .tip_text {
  2410. display: none;
  2411. position: absolute;
  2412. color: #697e91;
  2413. font-weight: 400;
  2414. font-size: 14px;
  2415. letter-spacing: 0px;
  2416. background-color: #ffffff;
  2417. padding: 10px;
  2418. margin: 5px 0px;
  2419. border-radius: 4px;
  2420. border: 1px solid #e4e7ed;
  2421. box-shadow: 0px 0px 12px rgba(0, 0, 0, .12);
  2422. z-index: 100;
  2423. }
  2424. .help_tip .tip_text p {
  2425. margin-bottom: 5px;
  2426. }
  2427. .help_tip .tip_text:before {
  2428. content: "";
  2429. position: absolute;
  2430. top: -20px;
  2431. right: -10px;
  2432. bottom: -10px;
  2433. left: -10px;
  2434. z-index: -1;
  2435. }
  2436. .help-icon {
  2437. cursor: help;
  2438. width: 15px;
  2439. color: #b4b9d4;
  2440. margin-left: 5px;
  2441. margin-top: 3px;
  2442. }
  2443. .OJBetter_setting_menu .OJBetter_setting_menu_label_text .help_tip .help-icon {
  2444. color: #7fbeb2;
  2445. }
  2446. .help_tip .help-icon:hover + .tip_text, .help_tip .tip_text:hover {
  2447. display: block;
  2448. cursor: help;
  2449. width: 250px;
  2450. }
  2451. /* 版本信息 */
  2452. .OJBetter_setting_menu .versionInfo{
  2453. display: grid;
  2454. justify-items: center;
  2455. font-size: 16px;
  2456. padding: 10px;
  2457. }
  2458. .OJBetter_setting_menu .versionInfo>* {
  2459. margin: 10px 0px;
  2460. }
  2461.  
  2462. /* 配置管理面板 */
  2463. .config{
  2464. width: 100%;
  2465. margin: 10px 0px;
  2466. }
  2467. .config li.tempConfig_add_button {
  2468. cursor: pointer;
  2469. height: 40px;
  2470. border: 1px dashed #BDBDBD;
  2471. border-radius: 8px;
  2472. background-color: #fcfbfb36;
  2473. color: #bdbdbd;
  2474. font-size: 14px;
  2475. align-items: center;
  2476. justify-content: center;
  2477. }
  2478. .config li.tempConfig_add_button:hover {
  2479. border: 1px dashed #03A9F4;
  2480. background-color: #d7f0fb8c;
  2481. color: #03A9F4;
  2482. }
  2483. .config .config_bar_list {
  2484. display: flex;
  2485. width: 100%;
  2486. padding-bottom: 2px;
  2487. border: 1px solid #c5cae9;
  2488. background-color: #f0f8ff;
  2489. box-sizing: border-box;
  2490. border-radius: 0px 0px 8px 8px;
  2491. }
  2492. .config .config_bar_list input[type="radio"] {
  2493. appearance: none;
  2494. width: 0;
  2495. height: 0;
  2496. overflow: hidden;
  2497. }
  2498. .config .config_bar_list input[type="radio"] {
  2499. margin: 0px;
  2500. }
  2501. .config .config_bar_list input[type=radio]:focus {
  2502. outline: 0px;
  2503. }
  2504. .config .config_bar_ul_li_text {
  2505. display: flex;
  2506. align-items: center;
  2507. justify-content: center;
  2508. max-width: 100%;
  2509. height: 40px;
  2510. overflow-x: auto;
  2511. font-size: 14px;
  2512. font-weight: 400;
  2513. margin: 0px 4px;
  2514. padding: 3px;
  2515. border: 1px solid #dedede;
  2516. border-radius: 10px;
  2517. box-shadow: 0px 2px 4px 0px rgba(0,0,0,.05);
  2518. box-sizing: border-box;
  2519. }
  2520. .config .config_bar_ul li button {
  2521. background-color: #e6e6e6;
  2522. color: #727378;
  2523. height: 23px;
  2524. font-size: 14px;
  2525. border-radius: 0.3rem;
  2526. padding: 1px 5px;
  2527. margin: 5px;
  2528. border: none;
  2529. box-shadow: 0 0 1px #0000004d;
  2530. }
  2531. .config .config_bar_ul {
  2532. display: flex;
  2533. align-items: center;
  2534. list-style-type: none;
  2535. padding-inline-start: 0px;
  2536. overflow-x: auto;
  2537. max-width: 100%;
  2538. margin: 0px;
  2539. padding: 5px;
  2540. }
  2541. .config .config_bar_ul li {
  2542. width: 80px;
  2543. display: grid;
  2544. margin: 4px 4px;
  2545. min-width: 100px;
  2546. box-sizing: border-box;
  2547. }
  2548. .config .config_bar_ul_li_text:hover {
  2549. background-color: #eae4dc24;
  2550. }
  2551. input[type="radio"]:checked + .config_bar_ul_li_text {
  2552. background: #41b3e430;
  2553. border: 1px solid #5e7ce0;
  2554. color: #5e7ce0;
  2555. }
  2556. .config .config_bar_ul::-webkit-scrollbar {
  2557. width: 5px;
  2558. height: 4px;
  2559. }
  2560. .config .config_bar_ul::-webkit-scrollbar-thumb {
  2561. background-clip: padding-box;
  2562. background-color: #d7d9e4;
  2563. border-radius: 8px;
  2564. }
  2565. .config .config_bar_ul::-webkit-scrollbar-button:start:decrement {
  2566. width: 4px;
  2567. background-color: transparent;
  2568. }
  2569. .config .config_bar_ul::-webkit-scrollbar-button:end:increment {
  2570. width: 4px;
  2571. background-color: transparent;
  2572. }
  2573. .config .config_bar_ul::-webkit-scrollbar-track {
  2574. border-radius: 5px;
  2575. }
  2576. .config .config_bar_ul_li_text::-webkit-scrollbar {
  2577. width: 5px;
  2578. height: 7px;
  2579. background-color: #aaa;
  2580. }
  2581. .config .config_bar_ul_li_text::-webkit-scrollbar-thumb {
  2582. background-clip: padding-box;
  2583. background-color: #d7d9e4;
  2584. }
  2585. .config .config_bar_ul_li_text::-webkit-scrollbar-track {
  2586. background-color: #f1f1f1;
  2587. }
  2588. .config .config_bar_list_add_div {
  2589. display: flex;
  2590. height: 40px;
  2591. margin: 4px 2px;
  2592. }
  2593.  
  2594. /* 修改菜单 */
  2595. #config_bar_menu {
  2596. z-index: 400;
  2597. position: fixed;
  2598. width: 60px;
  2599. background: #ffffff;
  2600. box-shadow: 1px 1px 4px 0px #0000004d;
  2601. border: 0px solid rgba(0,0,0,0.04);
  2602. border-radius: 4px;
  2603. padding: 8px 0;
  2604. }
  2605. .config_bar_menu_item {
  2606. cursor: pointer;
  2607. padding: 2px 6px;
  2608. display: flex;
  2609. justify-content: center;
  2610. align-items: center;
  2611. height: 32px;
  2612. font-size: 14px;
  2613. font-weight: 500;
  2614. box-shadow: inset 0px 0px 0px 0px #8bb2d9;
  2615. }
  2616. #config_bar_menu_edit:hover {
  2617. background-color: #00aeec;
  2618. color: white;
  2619. }
  2620. #config_bar_menu_delete:hover {
  2621. background-color: #FF5722;
  2622. color: white;
  2623. }
  2624.  
  2625. /* 配置编辑页面 */
  2626. #config_edit_menu {
  2627. z-index: 300;
  2628. width: 450px;
  2629. }
  2630.  
  2631. /* 黑暗模式选项按钮 */
  2632. .dark-mode-selection {
  2633. display: flex;
  2634. justify-content: center;
  2635. align-items: center;
  2636. max-width: 350px;
  2637. -webkit-user-select: none;
  2638. -moz-user-select: none;
  2639. -ms-user-select: none;
  2640. user-select: none;
  2641. }
  2642. .dark-mode-selection label {
  2643. margin: 8px 0px 8px 8px;
  2644. }
  2645. .dark-mode-selection > * {
  2646. margin: 6px;
  2647. }
  2648. .dark-mode-selection .OJBetter_setting_menu_label_text {
  2649. border-radius: 8px;
  2650. margin-bottom: 0px;
  2651. }
  2652.  
  2653. /*确认弹窗*/
  2654. .OJBetter_modal {
  2655. z-index: 600;
  2656. display: grid;
  2657. position: fixed;
  2658. top: 50%;
  2659. left: 50%;
  2660. transform: translate(-50%, -50%);
  2661. font-size: 12px;
  2662. font-family: var(--vp-font-family-base);
  2663. width: max-content;
  2664. padding: 10px 20px;
  2665. box-shadow: 0px 0px 0px 4px #ffffff;
  2666. border-radius: 6px;
  2667. background-color: #f0f4f9;
  2668. border-collapse: collapse;
  2669. border: 1px solid #ffffff;
  2670. color: #697e91;
  2671. }
  2672. .OJBetter_modal .content{
  2673. white-space: nowrap;
  2674. max-height: 500px;
  2675. overflow-y: auto;
  2676. }
  2677. .OJBetter_modal .buttons{
  2678. display: flex;
  2679. padding-top: 15px;
  2680. }
  2681. .OJBetter_modal button {
  2682. display: inline-flex;
  2683. justify-content: center;
  2684. align-items: center;
  2685. line-height: 1;
  2686. white-space: nowrap;
  2687. cursor: pointer;
  2688. text-align: center;
  2689. box-sizing: border-box;
  2690. outline: none;
  2691. transition: .1s;
  2692. user-select: none;
  2693. vertical-align: middle;
  2694. -webkit-appearance: none;
  2695. height: 24px;
  2696. padding: 5px 11px;
  2697. margin-right: 15px;
  2698. font-size: 12px;
  2699. border-radius: 4px;
  2700. color: #ffffff;
  2701. background: #009688;
  2702. border-color: #009688;
  2703. border: none;
  2704. }
  2705. .OJBetter_modal button.secondary{
  2706. background-color:#4DB6AC;
  2707. }
  2708. .OJBetter_modal button:hover{
  2709. background-color:#4DB6AC;
  2710. }
  2711. .OJBetter_modal button.secondary:hover {
  2712. background-color: #80CBC4;
  2713. }
  2714. .OJBetter_modal .help-icon {
  2715. margin: 0px 8px 0px 0px;
  2716. height: 1em;
  2717. width: 1em;
  2718. line-height: 1em;
  2719. display: inline-flex;
  2720. justify-content: center;
  2721. align-items: center;
  2722. position: relative;
  2723. fill: currentColor;
  2724. font-size: inherit;
  2725. }
  2726. .OJBetter_modal p {
  2727. margin: 5px 0px;
  2728. }
  2729.  
  2730. /* 右键菜单 */
  2731. .OJBetter_contextmenu {
  2732. z-index: 500;
  2733. display: grid;
  2734. position: absolute;
  2735. background-color: #f0f4f9;
  2736. border-collapse: collapse;
  2737. color: #697e91;
  2738. font-family: var(--vp-font-family-base);
  2739. overflow: hidden;
  2740. box-sizing: content-box;
  2741. box-shadow: 0px 0px 0px 2px #eddbdb4d;
  2742. }
  2743. input[type="radio"]:checked+.OJBetter_contextmenu_label_text {
  2744. background: #41e49930;
  2745. border: 1px solid green;
  2746. color: green;
  2747. font-weight: 500;
  2748. }
  2749. .OJBetter_contextmenu_label_text {
  2750. display: flex;
  2751. border: 1px dashed #80cbc4;
  2752. height: 26px;
  2753. width: 100%;
  2754. color: gray;
  2755. font-size: 13px;
  2756. padding: 4px;
  2757. align-items: center;
  2758. -webkit-box-sizing: border-box;
  2759. -moz-box-sizing: border-box;
  2760. box-sizing: border-box;
  2761. }
  2762. .OJBetter_contextmenu_label_text:hover {
  2763. color: #F44336;
  2764. border: 1px dashed #009688;
  2765. background-color: #ffebcd;
  2766. }
  2767.  
  2768. /* RatingByClist */
  2769. .ratingBadge, html[data-theme=dark] button.ratingBadge{
  2770. display: block;
  2771. font-weight: 700;
  2772. font-size: 11px;
  2773. margin-top: 5px;
  2774. padding: 2px;
  2775. border-radius: 4px;
  2776. color: #B0BEC5;
  2777. border: 1px solid #cccccc66;
  2778. }
  2779.  
  2780. /* 多选翻译 */
  2781. .block_selected{
  2782. box-shadow: 0px 0px 0px 1px #FF9800;
  2783. outline: none;
  2784. }
  2785.  
  2786. /* 悬浮菜单 */
  2787. .OJBetter_MiniTranslateButton {
  2788. z-index: 100;
  2789. display: grid;
  2790. position: absolute;
  2791. border-collapse: collapse;
  2792. fill: #F57C00;
  2793. background-color: #FFF3E0;
  2794. overflow: hidden;
  2795. box-sizing: content-box;
  2796. box-shadow: 0px 0px 0px 2px #FFE0B2;
  2797. border-radius: 100%;
  2798. }
  2799. .OJBetter_MiniTranslateButton:hover {
  2800. cursor: pointer;
  2801. box-shadow: 0px 0px 0px 2px #FFB74D;
  2802. }
  2803.  
  2804. /* acmsguru划分块 */
  2805. .OJBetter_acmsguru {
  2806. margin: 0 0 1em!important;
  2807. }
  2808.  
  2809. /* 代码提交表单 */
  2810. #OJBetter_SubmitForm.input-output-copier:hover {
  2811. background-color: #ffffff00;
  2812. }
  2813. #OJBetter_SubmitForm input[type="number"] {
  2814. width: 40px;
  2815. color: #009688;
  2816. appearance: none;
  2817. border-radius: 6px;
  2818. border-style: solid;
  2819. border: none;
  2820. background-color: #ffffff00;
  2821. }
  2822. #OJBetter_SubmitForm :focus-visible {
  2823. outline: none;
  2824. }
  2825. #OJBetter_SubmitForm .topDiv {
  2826. height: 28px;
  2827. display: flex;
  2828. align-items: center;
  2829. justify-content: space-between;
  2830. padding: 10px 0px;
  2831. }
  2832. #OJBetter_SubmitForm .topDiv .topRightDiv {
  2833. height: 100%;
  2834. display: flex;
  2835. flex-wrap: wrap;
  2836. gap: 0px;
  2837. }
  2838.  
  2839. /* 顶部区域 */
  2840. #OJBetter_SubmitForm .topRightDiv>* {
  2841. height: 100%;
  2842. box-sizing: border-box;
  2843. }
  2844. #OJBetter_SubmitForm .topRightDiv>button{
  2845. padding: 0px 8px;
  2846. }
  2847. #OJBetter_SubmitForm .topRightDiv {
  2848. display: flex;
  2849. flex-wrap: wrap;
  2850. gap: 0px;
  2851. align-items: center;
  2852. }
  2853.  
  2854. /* LSP连接Log */
  2855. #LSPLog{
  2856. width: 500px;
  2857. height: 500px;
  2858. position: fixed;
  2859. top: 50%;
  2860. left: 50%;
  2861. padding: 10px;
  2862. transform: translate(-50%, -50%);
  2863. border: 1px solid;
  2864. z-index: 200;
  2865. background-color: #ffffff;
  2866. }
  2867. #LSPLog button{
  2868. position: fixed;
  2869. top: 10px;
  2870. right: 10px;
  2871. z-index: 200;
  2872. }
  2873. #LSPLog #LSPLogList{
  2874. width: 500px;
  2875. height: 500px;
  2876. overflow: auto;
  2877. color: #424242;
  2878. }
  2879. #LSPLog li:nth-child(odd){
  2880. background-color: #f5f5f5;
  2881. }
  2882. #LSPLog details{
  2883. padding: 2px;
  2884. }
  2885.  
  2886. /* 代码编辑器 */
  2887. #OJBetter_editor{
  2888. box-sizing: border-box;
  2889. height: 600px;
  2890. border: 1px solid #d3d3d3;
  2891. width: 100%;
  2892. resize: vertical;
  2893. display: flex;
  2894. flex-direction: column;
  2895. }
  2896. #OJBetter_editor.fullscreen{
  2897. position: fixed;
  2898. top: 0;
  2899. left: 0;
  2900. width: 100%;
  2901. height: 100vh;
  2902. z-index: 100;
  2903. }
  2904. #OJBetter_editor.bottom{
  2905. position: fixed;
  2906. bottom: 0;
  2907. left: 0;
  2908. width: 100%;
  2909. height: 50vh;
  2910. z-index: 100;
  2911. }
  2912. .ojb_btn.exit_button_bottom {
  2913. position: fixed;
  2914. bottom: 30px;
  2915. right: 15px;
  2916. z-index: 100;
  2917. height: 28px;
  2918. }
  2919.  
  2920. /* monaco */
  2921. #OJBetter_monaco {
  2922. flex: 1;
  2923. min-height: 0;
  2924. width: 100%;
  2925. }
  2926. #OJBetter_monaco .highlight {
  2927. border: 1px solid #ffffff00;
  2928. background-color: #ffffff00!important
  2929. }
  2930. .monaco-hover hr {
  2931. margin: 4px -8px 4px !important;
  2932. }
  2933.  
  2934. /* 状态底栏 */
  2935. #OJBetter_statusBar{
  2936. height: 22px;
  2937. font-size: 12px;
  2938. color: #757575;
  2939. border: 1px solid #d3d3d3;
  2940. background-color: #f8f8f8;
  2941. padding: 3px;
  2942. box-sizing: border-box;
  2943. }
  2944.  
  2945. /* 提交 */
  2946. #OJBetter_submitDiv{
  2947. display: flex;
  2948. padding-top: 15px;
  2949. height: 35px;
  2950. }
  2951. #OJBetter_submitDiv >* {
  2952. border-radius: 6px;
  2953. }
  2954. #OJBetter_submitDiv > button {
  2955. height: 100%;
  2956. aspect-ratio: 1 / 1;
  2957. }
  2958. #SubmitButton {
  2959. color: #fff;
  2960. background-color: #209978;
  2961. border-color: #17795E;
  2962. }
  2963. #SubmitButton:hover {
  2964. background-color: #17795e;
  2965. }
  2966. #SubmitButton.disabled {
  2967. background-color: red;
  2968. animation: shake 0.07s infinite alternate;
  2969. }
  2970. #programTypeId{
  2971. height: 100%;
  2972. padding: 5px 10px;
  2973. border-radius: 6px;
  2974. border-style: solid;
  2975. border: 1px solid #ced4da;
  2976. color: #212529;
  2977. }
  2978.  
  2979. /* 调试 */
  2980. .OJBetter_loding{
  2981. padding: 6px 0px 0px 5px;
  2982. height: 22px;
  2983. }
  2984. #CompilerArgsInput{
  2985. flex-grow: 1;
  2986. width: 100%;
  2987. height: 100%;
  2988. margin-bottom: 10px;
  2989. padding: 5px 10px;
  2990. border-radius: 6px;
  2991. box-sizing: border-box;
  2992. border: 1px solid #ccc;
  2993. box-shadow: inset 0px 1px 1px rgba(0,0,0,.075);
  2994. }
  2995. #CompilerArgsInput[disabled] {
  2996. cursor: not-allowed;
  2997. }
  2998. #CompilerSetting{
  2999. font-size: 14px;
  3000. margin-top: 10px;
  3001. display: none;
  3002. }
  3003. #CompilerSetting select, #CompilerSetting textarea{
  3004. padding: 4px 10px;
  3005. border-radius: 6px;
  3006. border-style: solid;
  3007. border: 1px solid #ced4da;
  3008. color: #212529;
  3009. }
  3010. #CompilerBox{
  3011. display: grid;
  3012. margin-top: 10px;
  3013. border: #d0d7de solid 1px;
  3014. border-radius: 6px;
  3015. }
  3016. #CompilerBox > * {
  3017. margin: 5px;
  3018. }
  3019.  
  3020. /* 自定义样例 */
  3021. #customTestBlock {
  3022. margin-top: 10px;
  3023. font-size: 14px;
  3024. color: #616161;
  3025. border: 1px solid #d3d3d3;
  3026. box-sizing: border-box;
  3027. position: relative;
  3028. }
  3029. #customTestBlock #customTests{
  3030. border-top: 1px solid #d3d3d3;
  3031. margin: 0px 0px 40px 0px;
  3032. }
  3033. #customTestBlock summary {
  3034. cursor: pointer;
  3035. padding: 10px;
  3036. }
  3037. #customTestBlock textarea {
  3038. resize: vertical;
  3039. }
  3040. .sampleDiv {
  3041. color: #727378;
  3042. background-color: #FAFAFA;
  3043. padding: 5px;
  3044. margin-bottom: 10px;
  3045. box-shadow: inset 0 0 1px #0000004d;
  3046. position: relative;
  3047. }
  3048. .dynamicTextarea {
  3049. width: 98%;
  3050. height: 120px;
  3051. margin: 10px 5px;
  3052. border: 1px solid #E0E0E0;
  3053. }
  3054. .deleteCustomTest {
  3055. cursor: pointer;
  3056. position: absolute;
  3057. top: 5px;
  3058. right: 5px;
  3059. display: flex;
  3060. fill: #9E9E9E;
  3061. padding: 2px 2px;
  3062. border-radius: 4px;
  3063. border: 1px solid #ffffff00;
  3064. background-color: #ffffff00;
  3065. align-items: center;
  3066. }
  3067. .deleteCustomTest:hover {
  3068. fill: #EF5350;
  3069. border: 1px solid #ef9a9a;
  3070. background-color: #FFEBEE;
  3071. }
  3072. #addCustomTest {
  3073. cursor: pointer;
  3074. position: absolute;
  3075. bottom: 5px;
  3076. right: 5px;
  3077. padding: 3px 10px;
  3078. color: #795548;
  3079. border: 1px solid #ccc;
  3080. border-radius: 4px;
  3081. background-color: #FAFAFA;
  3082. }
  3083. #addCustomTest:hover {
  3084. background-color: #f5f5f5;
  3085. }
  3086.  
  3087. /* 调试结果 */
  3088. #statePanel{
  3089. display: none;
  3090. padding: 5px;
  3091. margin-top: 10px;
  3092. border: 1px solid #ddd;
  3093. border-radius: 4px;
  3094. }
  3095. .test-case {
  3096. padding: 10px;
  3097. border: 1px solid #ddd;
  3098. border-radius: 4px;
  3099. }
  3100. .test-case:not(:first-child){
  3101. margin-top: 5px;
  3102. }
  3103. .test-case > * {
  3104. margin: 5px 0px;
  3105. }
  3106. .test-case > :first-child {
  3107. margin-top: 0px;
  3108. }
  3109. .test-case > :last-child {
  3110. margin-bottom: 0px;
  3111. }
  3112. .test-case-title, .test-case-status {
  3113. font-size: 16px;
  3114. display: inline;
  3115. }
  3116. .test-case-status{
  3117. margin-left: 5px;
  3118. }
  3119. .test-case-status.error{
  3120. color: red;
  3121. }
  3122. .test-case-status.success{
  3123. color: #449d44;
  3124. }
  3125. .test-case-judge {
  3126. font-size: 13px;
  3127. }
  3128.  
  3129. /* 差异对比 */
  3130. .output_diff {
  3131. color: #5d4037;
  3132. margin: 5px 0px;
  3133. display: grid;
  3134. border: 1px solid #bcaaa4;
  3135. font-size: 13px;
  3136. font-family: Consolas, "Lucida Console", "Andale Mono", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace;
  3137. overflow: auto;
  3138. }
  3139. .output_diff .added {
  3140. background-color: #c8f7c5;
  3141. user-select: none;
  3142. padding-left: 3px;
  3143. }
  3144. .output_diff .removed {
  3145. background-color: #f7c5c5;
  3146. padding-left: 3px;
  3147. }
  3148. .output_diff .diffLine {
  3149. display: flex;
  3150.  
  3151. }
  3152. .output_diff .diffLine:nth-child(odd) {
  3153. background-color: #f5f5f5;
  3154. }
  3155. .lineNo {
  3156. display: flex;
  3157. align-items: center;
  3158. justify-content: center;
  3159. width: 17px;
  3160. color: #BDBDBD;
  3161. font-size: 10px;
  3162. border-right: 1px solid;
  3163. user-select: none;
  3164. }
  3165. .lineContent {
  3166. display: grid;
  3167. width: 100%;
  3168. }
  3169. .lineContent>span {
  3170. height: 16px;
  3171. }
  3172. .output_no_diff {
  3173. padding: 5px;
  3174. border: 1px solid #ddd;
  3175. }
  3176. .diff_note {
  3177. font-size: 10px;
  3178. }
  3179.  
  3180. /* 覆盖网站原本的样式 */
  3181. #footer > div:nth-child(7) {
  3182. left: 0px !important;
  3183. }
  3184.  
  3185. /* 移动设备 */
  3186. @media (max-device-width: 450px) {
  3187. .ojb_btn{
  3188. height: 2em;
  3189. font-size: 1.2em;
  3190. }
  3191. .ojb_btn.OJBetter_setting{
  3192. height: 2.5em;
  3193. font-size: 1em;
  3194. }
  3195. .OJBetter_setting_menu{
  3196. width: 90%;
  3197. }
  3198. .OJBetter_setting_menu label, #darkMode_span, #loaded_span, .OJBetter_setting_menu_label_text,
  3199. .OJBetter_setting_sidebar li{
  3200. font-size: 1em;
  3201. }
  3202. .translate-problem-statement{
  3203. font-size: 1.2em;
  3204. }
  3205. .OJBetter_modal{
  3206. font-size: 1.5em;
  3207. }
  3208. .OJBetter_setting_list, .translate-problem-statement{
  3209. padding: 0.5em;
  3210. }
  3211. .OJBetter_setting_menu_label_text{
  3212. height: 2.5em;
  3213. padding: 0.5em;
  3214. }
  3215. #pagBar #jump-input, #pagBar #items-per-page, .OJBetter_modal button{
  3216. height: 2.5em;
  3217. font-size: 1em;
  3218. }
  3219. .translate-problem-statement p, .translate-problem-statement ul li{
  3220. line-height: 1.5em !important;
  3221. }
  3222. .OJBetter_contextmenu_label_text{
  3223. height: 3em;
  3224. font-size: 1em;
  3225. }
  3226. }
  3227. `);
  3228.  
  3229. /**
  3230. * 添加一些依赖库和条件加载的css样式
  3231. */
  3232. function addDependencyStyles() {
  3233. GM_addStyle(GM_getResourceText("xtermcss"));
  3234. // 自定义图标大小
  3235. GM_addStyle(`
  3236. .iconfont {
  3237. font-size: ${OJBetter.preference.iconButtonSize}px;
  3238. }
  3239. `);
  3240. }
  3241.  
  3242. /**
  3243. * 添加包含i18n内容的css样式
  3244. */
  3245. function addI18nStyles() {
  3246. GM_addStyle(`
  3247. /* 加载鼠标悬浮覆盖层css */
  3248. .overlay::before {
  3249. content: '';
  3250. position: absolute;
  3251. top: 0;
  3252. left: 0;
  3253. width: 100%;
  3254. height: 100%;
  3255. 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);
  3256. z-index: 100;
  3257. }
  3258. .overlay::after {
  3259. content: '${i18next.t('targetArea', { ns: 'common' })}';
  3260. position: absolute;
  3261. top: 50%;
  3262. left: 50%;
  3263. transform: translate(-50%, -50%);
  3264. color: #00695C;
  3265. font-size: 16px;
  3266. font-weight: bold;
  3267. z-index: 100;
  3268. }
  3269.  
  3270. .config::before {
  3271. content: "${i18next.t('common.configManageTitle', { ns: 'settings' })}";
  3272. display: block;
  3273. height: 20px;
  3274. background-color: #f0f8ff;
  3275. border: 1px solid #c5cae9;
  3276. border-bottom: 0px;
  3277. line-height: 20px;
  3278. padding: 2px 10px;
  3279. border-radius: 8px 8px 0px 0px;
  3280. }
  3281. .config.missing::before {
  3282. content: "${i18next.t('common.missing.radio', { ns: 'settings' })}";
  3283. background-color: #fef0f0;
  3284. color: #f56c6c;
  3285. border: 1px solid #fab6b6;
  3286. }
  3287. `);
  3288. }
  3289.  
  3290. // ------------------------------
  3291. // 一些工具函数
  3292. // ------------------------------
  3293.  
  3294. /**
  3295. * 延迟函数
  3296. * @param {number} ms 延迟时间(毫秒)
  3297. * @returns {Promise<void>}
  3298. */
  3299. function OJB_delay(ms) {
  3300. return new Promise(resolve => setTimeout(resolve, ms));
  3301. }
  3302.  
  3303. /**
  3304. * 深度比较两个对象或数组是否完全相等。
  3305. * @param {any} a - 第一个比较对象。
  3306. * @param {any} b - 第二个比较对象。
  3307. * @returns {boolean} - 如果两个对象或数组深度相等,则返回true,否则返回false。
  3308. */
  3309. function OJB_deepEquals(a, b) {
  3310. if (a === b) return true;
  3311. if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) return false;
  3312. const keysA = Object.keys(a);
  3313. const keysB = Object.keys(b);
  3314. if (keysA.length !== keysB.length) return false;
  3315. for (let key of keysA) {
  3316. if (!b.hasOwnProperty(key)) return false;
  3317. if (!OJB_deepEquals(a[key], b[key])) return false;
  3318. }
  3319. return true;
  3320. }
  3321.  
  3322. /**
  3323. * 用于封装需要重试的异步函数
  3324. * @param {Function} task 需要封装的异步函数
  3325. * @param {Object} options 配置项
  3326. * @param {Number} options.maxRetries 重试次数,默认为 5
  3327. * @param {Number} options.retryInterval 重试时间间隔,默认为 0 毫秒
  3328. * @param {Function} options.errorHandler 错误处理函数,默认为抛出错误
  3329. * @param {...any} args task 函数的参数
  3330. * @returns {Promise} 返回 Promise
  3331. */
  3332. async function OJB_promiseRetryWrapper(task, {
  3333. maxRetries = 5,
  3334. retryInterval = 0,
  3335. errorHandler = (err) => { throw err }
  3336. } = {}, ...args) {
  3337. let attemptsLeft = maxRetries;
  3338. while (attemptsLeft--) {
  3339. try {
  3340. return await task(...args);
  3341. } catch (err) {
  3342. if (attemptsLeft <= 0) {
  3343. return errorHandler(err, maxRetries, attemptsLeft);
  3344. }
  3345. if (retryInterval > 0) {
  3346. await OJB_delay(retryInterval);
  3347. }
  3348. }
  3349. }
  3350. }
  3351.  
  3352. /**
  3353. * 自定义错误类,以区分不同的错误类型
  3354. */
  3355. class GMError extends Error {
  3356. constructor(type, message, originalError) {
  3357. super(message);
  3358. this.name = 'GMError';
  3359. this.type = type;
  3360. this.stack = originalError.stack;
  3361. Object.assign(this, originalError);
  3362. }
  3363. }
  3364.  
  3365. /**
  3366. * GM_xmlhttpRequest 的 Promise 封装
  3367. * @param {Object} options GM_xmlhttpRequest 的参数
  3368. * @param {Boolean} isStream 是否为流式请求
  3369. * @returns {Promise} 返回 Promise
  3370. */
  3371. function OJB_GMRequest(options, isStream = false) {
  3372. return new Promise((resolve, reject) => {
  3373. GM_xmlhttpRequest({
  3374. ...options,
  3375. ...(isStream ? {
  3376. onloadstart: resolve
  3377. } : {
  3378. onload: resolve
  3379. }),
  3380. onerror: (error) => reject(new GMError('error', 'An error occurred during the request.', error)),
  3381. ontimeout: (error) => reject(new GMError('timeout', 'The request timed out.', error)),
  3382. onabort: (error) => reject(new GMError('abort', 'The request was aborted.', error)),
  3383. });
  3384. });
  3385. }
  3386.  
  3387. /**
  3388. * 获取cookie
  3389. * @param {string} name cookie名称
  3390. * @returns {string} cookie值
  3391. */
  3392. function OJB_getCookie(name) {
  3393. const cookies = document.cookie.split(";");
  3394. for (let i = 0; i < cookies.length; i++) {
  3395. const cookie = cookies[i].trim();
  3396. const [cookieName, cookieValue] = cookie.split("=");
  3397.  
  3398. if (cookieName === name) {
  3399. return decodeURIComponent(cookieValue);
  3400. }
  3401. }
  3402. return "";
  3403. }
  3404.  
  3405. /**
  3406. * 随机数生成
  3407. * @param {number} numDigits 位数
  3408. * @returns {number}
  3409. */
  3410. function OJB_getRandomNumber(numDigits) {
  3411. let min = Math.pow(10, numDigits - 1);
  3412. let max = Math.pow(10, numDigits) - 1;
  3413. return Math.floor(Math.random() * (max - min + 1)) + min;
  3414. }
  3415.  
  3416. /**
  3417. * 防抖函数
  3418. * @param {Function} callback 回调函数
  3419. * @returns {Function}
  3420. */
  3421. function OJB_debounce(callback) {
  3422. let timer;
  3423. let immediateExecuted = false;
  3424. const delay = 500;
  3425. return function () {
  3426. clearTimeout(timer);
  3427. if (!immediateExecuted) { callback.call(this); immediateExecuted = true; }
  3428. timer = setTimeout(() => { immediateExecuted = false; }, delay);
  3429. };
  3430. }
  3431.  
  3432. /**
  3433. * 为元素添加鼠标拖拽支持
  3434. * @param {JQuery<HTMLElement>} element 要添加拖拽支持的元素
  3435. * @returns {void}
  3436. */
  3437. function OJB_addDraggable(element) {
  3438. let isDragging = false;
  3439. let x, y, l, t, nl, nt;
  3440. let isSpecialMouseDown = false; // 选取某些元素时不拖动
  3441.  
  3442. element.on('mousedown', function (e) {
  3443. isSpecialMouseDown = $(e.target).is('label, p, input, textarea, span, select, details, summary');
  3444. if (isSpecialMouseDown) return;
  3445.  
  3446. isDragging = true;
  3447. x = e.clientX;
  3448. y = e.clientY;
  3449. l = element.offset().left - $(window).scrollLeft();
  3450. t = element.offset().top - $(window).scrollTop();
  3451.  
  3452. element.css({ left: l + 'px', top: t + 'px', transform: 'none' });
  3453.  
  3454. $(document).on("mousemove", drag);
  3455. $(document).on("mouseup", stopDrag);
  3456. element.css('cursor', 'all-scroll');
  3457. });
  3458.  
  3459. const drag = (e) => {
  3460. if (!isDragging) return;
  3461. // 不执行拖动操作
  3462. if ($(e.target).is('label, p, input, textarea, span') || isSpecialMouseDown && !$(e.target).is('input, textarea')) return;
  3463. e.preventDefault();
  3464.  
  3465. const nx = e.clientX;
  3466. const ny = e.clientY;
  3467. nl = nx - (x - l);
  3468. nt = ny - (y - t);
  3469. element.css({ transform: `translate(${nx - x}px, ${ny - y}px)` });
  3470. };
  3471.  
  3472. const stopDrag = () => {
  3473. isDragging = false;
  3474. isSpecialMouseDown = false;
  3475. element.css('cursor', 'default');
  3476.  
  3477. // 在停止拖拽后,设置元素的left和top,并还原transform
  3478. element.css({ left: nl + 'px', top: nt + 'px', transform: 'none' });
  3479. $(document).off("mousemove", drag);
  3480. $(document).off("mouseup", stopDrag);
  3481. };
  3482. }
  3483.  
  3484. /**
  3485. * 切换元素的折叠/展开过渡动画
  3486. * @param {HTMLElement} element
  3487. */
  3488. function OJB_toggleCollapseExpand(element) {
  3489. // 设置transitionend事件监听器的函数
  3490. const setTransitionListener = (listener) => {
  3491. const listenerName = `transitionEndListener${Date.now()}`;
  3492. window[listenerName] = listener;
  3493. element.addEventListener('transitionend', listener);
  3494. element.setAttribute('data-transition-end-listener', listenerName);
  3495. };
  3496.  
  3497. // 移除事件监听器的函数
  3498. const removeTransitionListener = () => {
  3499. const transitionEndListenerName = element.getAttribute('data-transition-end-listener');
  3500. if (transitionEndListenerName) {
  3501. element.removeEventListener('transitionend', window[transitionEndListenerName]);
  3502. element.removeAttribute('data-transition-end-listener');
  3503. }
  3504. };
  3505.  
  3506. const collapsed = element.getAttribute('data-collapsed') === 'true';
  3507. const sectionHeight = element.scrollHeight;
  3508.  
  3509. // 移除事件监听器
  3510. removeTransitionListener();
  3511.  
  3512. // 设置初始样式
  3513. element.style.overflow = 'hidden';
  3514. element.style.transition = 'height 0.3s ease-out 0s';
  3515. element.style.height = collapsed ? `0px` : `${sectionHeight}px`;
  3516. element.style.opacity = collapsed ? '' : '1';
  3517.  
  3518. // 需要立即开始动画
  3519. requestAnimationFrame(() => {
  3520. // 设置结束样式
  3521. element.style.height = collapsed ? `${sectionHeight}px` : `0px`;
  3522. });
  3523.  
  3524. const transitionEndListener = (event) => {
  3525. if (event.propertyName === 'height') {
  3526. if (collapsed) {
  3527. // 展开后的设置
  3528. element.style.height = '';
  3529. element.style.overflow = '';
  3530. } else {
  3531. // 折叠后的设置
  3532. element.style.opacity = '0';
  3533. }
  3534. removeTransitionListener();
  3535. }
  3536. };
  3537.  
  3538. setTransitionListener(transitionEndListener);
  3539.  
  3540. // 更新data-collapsed属性
  3541. element.setAttribute('data-collapsed', collapsed ? 'false' : 'true');
  3542. }
  3543.  
  3544. /**
  3545. * 获取外部JSON并转换为Object
  3546. * @param {string} url JSON Url
  3547. * @returns {Promise<Object>} JSON Object
  3548. */
  3549. async function OJB_getExternalJSON(url) {
  3550. const response = await OJB_GMRequest({
  3551. method: "GET",
  3552. url: url
  3553. });
  3554. try {
  3555. return JSON.parse(response.responseText);
  3556. } catch (e) {
  3557. throw new Error(`JSON parse error\n${e}`);
  3558. }
  3559. }
  3560.  
  3561. /**
  3562. * 创建确认对话框dialog
  3563. * @param {string} title 标题
  3564. * @param {string} content 内容
  3565. * @param {string[]} buttons 按钮 (取消 确定) 可以为null
  3566. * @param {boolean} renderMarkdown 是否使用markdown渲染文本
  3567. * @returns {Promise<boolean>} 用户点击了确定按钮返回true, 否则返回false
  3568. */
  3569. function OJB_createDialog(title, content, buttons, renderMarkdown = false) {
  3570. return new Promise(resolve => {
  3571. let contentHtml = content;
  3572.  
  3573. if (renderMarkdown) {
  3574. const md = window.markdownit();
  3575. contentHtml = md.render(content);
  3576. }
  3577.  
  3578. const dialog = $(`
  3579. <dialog class="OJBetter_modal">
  3580. <h2>${title}</h2>
  3581. <div class="content">${contentHtml}</div>
  3582. </dialog>
  3583. `);
  3584. const buttonbox = $(`<div class="buttons"></div>`);
  3585. const cancelButton = $(`<button class="cancelButton">${buttons[0]}</button>`)
  3586. .addClass("secondary");
  3587. const continueButton = $(`<button class="continueButton">${buttons[1]}</button>`);
  3588. if (buttons[0] !== null) buttonbox.append(cancelButton);
  3589. if (buttons[1] !== null) buttonbox.append(continueButton);
  3590. dialog.append(buttonbox);
  3591. $('body').before(dialog);
  3592.  
  3593. OJB_showModal(dialog);
  3594. OJB_addDraggable(dialog);
  3595.  
  3596. continueButton.click(function () {
  3597. OJB_closeAndRemoveModal(dialog);
  3598. resolve(true);
  3599. });
  3600.  
  3601. cancelButton.click(function () {
  3602. OJB_closeAndRemoveModal(dialog);
  3603. resolve(false);
  3604. });
  3605. });
  3606. }
  3607.  
  3608. /**
  3609. * 显示模态对话框并阻止页面滚动,同时考虑滚动条宽度变化和原始marginRight
  3610. * @param {JQuery<HTMLElement>} element
  3611. */
  3612. function OJB_showModal(element) {
  3613. const dialog = element.get(0);
  3614. dialog.showModal();
  3615. OJBetter.state.openDialogCount++;
  3616.  
  3617. if (OJBetter.state.openDialogCount === 1) {
  3618. const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
  3619. // 获取原始的body marginRight,考虑到可能的非数字值,比如auto
  3620. const originalMarginRight = window.getComputedStyle(document.body).marginRight;
  3621. const marginRightValue = parseFloat(originalMarginRight) || 0; // 将非数字值转换为0
  3622.  
  3623. if (scrollbarWidth > 0) {
  3624. // 保存原始的marginRight,并设置新的值以补偿滚动条宽度
  3625. document.body.style.setProperty('--original-margin-right', originalMarginRight);
  3626. document.body.style.marginRight = `${marginRightValue + scrollbarWidth}px`;
  3627. }
  3628.  
  3629. // 保存原始的overflow样式
  3630. document.body.setAttribute('data-original-overflow', document.body.style.overflow);
  3631. document.body.style.overflow = 'hidden';
  3632. }
  3633.  
  3634. const allowScrollIfNeeded = () => {
  3635. OJBetter.state.openDialogCount--;
  3636. if (OJBetter.state.openDialogCount === 0) {
  3637. // 恢复原始的body marginRight和overflow样式
  3638. const originalMarginRight = document.body.style.getPropertyValue('--original-margin-right');
  3639. document.body.style.marginRight = originalMarginRight;
  3640. document.body.style.removeProperty('--original-margin-right');
  3641.  
  3642. const originalOverflow = document.body.getAttribute('data-original-overflow');
  3643. document.body.style.overflow = originalOverflow;
  3644. document.body.removeAttribute('data-original-overflow');
  3645. }
  3646. };
  3647.  
  3648. dialog.addEventListener('close', allowScrollIfNeeded);
  3649. }
  3650.  
  3651. /**
  3652. * 关闭并移除模态对话框
  3653. * @param {JQuery<HTMLElement>} element
  3654. */
  3655. function OJB_closeAndRemoveModal(element) {
  3656. const dialog = element.get(0);
  3657. dialog.close();
  3658. dialog.remove();
  3659. }
  3660.  
  3661. /**
  3662. * 关闭并移除模态对话框
  3663. * @param {JQuery<HTMLElement>} element
  3664. */
  3665. function OJB_closeModal(element) {
  3666. const dialog = element.get(0);
  3667. dialog.close();
  3668. }
  3669.  
  3670. /**
  3671. * 清除i18next的缓存数据并刷新
  3672. */
  3673. function clearI18nextCache() {
  3674. Object.keys(localStorage)
  3675. .filter(key => key.startsWith('i18next_res_'))
  3676. .forEach(key => localStorage.removeItem(key));
  3677. window.location.reload();
  3678. }
  3679.  
  3680. /**
  3681. * 更新检查
  3682. */
  3683. async function checkScriptVersion() {
  3684. try {
  3685. const versionResponse = await OJB_GMRequest({
  3686. method: "GET",
  3687. url: "https://aowuucdn.oss-accelerate.aliyuncs.com/script/versions.json",
  3688. timeout: 10 * 1e3,
  3689. nocache: true
  3690. });
  3691. const versionData = JSON.parse(versionResponse.responseText);
  3692. const { 'codeforces-better': { dev: version_dev, release: version_release } } = versionData;
  3693. const baseUrls = {
  3694. greasyfork: 'https://update.gf.qytechs.cn/scripts/465777/Codeforces%20Better%21.user.js',
  3695. github: `https://github.com/beijixiaohu/OJBetter/raw/main/script/${OJBetter.about.updateChannel}/codeforces-better.user.js`,
  3696. aliyunoss: `https://aowuucdn.oss-accelerate.aliyuncs.com/script/${OJBetter.about.updateChannel}/codeforces-better.user.js`
  3697. };
  3698. /** @type {string} 更新跳转url */
  3699. const updateUrl = baseUrls[OJBetter.about.updateSource];
  3700. /** @type {string} 是否暂时跳过cookie */
  3701. const skipUpdate = OJB_getCookie("skipUpdate");
  3702. /** @type {string} 当前更新频道的最新版本 */
  3703. const version = OJBetter.about.updateChannel == "release" ? version_release : version_dev;
  3704. if (OJB_compareVersions(version, OJBetter.state.version) === 1 && skipUpdate !== "true") {
  3705. const updateConfirmed = await OJB_createDialog(
  3706. i18next.t('update.title', { ns: 'dialog', scriptName: OJBetter.state.name }),
  3707. i18next.t('update.content', { ns: 'dialog', oldVersion: OJBetter.state.version, newVersion: version }),
  3708. [
  3709. i18next.t('update.buttons.0', { ns: 'dialog' }),
  3710. i18next.t('update.buttons.1', { ns: 'dialog' })
  3711. ],
  3712. true
  3713. );
  3714.  
  3715. if (updateConfirmed) {
  3716. window.location.href = updateUrl;
  3717. } else {
  3718. document.cookie = "skipUpdate=true; expires=session; path=/";
  3719. }
  3720. }
  3721. } catch (error) {
  3722. console.error("Update check failed: ", error);
  3723. }
  3724. }
  3725.  
  3726. /**
  3727. * 公告
  3728. */
  3729. async function showAnnounce() {
  3730. /** @type {string} 最新公告版本*/
  3731. const lastAnnounceVer = i18next.t('lastVersion', { ns: 'announce' });
  3732. if (OJB_compareVersions(OJBetter.state.version, OJBetter.state.lastAnnounceVer) === 1) {
  3733. const title = `🎉${i18next.t('announce.title', { ns: 'dialog' })} ${OJBetter.state.version}`;
  3734. /** @type {Boolean} 是否是新的公告 */
  3735. const isNewAnnounceVer = OJB_compareVersions(lastAnnounceVer, OJBetter.state.lastReadAnnounceVer) === 1;
  3736. /** @type {Boolean} 是否展示新的公告(高于当前版本的测试公告不展示) */
  3737. const showNewAnnounceVer = OJB_compareVersions(lastAnnounceVer, OJBetter.state.version) !== 1;
  3738. /**
  3739. * 获取最后三个公告的内容
  3740. * @param {string} lastAnnounceVer
  3741. * @returns {string} 公告内容
  3742. */
  3743. const getLastThreeAnnounceContent = function (lastAnnounceVer) {
  3744. let content = "";
  3745. for (let i = 0; i < 3; i++) {
  3746. content += `### ${lastAnnounceVer}\n\n`;
  3747. content += i18next.t(`${lastAnnounceVer}`, { ns: 'announce' });
  3748. content += "\n\n";
  3749. lastAnnounceVer = OJB_getPreviousVersion(lastAnnounceVer);
  3750. }
  3751. return content;
  3752. };
  3753.  
  3754. const content = (() => {
  3755. if (isNewAnnounceVer && showNewAnnounceVer) {
  3756. return `${i18next.t('announce.prefix', { ns: 'dialog' })}\n\n${getLastThreeAnnounceContent(lastAnnounceVer)}`;
  3757. } else {
  3758. return i18next.t('announce.divContent', { ns: 'dialog' });
  3759. }
  3760. })();
  3761. const ok = await OJB_createDialog(
  3762. title,
  3763. content,
  3764. [
  3765. null,
  3766. i18next.t('announce.buttons.0', { ns: 'dialog' })
  3767. ],
  3768. true
  3769. ); //跳过折叠块确认
  3770. if (ok) {
  3771. if (isNewAnnounceVer && showNewAnnounceVer) {
  3772. GM_setValue('lastReadAnnounceVer', lastAnnounceVer);
  3773. }
  3774. GM_setValue('lastAnnounceVer', OJBetter.state.version);
  3775. }
  3776. }
  3777. };
  3778.  
  3779. /**
  3780. * 提示信息类
  3781. */
  3782. class LoadingMessage {
  3783. constructor() {
  3784. this._statusElement = null;
  3785. this._isDisplayed = false;
  3786. this.init();
  3787. }
  3788.  
  3789. /**
  3790. * 初始化加载提示信息
  3791. */
  3792. init() {
  3793. this._statusElement = this.createStatusElement();
  3794. this.insertStatusElement();
  3795. }
  3796.  
  3797. /**
  3798. * 创建提示信息元素
  3799. */
  3800. createStatusElement() {
  3801. const statusElement = $("<div></div>").addClass("alert OJBetter_alert")
  3802. .css({
  3803. "margin": "1em",
  3804. "text-align": "center",
  3805. "position": "relative"
  3806. }).hide();
  3807. return statusElement;
  3808. }
  3809.  
  3810. /**
  3811. * 插入提示信息
  3812. * @returns {void}
  3813. */
  3814. insertStatusElement() {
  3815. (OJBetter.typeOfPage.is_mSite ? $("header") : $(".menu-box:first").next()).after(this._statusElement);
  3816. }
  3817.  
  3818. /**
  3819. * 显示提示信息
  3820. */
  3821. showStatus() {
  3822. this._statusElement.show();
  3823. this._isDisplayed = true;
  3824. }
  3825.  
  3826. /**
  3827. * 隐藏提示信息
  3828. */
  3829. hideStatus() {
  3830. this._statusElement.fadeOut(500);
  3831. this._isDisplayed = false;
  3832. }
  3833.  
  3834. /**
  3835. * 移除提示信息
  3836. */
  3837. removeStatus() {
  3838. this._statusElement.remove();
  3839. this._isDisplayed = false;
  3840. }
  3841.  
  3842. /**
  3843. * 更新提示信息
  3844. * @param {string} text 提示信息文本
  3845. * @param {string} type 提示信息类型,可选值:info, success, warning, error
  3846. * @param {number} timeout 提示信息显示的持续时间(毫秒), 默认为无限长
  3847. */
  3848. updateStatus(text, type = 'info', timeout = Infinity, isMarkdown = false) {
  3849. if (isMarkdown) {
  3850. var md = window.markdownit({
  3851. html: !is_escapeHTML,
  3852. });
  3853. text = md.render(text);
  3854. }
  3855. this._statusElement.html(text).removeClass("alert-info alert-success alert-warning alert-error").addClass(`alert-${type}`);
  3856. if (!this._isDisplayed) {
  3857. this.showStatus();
  3858. }
  3859. if (timeout !== Infinity) {
  3860. setTimeout(() => {
  3861. this.hideStatus();
  3862. }, timeout);
  3863. }
  3864. }
  3865. }
  3866.  
  3867. /**
  3868. * 获取网站本地化的数据
  3869. * @param {*} localizationLanguage 本地化语言
  3870. * @returns {Promise<Object>} 本地化数据
  3871. */
  3872. async function getLocalizeWebsiteJson(localizationLanguage) {
  3873. let data = await OJBetter.common.database.localizeSubsData.get(localizationLanguage);
  3874. let url = localizationLanguage === "zh" ?
  3875. "https://aowuucdn.oss-accelerate.aliyuncs.com/resources/subs/Codeforces-subs.json" :
  3876. `https://aowuucdn.oss-accelerate.aliyuncs.com/i18n/${localizationLanguage}/resources/subs/Codeforces-subs.json`;
  3877. if (data) data = data.data;
  3878. if (!data) {
  3879. // 如果本地没有数据,从远端获取并保存
  3880. data = await OJB_getExternalJSON(url);
  3881. await OJBetter.common.database.localizeSubsData.put({ lang: localizationLanguage, data: data });
  3882. } else {
  3883. // 如果本地有数据,先返回旧数据,然后在后台更新
  3884. (async () => {
  3885. try {
  3886. const newData = await OJB_getExternalJSON(url);
  3887. await OJBetter.common.database.localizeSubsData.put({ lang: localizationLanguage, data: newData });
  3888. } catch (error) {
  3889. console.error('Failed to update localization data:', error);
  3890. }
  3891. })();
  3892. }
  3893. return data;
  3894. }
  3895.  
  3896. /**
  3897. * 网站本地化替换
  3898. * @returns
  3899. */
  3900. async function localizeWebsite() {
  3901. if (OJBetter.localization.websiteLang === "initial") return;
  3902.  
  3903. // 设置网页语言
  3904. var htmlTag = document.getElementsByTagName("html")[0];
  3905. htmlTag.setAttribute("lang", OJBetter.localization.websiteLang);
  3906.  
  3907. // 获取网站本地化的数据
  3908. var subs = await getLocalizeWebsiteJson(OJBetter.localization.websiteLang);
  3909.  
  3910. /**
  3911. * 文本节点遍历替换
  3912. * @param {JQuery} $nodes jQuery对象
  3913. * @param {Object} textReplaceRules 文本替换规则对象
  3914. */
  3915. function traverseTextNodes($nodes, textReplaceRules) {
  3916. if (!$nodes) return;
  3917.  
  3918. $nodes.each(function () {
  3919. let node = this;
  3920. if (node.nodeType === Node.TEXT_NODE) {
  3921. Object.keys(textReplaceRules).forEach(match => {
  3922. const replace = textReplaceRules[match];
  3923. const regex = new RegExp(match, 'g');
  3924. node.textContent = node.textContent.replace(regex, replace);
  3925. });
  3926. } else {
  3927. $(node).contents().each(function () {
  3928. traverseTextNodes($(this), textReplaceRules);
  3929. });
  3930. }
  3931. });
  3932. }
  3933.  
  3934. /**
  3935. * value替换
  3936. * @param {JQuery} $nodes jQuery对象
  3937. * @param {Object} valueReplaceRules 值替换规则对象
  3938. */
  3939. function traverseValueNodes($nodes, valueReplaceRules) {
  3940. if (!$nodes) return;
  3941.  
  3942. $nodes.each(function () {
  3943. let $node = $(this);
  3944. if ($node.is('[value]')) {
  3945. Object.keys(valueReplaceRules).forEach(match => {
  3946. const replace = valueReplaceRules[match];
  3947. const regex = new RegExp(match, 'g');
  3948. let currentValue = $node.val();
  3949. let newValue = currentValue.replace(regex, replace);
  3950. $node.val(newValue);
  3951. });
  3952. } else {
  3953. $node.children().each(function () {
  3954. traverseValueNodes($(this), valueReplaceRules);
  3955. });
  3956. }
  3957. });
  3958. }
  3959.  
  3960. /**
  3961. * 严格的文本节点遍历替换
  3962. * @param {JQuery} $node jQuery对象
  3963. * @param {Object} textReplaceRules 文本替换规则对象
  3964. */
  3965. function strictTraverseTextNodes($nodes, textReplaceRules) {
  3966. if (!$nodes) return;
  3967.  
  3968. $nodes.each(function () {
  3969. let $node = $(this);
  3970. if ($node.nodeType === Node.TEXT_NODE) {
  3971. const trimmedNodeText = $node.textContent.trim();
  3972. Object.keys(textReplaceRules).forEach(match => {
  3973. if (trimmedNodeText === match) {
  3974. $node.textContent = textReplaceRules[match];
  3975. }
  3976. });
  3977. } else {
  3978. $($node).contents().each(function () {
  3979. strictTraverseTextNodes($(this), textReplaceRules);
  3980. });
  3981. }
  3982. });
  3983. }
  3984.  
  3985. /**
  3986. * 应用文本替换
  3987. */
  3988. let commonReplacements = subs.commonReplacements;
  3989. Object.entries(commonReplacements).forEach(([key, value]) => {
  3990. const classSelectors = Array.isArray(value.class) ? value.class : [value.class]; // 兼容,class的值可以为数组或者字符串
  3991. classSelectors.forEach(classSelector => {
  3992. if (value.isStrict) {
  3993. strictTraverseTextNodes($(`${classSelector}`), value.rules);
  3994. } else {
  3995. traverseTextNodes($(`${classSelector}`), value.rules);
  3996. }
  3997. });
  3998. });
  3999.  
  4000. // 测试
  4001. {
  4002. // var translations = {
  4003. //
  4004. // };
  4005. // traverseTextNodes($('xxx'), translations);
  4006. };
  4007.  
  4008. /**
  4009. * 应用value替换
  4010. */
  4011. let InputValueReplacements = subs.InputValueReplacements;
  4012. Object.entries(InputValueReplacements).forEach(([key, value]) => {
  4013. const classSelectors = Array.isArray(value.class) ? value.class : [value.class];
  4014. classSelectors.forEach(classSelector => {
  4015. traverseValueNodes($(`${classSelector}`), value.rules);
  4016. });
  4017. });
  4018.  
  4019. // 杂项
  4020. (function () {
  4021. // 选项汉化input[type="radio"]
  4022. var translations = {
  4023. "as individual participant": "个人",
  4024. "as a team member": "作为一个团队成员",
  4025. };
  4026. $('input[type="radio"]').each(function () {
  4027. var tag = $(this).parent().contents().filter(function () {
  4028. return this.nodeType === Node.TEXT_NODE;
  4029. });
  4030. for (var i = 0; i < tag.length; i++) {
  4031. var text = tag[i].textContent.trim();
  4032. if (translations.hasOwnProperty(text)) {
  4033. $(this).addClass(text);
  4034. tag[i].replaceWith(translations[text]);
  4035. break;
  4036. }
  4037. }
  4038. });
  4039. })();
  4040. (function () {
  4041. var translations = {
  4042. "(standard input\/output)": "标准输入/输出",
  4043. };
  4044. $("div.notice").each(function () {
  4045. var tag = $(this).children().eq(0).text();
  4046. for (var property in translations) {
  4047. if (tag.match(property)) {
  4048. $(this).children().eq(0).text(translations[property]);
  4049. break;
  4050. }
  4051. }
  4052. });
  4053. })();
  4054.  
  4055. // 轻量站特殊
  4056. if (OJBetter.typeOfPage.is_mSite) {
  4057. traverseTextNodes($('nav'), commonReplacements['.second-level-menu']['rules']);
  4058. }
  4059. if (OJBetter.typeOfPage.is_mSite) {
  4060. (function () {
  4061. var translations = {
  4062. "Announcements": "公告",
  4063. "Submissions": "提交记录",
  4064. "Contests": "比赛",
  4065. };
  4066. $(".caption").each(function () {
  4067. var optionValue = $(this).text();
  4068. if (translations[optionValue]) {
  4069. $(this).text(translations[optionValue]);
  4070. }
  4071. });
  4072. })();
  4073. }
  4074. };
  4075.  
  4076. /**
  4077. * i18next初始化
  4078. */
  4079. async function initI18next() {
  4080. return new Promise((resolve, reject) => {
  4081. i18next
  4082. .use(i18nextChainedBackend)
  4083. .init({
  4084. lng: OJBetter.localization.scriptLang,
  4085. ns: ['common', 'settings', 'config', 'dialog', 'alert', 'translator',
  4086. 'button', 'codeEditor', 'comments', 'announce', 'logMessage'], // 命名空间列表
  4087. defaultNS: 'settings',
  4088. fallbackLng: ['zh', OJBetter.translation.targetLang],
  4089. load: 'currentOnly',
  4090. debug: false,
  4091. backend: {
  4092. backends: [
  4093. i18nextLocalStorageBackend,
  4094. i18nextHttpBackend
  4095. ],
  4096. backendOptions: [{
  4097. prefix: 'i18next_res_',
  4098. expirationTime: 7 * 24 * 60 * 60 * 1000,
  4099. defaultVersion: `v${OJBetter.state.version}`,
  4100. store: typeof window !== 'undefined' ? window.localStorage : null
  4101. }, {
  4102. /* options for secondary backend */
  4103. loadPath: (lng, ns) => {
  4104. if (lng[0] === 'zh' || lng[0] === 'zh-Hans') {
  4105. return `https://aowuucdn.oss-accelerate.aliyuncs.com/resources/locales/Codeforces/${ns}.json`;
  4106. }
  4107. return `https://aowuucdn.oss-accelerate.aliyuncs.com/i18n/${lng}/resources/locales/Codeforces/${ns}.json`;
  4108. }
  4109. }]
  4110. }
  4111. }, (err, t) => {
  4112. if (err) {
  4113. reject(err);
  4114. } else {
  4115. jqueryI18next.init(i18next, $);
  4116. resolve(t);
  4117. }
  4118. });
  4119. });
  4120. };
  4121.  
  4122. /**
  4123. * 抽象命令类
  4124. */
  4125. class Command {
  4126. execute() { }
  4127. undo() { }
  4128. }
  4129.  
  4130. /**
  4131. * 命令调用者
  4132. */
  4133. class CommandInvoker {
  4134. constructor() {
  4135. this.history = [];
  4136. }
  4137.  
  4138. /**
  4139. * 执行命令
  4140. * @param {Command} command 命令对象
  4141. */
  4142. execute(command) {
  4143. this.history.push(command);
  4144. command.execute();
  4145. }
  4146.  
  4147. /**
  4148. * 撤销命令
  4149. */
  4150. undo() {
  4151. const command = this.history.pop();
  4152. if (command) {
  4153. command.undo();
  4154. }
  4155. }
  4156. }
  4157.  
  4158. /**
  4159. * 接收者
  4160. */
  4161. class DOMContainer {
  4162. /**
  4163. * @param {JQueryObject} element 容器对象
  4164. */
  4165. constructor(element) {
  4166. this.containerElement = element;
  4167. }
  4168.  
  4169. /**
  4170. * 添加元素
  4171. * @param {JQueryObject} element 元素对象
  4172. * @returns {JQueryObject} 添加的元素对象
  4173. */
  4174. add(element) {
  4175. this.containerElement.append(element);
  4176. return this.containerElement.children().last();
  4177. }
  4178.  
  4179. /**
  4180. * 删除元素
  4181. * @param {JQueryObject} element 元素对象
  4182. */
  4183. remove(element) {
  4184. $(element).remove();
  4185. }
  4186. }
  4187.  
  4188. /**
  4189. * 具体命令类:添加元素
  4190. */
  4191. class AddElementCommand extends Command {
  4192. /**
  4193. * @param {DOMContainer} receiver 接收者
  4194. * @param {JQueryObject} element 元素对象
  4195. */
  4196. constructor(receiver, element) {
  4197. super();
  4198. this.receiver = receiver;
  4199. this.element = element;
  4200. this.addedElement = null;
  4201. }
  4202.  
  4203. execute() {
  4204. this.addedElement = this.receiver.add(this.element);
  4205. }
  4206.  
  4207. undo() {
  4208. if (this.addedElement) {
  4209. this.receiver.remove(this.addedElement);
  4210. }
  4211. }
  4212. }
  4213.  
  4214. /**
  4215. * 具体命令类:删除元素
  4216. */
  4217. class RemoveElementCommand extends Command {
  4218. /**
  4219. * @param {DOMContainer} receiver 接收者
  4220. * @param {JQueryObject} element 元素对象
  4221. */
  4222. constructor(receiver, element) {
  4223. super();
  4224. this.receiver = receiver;
  4225. this.element = element;
  4226. this.parent = $(element).parent();
  4227. this.nextSibling = $(element).next();
  4228. }
  4229.  
  4230. execute() {
  4231. this.receiver.remove(this.element);
  4232. }
  4233.  
  4234. undo() {
  4235. if (this.nextSibling.length > 0) {
  4236. $(this.element).insertBefore(this.nextSibling);
  4237. } else {
  4238. this.parent.append(this.element);
  4239. }
  4240. }
  4241. }
  4242.  
  4243. /**
  4244. * 验证器
  4245. */
  4246. class Validator {
  4247. /**
  4248. * 表单必填项空值校验
  4249. */
  4250. static required(structure) {
  4251. let config = {};
  4252. let allFieldsValid = true;
  4253. for (const key in structure) {
  4254. let value = key.type == 'checkbox' ?
  4255. $(key).prop("checked") : $(key).val();
  4256.  
  4257. config[structure[key].value] = value;
  4258.  
  4259. if (value || structure[key].require === false) {
  4260. $(key).removeClass('is_null');
  4261. } else {
  4262. $(key).addClass('is_null');
  4263. allFieldsValid = false;
  4264. }
  4265. }
  4266. return {
  4267. valid: allFieldsValid,
  4268. config: config
  4269. };
  4270. }
  4271.  
  4272. /**
  4273. * 表单合法性校验
  4274. */
  4275. static checkKeyValuePairs(structure, config) {
  4276. let errorKeys = [];
  4277. let allFieldsValid = true;
  4278.  
  4279. for (const key in structure) {
  4280. const { check, value } = structure[key];
  4281. const fieldValue = config[value];
  4282.  
  4283. // 如果字段没有值或校验类型不匹配,则跳过当前迭代
  4284. if (!fieldValue) continue;
  4285.  
  4286. let isValid = true;
  4287. switch (check) {
  4288. case 'keyValuePairs':
  4289. isValid = Validator.keyValuePairs(fieldValue);
  4290. break;
  4291. case 'dotSeparatedPath':
  4292. isValid = Validator.validateDotSeparatedPath(fieldValue);
  4293. break;
  4294. default:
  4295. // 没有匹配的校验类型
  4296. continue;
  4297. }
  4298.  
  4299. Validator.toggleErrorDisplay(key, isValid);
  4300. if (!isValid) {
  4301. allFieldsValid = false;
  4302. errorKeys.push(key);
  4303. }
  4304. }
  4305.  
  4306. return {
  4307. valid: allFieldsValid,
  4308. errorKeys: errorKeys
  4309. };
  4310. }
  4311.  
  4312. /**
  4313. * 切换错误信息的显示和隐藏
  4314. * @param {string} key - 字段的键
  4315. * @param {boolean} isValid - 字段值是否有效
  4316. */
  4317. static toggleErrorDisplay(key, isValid) {
  4318. const errorMessage = i18next.t('common.unValid', { ns: 'settings' });
  4319. const $errorSpan = $(key).prev('span.text-error');
  4320. if (!isValid) {
  4321. if (!$errorSpan.length) {
  4322. $(key).before(`<span class="text-error" style="color: red;">${errorMessage}</span>`);
  4323. }
  4324. } else {
  4325. $errorSpan.remove();
  4326. }
  4327. }
  4328.  
  4329. /**
  4330. * 键值对合法性校验
  4331. * @param {string} value
  4332. * @returns {boolean}
  4333. */
  4334. static keyValuePairs(value) {
  4335. const keyValuePairs = value.split('\n');
  4336. // 允许值中包含空格和冒号
  4337. const regex = /^[a-zA-Z0-9_-]+\s*:\s*.+$/;
  4338. return keyValuePairs.every(pair => regex.test(pair));
  4339. }
  4340.  
  4341.  
  4342. /**
  4343. * 点分隔符路径格式校验,允许加减运算
  4344. * @param {string} path
  4345. * @returns {boolean}
  4346. */
  4347. static validateDotSeparatedPath(path) {
  4348. // 正则表达式允许标识符之间有点号,标识符可以包含加减运算
  4349. const regex = /^([a-zA-Z0-9_-]+(\s*[\+\-]\s*[a-zA-Z0-9_-]+)*\.)*([a-zA-Z0-9_-]+(\s*[\+\-]\s*[a-zA-Z0-9_-]+)*)$/;
  4350. return regex.test(path);
  4351. }
  4352. }
  4353.  
  4354. /**
  4355. * 配置管理
  4356. */
  4357. class ConfigManager {
  4358. /**
  4359. * @param {HTMLElement} element - 挂载容器
  4360. * @param {string} prefix - 前缀
  4361. * @param {object} tempConfig - 配置内容
  4362. * @param {object} structure - 配置结构
  4363. * @param {object} configHTML - 配置编辑页面HTML
  4364. * @param {boolean} allowChoice - 是否允许选择列表项
  4365. */
  4366. constructor(element, prefix, tempConfig, structure, configHTML, allowChoice = true) {
  4367. /** @param 设置面板DIV */
  4368. this.settingMenuDiv = $('#OJBetter_setting_menu');
  4369. this.element = $(element);
  4370. this.prefix = prefix;
  4371. this.tempConfig = tempConfig;
  4372. this.structure = structure;
  4373. this.configHTML = configHTML;
  4374. this.allowChoice = allowChoice;
  4375.  
  4376. this.controlTip = null;
  4377. this.config_bar_list = null;
  4378. this.config_bar_ul = null;
  4379. this.config_add_button = null;
  4380. this.menu = null;
  4381. this.editItem = null;
  4382. this.deleteItem = null;
  4383.  
  4384. // 绑定方法
  4385. this.onAdd = this.onAdd.bind(this);
  4386. this.onEdit = this.onEdit.bind(this);
  4387. this.onDelete = this.onDelete.bind(this);
  4388. this.createListItemElement = this.createListItemElement.bind(this);
  4389.  
  4390. this.lastItemId = 0; // 列表中当前最后一个元素的id号
  4391. this.init();
  4392. }
  4393.  
  4394. init() {
  4395. this.createControlBar();
  4396. this.createContextMenu();
  4397. this.renderList();
  4398. }
  4399.  
  4400. /**
  4401. * 创建控制栏
  4402. */
  4403. createControlBar() {
  4404. this.controlTip = $(`<div id='${this.prefix}configControlTip' style='color:red;'></div>`);
  4405. this.config_bar_list = $(`<div class='config_bar_list' id='${this.prefix}config_bar_list'></div>`);
  4406. this.config_bar_ul = $(`<ul class='config_bar_ul' id='${this.prefix}config_bar_ul'></ul>`);
  4407. this.element.append(this.controlTip);
  4408. this.element.append(this.config_bar_list);
  4409. this.config_bar_list.append(this.config_bar_ul);
  4410. }
  4411.  
  4412. /**
  4413. * 创建右键菜单
  4414. */
  4415. createContextMenu() {
  4416. const menu = $(`<div id='config_bar_menu' style='display: none;'></div>`);
  4417. const editItem = $(`
  4418. <div class='config_bar_menu_item' id='config_bar_menu_edit'>
  4419. ${i18next.t('contextMenu.edit', { ns: 'translator' })}
  4420. </div>`);
  4421. const deleteItem = $(`
  4422. <div class='config_bar_menu_item' id='config_bar_menu_delete'>
  4423. ${i18next.t('contextMenu.delete', { ns: 'translator' })}
  4424. </div>`);
  4425. menu.append(editItem);
  4426. menu.append(deleteItem);
  4427. this.editItem = editItem;
  4428. this.deleteItem = deleteItem;
  4429. this.menu = menu;
  4430. this.settingMenuDiv.append(menu);
  4431. }
  4432.  
  4433. /**
  4434. * 关闭右键菜单
  4435. */
  4436. closeContextMenu() {
  4437. this.menu.css({ display: "none" });
  4438. }
  4439.  
  4440. /**
  4441. * 创建列表项
  4442. * @param {string} text - 列表项文本
  4443. * @returns {HTMLElement} - 列表项
  4444. */
  4445. createListItemElement(text) {
  4446. const id = OJB_getRandomNumber(4);
  4447. const li = $("<li></li>");
  4448. const radio = $(`<input type='radio' name='${this.prefix}config_item'></input>`)
  4449. .attr("value", text)
  4450. .attr("id", id)
  4451. .attr("prev_id", this.lastItemId)
  4452. .appendTo(li);
  4453. if (!this.allowChoice) {
  4454. radio.prop("disabled", true);
  4455. }
  4456. const label = $(`<label for='${id}' class='config_bar_ul_li_text'>${text}</label>`).appendTo(li);
  4457.  
  4458.  
  4459. this.lastItemId = id;
  4460.  
  4461. // 添加右键菜单
  4462. li.on("contextmenu", (event) => {
  4463. event.preventDefault();
  4464. this.menu.css({
  4465. display: "block",
  4466. left: event.pageX, top: event.pageY
  4467. });
  4468.  
  4469. const deleteItem = this.deleteItem;
  4470. const editItem = this.editItem;
  4471.  
  4472. // 移除旧事件
  4473. deleteItem.off("click");
  4474. editItem.off("click");
  4475.  
  4476. // 获取 li 在 ul 中的索引
  4477. const index = li.index();
  4478.  
  4479. deleteItem.on("click", () => this.onDelete(index, li));
  4480. editItem.on("click", () => this.onEdit(index, li));
  4481.  
  4482. $(document).one("click", (event) => {
  4483. if (!this.menu.get(0).contains(event.target)) {
  4484. this.closeContextMenu();
  4485. deleteItem.off("click", () => this.onDelete);
  4486. editItem.off("click", () => this.onEdit);
  4487. }
  4488. });
  4489. });
  4490.  
  4491. return li;
  4492. }
  4493.  
  4494. /**
  4495. * 渲染配置列表
  4496. */
  4497. renderList() {
  4498. const list = this.config_bar_ul;
  4499. list.empty(); // 清空
  4500. this.tempConfig.configurations.forEach((item) => {
  4501. list.append(this.createListItemElement(item['name']));
  4502. });
  4503.  
  4504. // 添加按钮
  4505. let addButton = $(`<li id='${this.prefix}add_button' class="tempConfig_add_button">
  4506. <span>+ ${i18next.t('add', { ns: 'common' })}</span>
  4507. </li>`);
  4508. this.config_add_button = addButton;
  4509. list.append(addButton);
  4510. addButton.on("click", this.onAdd);
  4511. }
  4512.  
  4513. /**
  4514. * 添加配置项
  4515. */
  4516. onAdd() {
  4517. const configMenu = this.createConfigHTML();
  4518. const structure = this.structure;
  4519.  
  4520. configMenu.on("click", "#tempConfig_save", () => {
  4521.  
  4522. // 检查必填字段
  4523. const { valid, config } = Validator.required(structure);
  4524. if (!valid) return;
  4525.  
  4526. // 检查键值对
  4527. const { valid: checkOk, errorKey } = Validator.checkKeyValuePairs(structure, config);
  4528. if (!checkOk) return;
  4529.  
  4530. this.tempConfig.configurations.push(config);
  4531.  
  4532. this.createListItemElement(config.name).insertBefore(this.config_add_button);
  4533.  
  4534. configMenu.remove();
  4535. });
  4536.  
  4537. configMenu.on("click", ".btn-close", () => {
  4538. configMenu.remove();
  4539. });
  4540. }
  4541.  
  4542. /**
  4543. * 修改配置项
  4544. * @param {number} index - 配置项索引
  4545. * @param {HTMLElement} li - 配置项
  4546. * @returns {void}
  4547. */
  4548. onEdit(index, li) {
  4549. const configMenu = this.createConfigHTML();
  4550. const structure = this.structure;
  4551.  
  4552. this.closeContextMenu();
  4553.  
  4554. // 填充表单
  4555. for (const [key, { value, type }] of Object.entries(this.structure)) {
  4556. const configValue = this.tempConfig.configurations[index][value];
  4557. const $element = $(key);
  4558. if (type === 'checkbox') {
  4559. $element.prop("checked", configValue);
  4560. } else {
  4561. $element.val(configValue);
  4562. }
  4563. }
  4564.  
  4565. configMenu.on("click", "#tempConfig_save", () => {
  4566. // 检查必填字段
  4567. const { valid, config } = Validator.required(structure);
  4568. if (!valid) return;
  4569.  
  4570. // 检查键值对
  4571. const { valid: checkOk, errorKey } = Validator.checkKeyValuePairs(structure, config);
  4572. if (!checkOk) return;
  4573.  
  4574. // 更新配置
  4575. this.tempConfig.configurations[index] = config;
  4576. li.find('label').text(config.name);
  4577.  
  4578. OJB_closeAndRemoveModal(configMenu);
  4579. });
  4580.  
  4581. configMenu.on("click", ".btn-close", () => {
  4582. OJB_closeAndRemoveModal(configMenu);
  4583. });
  4584. }
  4585.  
  4586. /**
  4587. * 删除配置项
  4588. * @param {number} index - 配置项索引
  4589. * @param {HTMLElement} li - 配置项
  4590. * @returns {void}
  4591. */
  4592. onDelete(index, li) {
  4593. this.closeContextMenu();
  4594. this.tempConfig.configurations.splice(index, 1);
  4595. li.remove();
  4596. }
  4597.  
  4598. /**
  4599. * 创建配置编辑页面
  4600. * @returns {JQuery<HTMLElement>} 返回配置编辑页面
  4601. */
  4602. createConfigHTML() {
  4603. const configMenu = $(this.configHTML);
  4604. this.settingMenuDiv.after(configMenu);
  4605. OJB_showModal(configMenu);
  4606. OJB_addDraggable(configMenu);
  4607. elementLocalize(configMenu);
  4608. return configMenu;
  4609. }
  4610.  
  4611. /**
  4612. * 获取配置内容
  4613. * @returns {object} - 配置内容
  4614. */
  4615. getTempConfig() {
  4616. return this.tempConfig;
  4617. }
  4618.  
  4619. /**
  4620. * 注册(不可用)列表项选中改变监听
  4621. */
  4622. registerChoiceChange() {
  4623. this.config_bar_ul.on("change", "input[type='radio']", (event) => {
  4624. const value = event.target.value;
  4625. this.tempConfig.choice = value;
  4626. });
  4627. }
  4628. }
  4629.  
  4630. const OJBetter_setting_sidebar_HTML = `
  4631. <div class="OJBetter_setting_sidebar">
  4632. <ul>
  4633. <li><a href="#basic-settings" id="sidebar-basic-settings" class="active" data-i18n="settings:sidebar.basic"></a></li>
  4634. <li><a href="#l10n_settings" id="sidebar-l10n_settings" data-i18n="settings:sidebar.localization"></a></li>
  4635. <li><a href="#translation-settings" id="sidebar-translation-settings" data-i18n="settings:sidebar.translation"></a></li>
  4636. <li><a href="#clist_rating-settings" id="sidebar-clist_rating-settings" data-i18n="settings:sidebar.clist"></a></li>
  4637. <li><a href="#code_editor-settings" id="sidebar-code_editor-settings" data-i18n="settings:sidebar.monaco"></a></li>
  4638. <li><a href="#preference-settings" id="sidebar-preference-settings" data-i18n="settings:sidebar.preference"></a></li>
  4639. <li><a href="#dev-settings" id="sidebar-dev-settings" data-i18n="settings:sidebar.dev"></a></li>
  4640. <li><a href="#about-settings" id="sidebar-about-settings" data-i18n="settings:sidebar.about"></a></li>
  4641. </ul>
  4642. </div>
  4643. `;
  4644.  
  4645. const basic_settings_HTML = `
  4646. <div id="basic-settings" class="settings-page active">
  4647. <h3 data-i18n="settings:basic.title"></h3>
  4648. <hr>
  4649. <div class='OJBetter_setting_list' style="padding: 0px 10px;">
  4650. <span id="darkMode_span" data-i18n="settings:basic.darkMode.name"></span>
  4651. <div class="dark-mode-selection">
  4652. <label>
  4653. <input class="radio-input" type="radio" name="darkMode" value="dark" />
  4654. <span class="OJBetter_setting_menu_label_text"
  4655. data-i18n="settings:basic.darkMode.options.dark"></span>
  4656. <span class="radio-icon"> </span>
  4657. </label>
  4658. <label>
  4659. <input checked="" class="radio-input" type="radio" name="darkMode" value="light" />
  4660. <span class="OJBetter_setting_menu_label_text"
  4661. data-i18n="settings:basic.darkMode.options.light"></span>
  4662. <span class="radio-icon"> </span>
  4663. </label>
  4664. <label>
  4665. <input class="radio-input" type="radio" name="darkMode" value="follow" />
  4666. <span class="OJBetter_setting_menu_label_text"
  4667. data-i18n="settings:basic.darkMode.options.system"></span>
  4668. <span class="radio-icon"> </span>
  4669. </label>
  4670. </div>
  4671. </div>
  4672. <div class='OJBetter_setting_list'>
  4673. <label for="expandFoldingblocks" data-i18n="settings:basic.expandBlocks"></label>
  4674. <input type="checkbox" id="expandFoldingblocks" name="expandFoldingblocks">
  4675. </div>
  4676. <div class='OJBetter_setting_list'>
  4677. <label for="renderPerfOpt" data-i18n="settings:basic.renderOptimization.label"></label>
  4678. <div class="help_tip">
  4679. ${helpCircleHTML}
  4680. <div class="tip_text" data-i18n="[html]settings:basic.renderOptimization.helpText"></div>
  4681. </div>
  4682. <input type="checkbox" id="renderPerfOpt" name="renderPerfOpt">
  4683. </div>
  4684. <div class='OJBetter_setting_list'>
  4685. <label for="commentPaging" data-i18n="settings:basic.paging.label"></label>
  4686. <div class="help_tip">
  4687. ${helpCircleHTML}
  4688. <div class="tip_text" data-i18n="[html]settings:basic.paging.helpText"></div>
  4689. </div>
  4690. <input type="checkbox" id="commentPaging" name="commentPaging">
  4691. </div>
  4692. <div class='OJBetter_setting_list'>
  4693. <label for="showJumpToLuogu" data-i18n="settings:basic.luoguJump.label"></label>
  4694. <div class="help_tip">
  4695. ${helpCircleHTML}
  4696. <div class="tip_text" data-i18n="[html]settings:basic.luoguJump.helpText"></div>
  4697. </div>
  4698. <input type="checkbox" id="showJumpToLuogu" name="showJumpToLuogu">
  4699. </div>
  4700. <div class='OJBetter_setting_list'>
  4701. <label for="standingsRecolor" data-i18n="settings:basic.recolor.label"></label>
  4702. <div class="help_tip">
  4703. ${helpCircleHTML}
  4704. <div class="tip_text" data-i18n="[html]settings:basic.recolor.helpText"></div>
  4705. </div>
  4706. <input type="checkbox" id="standingsRecolor" name="standingsRecolor">
  4707. </div>
  4708. </div>
  4709. `;
  4710.  
  4711. const l10n_settings_HTML = `
  4712. <div id="l10n_settings" class="settings-page">
  4713. <h3 data-i18n="settings:localization.title"></h3>
  4714. <hr>
  4715. <div class='OJBetter_setting_list'>
  4716. <label for="scriptL10nLanguage" style="display: flex;" data-i18n="settings:localization.scriptLanguageLabel"></label>
  4717. <select id="scriptL10nLanguage" name="scriptL10nLanguage">
  4718. <option value="zh">简体中文</option>
  4719. <option value="zh-Hant">繁體中文</option>
  4720. <option value="en">English</option>
  4721. <option value="de">Deutsch</option>
  4722. <option value="fr">Français</option>
  4723. <option value="ko">한국어</option>
  4724. <option value="pt">Português</option>
  4725. <option value="ja">日本語</option>
  4726. <option value="es">Español</option>
  4727. <option value="it">Italiano</option>
  4728. <option value="hi">हिन्दी</option>
  4729. </select>
  4730. </div>
  4731. <div class='OJBetter_setting_list'>
  4732. <label for="localizationLanguage" style="display: flex;" data-i18n="settings:localization.websiteLanguageLabel"></label>
  4733. <select id="localizationLanguage" name="localizationLanguage">
  4734. <option value="initial">——</option>
  4735. <option value="zh">简体中文</option>
  4736. <option value="zh-Hant">繁體中文</option>
  4737. <option value="de">Deutsch</option>
  4738. <option value="fr">Français</option>
  4739. <option value="ko">한국어</option>
  4740. <option value="pt">Português</option>
  4741. <option value="ja">日本語</option>
  4742. <option value="es">Español</option>
  4743. <option value="it">Italiano</option>
  4744. <option value="hi">हिन्दी</option>
  4745. </select>
  4746. </div>
  4747. <div class='OJBetter_setting_list alert_tip'>
  4748. <div data-i18n="[html]settings:localization.notice.1"></div>
  4749. </div>
  4750. <div class='OJBetter_setting_list alert_tip'>
  4751. <div data-i18n="[html]settings:localization.notice.2"></div>
  4752. </div>
  4753. </div>
  4754. `;
  4755.  
  4756. const translation_settings_HTML = `
  4757. <div id="translation-settings" class="settings-page">
  4758. <h3 data-i18n="settings:translation.title"></h3>
  4759. <hr>
  4760. <h4 data-i18n="settings:translation.options.title"></h4>
  4761. <div class='OJBetter_setting_list'>
  4762. <label for="transTargetLang" style="display: flex;" data-i18n="settings:translation.preference.target.title"></label>
  4763. <div class="help_tip">
  4764. ${helpCircleHTML}
  4765. <div class="tip_text" data-i18n="[html]settings:translation.preference.target.helpText"></div>
  4766. </div>
  4767. <select id="transTargetLang" name="transTargetLang">
  4768. <option value="zh">简体中文</option>
  4769. <option value="zh-Hant">繁體中文</option>
  4770. <option value="de">Deutsch</option>
  4771. <option value="fr">Français</option>
  4772. <option value="ko">한국어</option>
  4773. <option value="pt">Português</option>
  4774. <option value="ja">日本語</option>
  4775. <option value="es">Español</option>
  4776. <option value="it">Italiano</option>
  4777. <option value="hi">हिन्दी</option>
  4778. </select>
  4779. </div>
  4780. <div id="translationServices">
  4781. <label>
  4782. <input type='radio' name='translation' value='deepl'>
  4783. <span class='OJBetter_setting_menu_label_text'
  4784. data-i18n="settings:translation.options.services.deepl"></span>
  4785. </label>
  4786. <label>
  4787. <input type='radio' name='translation' value='iflyrec'>
  4788. <span class='OJBetter_setting_menu_label_text'
  4789. data-i18n="settings:translation.options.services.iflyrec"></span>
  4790. </label>
  4791. <label>
  4792. <input type='radio' name='translation' value='youdao'>
  4793. <span class='OJBetter_setting_menu_label_text'
  4794. data-i18n="settings:translation.options.services.youdao"></span>
  4795. </label>
  4796. <label>
  4797. <input type='radio' name='translation' value='google'>
  4798. <span class='OJBetter_setting_menu_label_text'
  4799. data-i18n="settings:translation.options.services.google"></span>
  4800. </label>
  4801. <label>
  4802. <input type='radio' name='translation' value='caiyun'>
  4803. <span class='OJBetter_setting_menu_label_text'
  4804. data-i18n="settings:translation.options.services.caiyun"></span>
  4805. </label>
  4806. <label>
  4807. <input type='radio' name='translation' value='openai'>
  4808. <span class='OJBetter_setting_menu_label_text'
  4809. data-i18n="settings:translation.options.services.openai.name">
  4810. <div class="help_tip">
  4811. ${helpCircleHTML}
  4812. <div class="tip_text"
  4813. data-i18n="[html]settings:translation.options.services.openai.helpText"></div>
  4814. </div>
  4815. </span>
  4816. </label>
  4817. </div>
  4818. <hr>
  4819. <h4>DeepL</h4>
  4820. <div class='OJBetter_setting_list'>
  4821. <label for="deepl_type" style="display: flex;" data-i18n="settings:translation.deepl.mode.title"></label>
  4822. <div class="help_tip">
  4823. ${helpCircleHTML}
  4824. <div class="tip_text" data-i18n="[html]settings:translation.deepl.mode.helpText"></div>
  4825. </div>
  4826. <select id="deepl_type" name="deepl_type">
  4827. <option value="free" data-i18n="settings:translation.deepl.mode.select.free"></option>
  4828. <option value="api" data-i18n="settings:translation.deepl.mode.select.api"></option>
  4829. </select>
  4830. </div>
  4831. <div id="deepl_config" class="config"></div>
  4832. <div class='OJBetter_setting_list'>
  4833. <label for="enableEmphasisProtection" data-i18n="settings:translation.deepl.enableEmphasisProtection.title"></label>
  4834. <div class="help_tip" style="margin-right: initial;">
  4835. ${helpCircleHTML}
  4836. <div class="tip_text" data-i18n="[html]settings:translation.deepl.enableEmphasisProtection.helpText"></div>
  4837. </div>
  4838. <div class="badge">Official API Only</div>
  4839. <input type="checkbox" id="enableEmphasisProtection" name="enableEmphasisProtection">
  4840. </div>
  4841. <div class='OJBetter_setting_list'>
  4842. <label for="enableLinkProtection" data-i18n="settings:translation.deepl.enableLinkProtection.title"></label>
  4843. <div class="help_tip" style="margin-right: initial;">
  4844. ${helpCircleHTML}
  4845. <div class="tip_text" data-i18n="[html]settings:translation.deepl.enableLinkProtection.helpText"></div>
  4846. </div>
  4847. <div class="badge">Official API Only</div>
  4848. <input type="checkbox" id="enableLinkProtection" name="enableLinkProtection">
  4849. </div>
  4850. <hr>
  4851. <h4>ChatGPT</h4>
  4852. <div id="chatgpt_config" class="config"></div>
  4853. <div class='OJBetter_setting_list'>
  4854. <label for="openai_isStream" data-i18n="settings:translation.chatgpt.isStream.name"></label>
  4855. <div class="help_tip">
  4856. ${helpCircleHTML}
  4857. <div class="tip_text" data-i18n="[html]settings:translation.chatgpt.isStream.helpText"></div>
  4858. </div>
  4859. <input type="checkbox" id="openai_isStream" name="openai_isStream">
  4860. </div>
  4861. <hr>
  4862. <h4 data-i18n="settings:translation.preference.title"></h4>
  4863. <div class='OJBetter_setting_list'>
  4864. <label for="comment_translation_choice" style="display: flex;"
  4865. data-i18n="settings:translation.preference.comment_translation_choice.title">
  4866. </label>
  4867. <select id="comment_translation_choice" name="comment_translation_choice">
  4868. <option value="0" data-i18n="settings:translation.preference.comment_translation_choice.services.follow"></option>
  4869. <option value="deepl" data-i18n="settings:translation.preference.comment_translation_choice.services.deepl"></option>
  4870. <option value="iflyrec" data-i18n="settings:translation.preference.comment_translation_choice.services.iflyrec"></option>
  4871. <option value="youdao" data-i18n="settings:translation.preference.comment_translation_choice.services.youdao"></option>
  4872. <option value="google" data-i18n="settings:translation.preference.comment_translation_choice.services.google"></option>
  4873. <option value="caiyun" data-i18n="settings:translation.preference.comment_translation_choice.services.caiyun"></option>
  4874. <option value="openai" data-i18n="settings:translation.preference.comment_translation_choice.services.openai"></option>
  4875. </select>
  4876. </div>
  4877. <hr>
  4878. <h4 data-i18n="settings:translation.autoTranslation.title"></h4>
  4879. <div class='OJBetter_setting_list'>
  4880. <label for="autoTranslation" data-i18n="settings:translation.autoTranslation.enable"></label>
  4881. <div class="help_tip">
  4882. ${helpCircleHTML}
  4883. <div class="tip_text" data-i18n="[html]settings:translation.autoTranslation.helpText"></div>
  4884. </div>
  4885. <input type="checkbox" id="autoTranslation" name="autoTranslation">
  4886. </div>
  4887. <div class='OJBetter_setting_list'>
  4888. <label for='shortTextLength'>
  4889. <div style="display: flex;align-items: center;"
  4890. data-i18n="settings:translation.autoTranslation.shortTextLength.name"></div>
  4891. </label>
  4892. <div class="help_tip">
  4893. ${helpCircleHTML}
  4894. <div class="tip_text" data-i18n="[html]settings:translation.autoTranslation.shortTextLength.helpText">
  4895. </div>
  4896. </div>
  4897. <input type='number' id='shortTextLength' class='no_default' require=true data-i18n="[placeholder]settings:translation.autoTranslation.shortTextLength.placeholder">
  4898. <span data-i18n="settings:translation.autoTranslation.shortTextLength.end"></span>
  4899. </div>
  4900. <div class='OJBetter_setting_list'>
  4901. <label for="allowMixTrans" data-i18n="settings:translation.autoTranslation.allowMixTrans.name"></label>
  4902. <div class="help_tip">
  4903. ${helpCircleHTML}
  4904. <div class="tip_text" data-i18n="[html]settings:translation.autoTranslation.allowMixTrans.helpText">
  4905. </div>
  4906. </div>
  4907. <input type="checkbox" id="allowMixTrans" name="allowMixTrans">
  4908. <div class='OJBetter_checkboxs'>
  4909. <input type="checkbox" id="deepl" name="mixedTranslation" value="deepl">
  4910. <label for="deepl" data-i18n="settings:translation.autoTranslation.allowMixTrans.checkboxs.deepl"></label>
  4911. <input type="checkbox" id="iflyrec" name="mixedTranslation" value="iflyrec">
  4912. <label for="iflyrec" data-i18n="settings:translation.autoTranslation.allowMixTrans.checkboxs.iflyrec"></label>
  4913. <input type="checkbox" id="youdao" name="mixedTranslation" value="youdao">
  4914. <label for="youdao" data-i18n="settings:translation.autoTranslation.allowMixTrans.checkboxs.youdao"></label>
  4915. <input type="checkbox" id="google" name="mixedTranslation" value="google">
  4916. <label for="google" data-i18n="settings:translation.autoTranslation.allowMixTrans.checkboxs.google">Google</label>
  4917. <input type="checkbox" id="caiyun" name="mixedTranslation" value="caiyun">
  4918. <label for="caiyun" data-i18n="settings:translation.autoTranslation.allowMixTrans.checkboxs.caiyun"></label>
  4919. </div>
  4920. </div>
  4921. <hr>
  4922. <h4 data-i18n="settings:translation.advanced.name"></h4>
  4923. <div class='OJBetter_setting_list'>
  4924. <label for="comment_translation_mode" style="display: flex;" data-i18n="settings:translation.advanced.mode.name"></label>
  4925. <div class="help_tip">
  4926. ${helpCircleHTML}
  4927. <div class="tip_text" data-i18n="[html]settings:translation.advanced.mode.helpText"></div>
  4928. </div>
  4929. <select id="comment_translation_mode" name="comment_translation_mode">
  4930. <option value="0" data-i18n="settings:translation.advanced.mode.options.0"></option>
  4931. <option value="1" data-i18n="settings:translation.advanced.mode.options.1"></option>
  4932. <option value="2" data-i18n="settings:translation.advanced.mode.options.2"></option>
  4933. </select>
  4934. </div>
  4935. <div class='OJBetter_setting_list'>
  4936. <label for="memoryTranslateHistory" data-i18n="settings:translation.advanced.memory.name"></label>
  4937. <div class="help_tip">
  4938. ${helpCircleHTML}
  4939. <div class="tip_text" data-i18n="[html]settings:translation.advanced.memory.helpText"></div>
  4940. </div>
  4941. <input type="checkbox" id="memoryTranslateHistory" name="memoryTranslateHistory">
  4942. </div>
  4943. <div class='OJBetter_setting_list'>
  4944. <label for="translation_retransAction" style="display: flex;" data-i18n="settings:translation.advanced.retrans.name"></label>
  4945. <div class="help_tip">
  4946. ${helpCircleHTML}
  4947. <div class="tip_text" data-i18n="[html]settings:translation.advanced.retrans.helpText"></div>
  4948. </div>
  4949. <select id="translation_retransAction" name="translation_retransAction">
  4950. <option value=0 data-i18n="settings:translation.advanced.retrans.options.0"></option>
  4951. <option value=1 data-i18n="settings:translation.advanced.retrans.options.1"></option>
  4952. </select>
  4953. </div>
  4954. <div class='OJBetter_setting_list'>
  4955. <label for='transWaitTime'>
  4956. <div style="display: flex;align-items: center;" data-i18n="settings:translation.advanced.transWaitTime.name"></div>
  4957. </label>
  4958. <div class="help_tip">
  4959. ${helpCircleHTML}
  4960. <div class="tip_text" data-i18n="[html]settings:translation.advanced.transWaitTime.helpText"></div>
  4961. </div>
  4962. <input type='number' id='transWaitTime' class='no_default' require=true data-i18n="[placeholder]settings:translation.advanced.transWaitTime.placeholder">
  4963. <span data-i18n="settings:translation.advanced.transWaitTime.end"></span>
  4964. </div>
  4965. <div class='OJBetter_setting_list'>
  4966. <label for="translation_replaceSymbol" style="display: flex;" data-i18n="settings:translation.advanced.replaceSymbol.name"></label>
  4967. <div class="help_tip">
  4968. ${helpCircleHTML}
  4969. <div class="tip_text" data-i18n="[html]settings:translation.advanced.replaceSymbol.helpText"></div>
  4970. </div>
  4971. <select id="translation_replaceSymbol" name="translation_replaceSymbol">
  4972. <option value=2 data-i18n="settings:translation.advanced.replaceSymbol.options.2"></option>
  4973. <option value=1 data-i18n="settings:translation.advanced.replaceSymbol.options.1"></option>
  4974. <option value=3 data-i18n="settings:translation.advanced.replaceSymbol.options.3"></option>
  4975. </select>
  4976. </div>
  4977. <div class='OJBetter_setting_list'>
  4978. <label for="filterTextWithoutEmphasis" data-i18n="settings:translation.advanced.filterTextWithoutEmphasis.name"></label>
  4979. <div class="help_tip">
  4980. ${helpCircleHTML}
  4981. <div class="tip_text" data-i18n="[html]settings:translation.advanced.filterTextWithoutEmphasis.helpText"></div>
  4982. </div>
  4983. <input type="checkbox" id="filterTextWithoutEmphasis" name="filterTextWithoutEmphasis">
  4984. </div>
  4985. </div>
  4986. `;
  4987.  
  4988. const clist_rating_settings_HTML = `
  4989. <div id="clist_rating-settings" class="settings-page">
  4990. <h3 data-i18n="settings:clist.title"></h3>
  4991. <hr>
  4992. <h4 data-i18n="settings:clist.basics.name"></h4>
  4993. <div class='OJBetter_setting_list alert_tip'>
  4994. <div>
  4995. <p data-i18n="[html]settings:clist.basics.notice"></p>
  4996. </div>
  4997. </div>
  4998. <div class='OJBetter_setting_list'>
  4999. <label for='clist_Authorization'>
  5000. <div style="display: flex;align-items: center;">
  5001. <span class="input_label" data-i18n="settings:clist.basics.key.title"></span>
  5002. </div>
  5003. </label>
  5004. <div class="help_tip">
  5005. ${helpCircleHTML}
  5006. <div class="tip_text" data-i18n="[html]settings:clist.basics.key.helpText"></div>
  5007. </div>
  5008. <input type='text' id='clist_Authorization' class='no_default' required="true"
  5009. data-i18n="[placeholder]settings:clist.basics.key.keyPlaceholder">
  5010. </div>
  5011. <hr>
  5012. <h4 data-i18n="settings:clist.displayRating.title"></h4>
  5013. <div class='OJBetter_setting_list'>
  5014. <label for="showClistRating_contest"><span data-i18n="settings:clist.displayRating.contest.name"></span></label>
  5015. <input type="checkbox" id="showClistRating_contest" name="showClistRating_contest">
  5016. </div>
  5017. <div class='OJBetter_setting_list'>
  5018. <label for="showClistRating_problem"><span data-i18n="settings:clist.displayRating.problem.name"></span></label>
  5019. <input type="checkbox" id="showClistRating_problem" name="showClistRating_problem">
  5020. </div>
  5021. <div class='OJBetter_setting_list'>
  5022. <label for="showClistRating_problemset"><span data-i18n="settings:clist.displayRating.problemset.name"></span></label>
  5023. <input type="checkbox" id="showClistRating_problemset" name="showClistRating_problemset">
  5024. </div>
  5025. <hr>
  5026. <div class='OJBetter_setting_list'>
  5027. <label for="RatingHidden"><span data-i18n="settings:clist.spoilerProtection.title"></span></label>
  5028. <div class="help_tip">
  5029. ${helpCircleHTML}
  5030. <div class="tip_text" data-i18n="[html]settings:clist.spoilerProtection.helpText"></div>
  5031. </div>
  5032. <input type="checkbox" id="RatingHidden" name="RatingHidden">
  5033. </div>
  5034. </div>
  5035. `;
  5036.  
  5037. const code_editor_settings_HTML = `
  5038. <div id="code_editor-settings" class="settings-page">
  5039. <h3 data-i18n="settings:codeEditor.title"></h3>
  5040. <hr>
  5041. <h4 data-i18n="settings:codeEditor.basics"></h4>
  5042. <div class='OJBetter_setting_list'>
  5043. <label for="problemPageCodeEditor"><span
  5044. data-i18n="settings:codeEditor.problemPageCodeEditor.label"></span></label>
  5045. <div class="help_tip">
  5046. ${helpCircleHTML}
  5047. <div class="tip_text" data-i18n="settings:codeEditor.problemPageCodeEditor.helpText"></div>
  5048. </div>
  5049. <input type="checkbox" id="problemPageCodeEditor" name="problemPageCodeEditor">
  5050. </div>
  5051. <hr>
  5052. <h4 data-i18n="settings:codeEditor.preferences.title"></h4>
  5053. <div class='OJBetter_setting_list'>
  5054. <label for="isCodeSubmitConfirm"><span
  5055. data-i18n="settings:codeEditor.preferences.isCodeSubmitConfirm.label"></span></label>
  5056. <div class="help_tip">
  5057. ${helpCircleHTML}
  5058. <div class="tip_text" data-i18n="settings:codeEditor.preferences.isCodeSubmitConfirm.helpText"></div>
  5059. </div>
  5060. <input type="checkbox" id="isCodeSubmitConfirm" name="isCodeSubmitConfirm">
  5061. </div>
  5062. <div class='OJBetter_setting_list'>
  5063. <label for="alwaysConsumeMouseWheel"><span
  5064. data-i18n="settings:codeEditor.preferences.alwaysConsumeMouseWheel.label"></span></label>
  5065. <div class="help_tip">
  5066. ${helpCircleHTML}
  5067. <div class="tip_text" data-i18n="settings:codeEditor.preferences.alwaysConsumeMouseWheel.helpText"></div>
  5068. </div>
  5069. <input type="checkbox" id="alwaysConsumeMouseWheel" name="alwaysConsumeMouseWheel">
  5070. </div>
  5071. <div class='OJBetter_setting_list'>
  5072. <label for="submitButtonPosition"><span
  5073. data-i18n="settings:codeEditor.preferences.submitButtonPosition.label"></span></label>
  5074. <div class="help_tip">
  5075. ${helpCircleHTML}
  5076. <div class="tip_text" data-i18n="settings:codeEditor.preferences.submitButtonPosition.helpText"></div>
  5077. </div>
  5078. <select id="submitButtonPosition" name="submitButtonPosition">
  5079. <option value="bottom" data-i18n="settings:codeEditor.preferences.submitButtonPosition.options.bottom"></option>
  5080. <option value="top" data-i18n="settings:codeEditor.preferences.submitButtonPosition.options.top"></option>
  5081. </select>
  5082. </div>
  5083. <hr>
  5084. <h4 data-i18n="settings:codeEditor.onlineCodeExecution.title"></h4>
  5085. <label>
  5086. <input type='radio' name='compiler' value='official'>
  5087. <span class='OJBetter_setting_menu_label_text'
  5088. data-i18n="settings:codeEditor.onlineCodeExecution.compilerOptions.codeforces"></span>
  5089. </label>
  5090. <label>
  5091. <input type='radio' name='compiler' value='wandbox'>
  5092. <span class='OJBetter_setting_menu_label_text'
  5093. data-i18n="settings:codeEditor.onlineCodeExecution.compilerOptions.wandbox"></span>
  5094. </label>
  5095. <label>
  5096. <input type='radio' name='compiler' value='rextester'>
  5097. <span class='OJBetter_setting_menu_label_text'
  5098. data-i18n="settings:codeEditor.onlineCodeExecution.compilerOptions.rextester"></span>
  5099. </label>
  5100. <hr>
  5101. <h4 data-i18n="settings:codeEditor.lsp.title"></h4>
  5102. <div class='OJBetter_setting_list'>
  5103. <label for="useLSP"><span data-i18n="settings:codeEditor.lsp.useLSP.label"></span></label>
  5104. <div class="help_tip">
  5105. ${helpCircleHTML}
  5106. <div class="tip_text" data-i18n="[html]settings:codeEditor.lsp.useLSP.helpText"></div>
  5107. </div>
  5108. <input type="checkbox" id="useLSP" name="useLSP">
  5109. </div>
  5110. <div class='OJBetter_setting_list'>
  5111. <label for='OJBetter_Bridge_WorkUri'>
  5112. <div style="display: flex;align-items: center;">
  5113. <span class="input_label" data-i18n="settings:codeEditor.lsp.OJBetter_Bridge_WorkUri.label"></span>
  5114. </div>
  5115. </label>
  5116. <div class="help_tip">
  5117. ${helpCircleHTML}
  5118. <div class="tip_text" data-i18n="[html]settings:codeEditor.lsp.OJBetter_Bridge_WorkUri.helpText"></div>
  5119. </div>
  5120. <input type='text' id='OJBetter_Bridge_WorkUri' class='no_default'
  5121. require=true data-i18n="[placeholder]settings:codeEditor.lsp.OJBetter_Bridge_WorkUri.placeholder">
  5122. </div>
  5123. <div class='OJBetter_setting_list'>
  5124. <label for='OJBetter_Bridge_SocketUrl'>
  5125. <div style="display: flex;align-items: center;">
  5126. <span class="input_label"
  5127. data-i18n="settings:codeEditor.lsp.OJBetter_Bridge_SocketUrl.label"></span>
  5128. </div>
  5129. </label>
  5130. <div class="help_tip">
  5131. ${helpCircleHTML}
  5132. <div class="tip_text" data-i18n="[html]settings:codeEditor.lsp.OJBetter_Bridge_SocketUrl.helpText"></div>
  5133. </div>
  5134. <input type='text' id='OJBetter_Bridge_SocketUrl' class='no_default'
  5135. require=true data-i18n="[placeholder]settings:codeEditor.lsp.OJBetter_Bridge_SocketUrl.placeholder">
  5136. </div>
  5137. <hr>
  5138. <h4 data-i18n="settings:codeEditor.staticCompletionEnhancement.title"></h4>
  5139. <div class='OJBetter_setting_list'>
  5140. <label for="cppCodeTemplateComplete"><span
  5141. data-i18n="settings:codeEditor.staticCompletionEnhancement.cppCodeTemplateComplete.label"></span></label>
  5142. <div class="help_tip">
  5143. ${helpCircleHTML}
  5144. <div class="tip_text" data-i18n="[html]settings:codeEditor.staticCompletionEnhancement.cppCodeTemplateComplete.helpText"></div>
  5145. </div>
  5146. <input type="checkbox" id="cppCodeTemplateComplete" name="cppCodeTemplateComplete">
  5147. </div>
  5148. <hr>
  5149. <h5 data-i18n="settings:codeEditor.staticCompletionEnhancement.customization"></h5>
  5150. <div class='OJBetter_setting_list alert_warn'>
  5151. <div>
  5152. <p data-i18n="settings:codeEditor.staticCompletionEnhancement.performanceWarning"></p>
  5153. </div>
  5154. </div>
  5155. <div id="Complet_config" class="config"></div>
  5156. </div>
  5157. `;
  5158.  
  5159. const preference_settings_HTML = `
  5160. <div id="preference-settings" class="settings-page">
  5161. <h3 data-i18n="settings:preference.title"></h3>
  5162. <hr>
  5163. <div class='OJBetter_setting_list'>
  5164. <label for="showLoading" data-i18n="settings:preference.loadingInfo.label"></label>
  5165. <div class="help_tip">
  5166. ${helpCircleHTML}
  5167. <div class="tip_text" data-i18n="[html]settings:preference.loadingInfo.helpText"></div>
  5168. </div>
  5169. <input type="checkbox" id="showLoading" name="showLoading">
  5170. </div>
  5171. <div class='OJBetter_setting_list'>
  5172. <label for="hoverTargetAreaDisplay" data-i18n="settings:preference.targetArea.label"></label>
  5173. <div class="help_tip">
  5174. ${helpCircleHTML}
  5175. <div class="tip_text" data-i18n="[html]settings:preference.targetArea.helpText"></div>
  5176. </div>
  5177. <input type="checkbox" id="hoverTargetAreaDisplay" name="hoverTargetAreaDisplay">
  5178. </div>
  5179. <div class='OJBetter_setting_list'>
  5180. <label for='iconButtonSize'>
  5181. <div style="display: flex;align-items: center;" data-i18n="settings:preference.iconButtonSize.title"></div>
  5182. </label>
  5183. <div class="help_tip">
  5184. ${helpCircleHTML}
  5185. <div class="tip_text" data-i18n="[html]settings:preference.iconButtonSize.helpText"></div>
  5186. </div>
  5187. <input type='number' id='iconButtonSize' class='no_default' require=true data-i18n="[placeholder]settings:preference.iconButtonSize.placeholder">
  5188. <span>px</span>
  5189. </div>
  5190. </div>
  5191. `;
  5192.  
  5193. const dev_settings_HTML = `
  5194. <div id="dev-settings" class="settings-page">
  5195. <h3 data-i18n="settings:dev.title"></h3>
  5196. <hr>
  5197. <div class='OJBetter_setting_list alert_danger'>
  5198. <div>
  5199. <p data-i18n="[html]settings:dev.notice"></p>
  5200. </div>
  5201. </div>
  5202. <hr>
  5203. <h5 data-i18n="settings:dev.load.title"></h5>
  5204. <div class='OJBetter_setting_list'>
  5205. <label for="notWaiteLoaded"><span data-i18n="settings:dev.load.notWaiteLoaded.label"></span></label>
  5206. <div class="help_tip">
  5207. ${helpCircleHTML}
  5208. <div class="tip_text" data-i18n="[html]settings:dev.load.notWaiteLoaded.helpText"></div>
  5209. </div>
  5210. <input type="checkbox" id="notWaiteLoaded" name="notWaiteLoaded">
  5211. </div>
  5212. <hr>
  5213. <h5 data-i18n="settings:dev.l10n.title"></h5>
  5214. <div class='OJBetter_setting_list'>
  5215. <label><span data-i18n="settings:dev.l10n.refreshScrpitCache.label"></span></label>
  5216. <div class="help_tip">
  5217. ${helpCircleHTML}
  5218. <div class="tip_text" data-i18n="[html]settings:dev.l10n.refreshScrpitCache.helpText"></div>
  5219. </div>
  5220. <button type="button" id="l10n_refreshScrpitCacheButton" name="l10n_refreshScrpitCacheButton" data-i18n="settings:dev.l10n.refreshScrpitCache.button"></button>
  5221. </div>
  5222. <hr>
  5223. <h5 data-i18n="settings:dev.indexedDB.title"></h5>
  5224. <div class='OJBetter_setting_list'>
  5225. <label><span data-i18n="settings:dev.indexedDB.clear.label"></span></label>
  5226. <div class="help_tip">
  5227. ${helpCircleHTML}
  5228. <div class="tip_text" data-i18n="[html]settings:dev.indexedDB.clear.helpText"></div>
  5229. </div>
  5230. <button type="button" id="indexedDB_clearButton" name="indexedDB_clearButton" data-i18n="settings:dev.indexedDB.clear.button"></button>
  5231. </div>
  5232. <div class='OJBetter_setting_list'>
  5233. <label><span data-i18n="settings:dev.indexedDB.inputOrExport.label"></span></label>
  5234. <div class="help_tip">
  5235. ${helpCircleHTML}
  5236. <div class="tip_text" data-i18n="[html]settings:dev.indexedDB.inputOrExport.helpText"></div>
  5237. </div>
  5238. <button type="button" id="indexedDB_exportButton" name="indexedDB_exportButton" data-i18n="settings:dev.indexedDB.inputOrExport.export"></button>
  5239. <button type="button" id="indexedDB_importButton" name="indexedDB_importButton" data-i18n="settings:dev.indexedDB.inputOrExport.import"></button>
  5240. </div>
  5241. <hr>
  5242. <h5 data-i18n="settings:dev.configuration.title"></h5>
  5243. <div class='OJBetter_setting_list'>
  5244. <label><span data-i18n="settings:dev.configuration.clear.label"></span></label>
  5245. <div class="help_tip">
  5246. ${helpCircleHTML}
  5247. <div class="tip_text" data-i18n="[html]settings:dev.configuration.clear.helpText"></div>
  5248. </div>
  5249. <button type="button" id="configuration_clearButton" name="configuration_clearButton" data-i18n="settings:dev.configuration.clear.button"></button>
  5250. </div>
  5251. <div class='OJBetter_setting_list'>
  5252. <label><span data-i18n="settings:dev.configuration.inputOrExport.label"></span></label>
  5253. <div class="help_tip">
  5254. ${helpCircleHTML}
  5255. <div class="tip_text" data-i18n="[html]settings:dev.configuration.inputOrExport.helpText"></div>
  5256. </div>
  5257. <button type="button" id="configuration_exportButton" name="configuration_exportButton" data-i18n="settings:dev.configuration.inputOrExport.export"></button>
  5258. <button type="button" id="configuration_importButton" name="configuration_importButton" data-i18n="settings:dev.configuration.inputOrExport.import"></button>
  5259. </div>
  5260. </div>
  5261. `;
  5262.  
  5263. // TODO 2
  5264. const about_settings_HTML = `
  5265. <div id="about-settings" class="settings-page">
  5266. <h3 data-i18n="settings:about.title"></h3>
  5267. <hr>
  5268. <div class='versionInfo'>
  5269. <p>Codeforces Better!</p>
  5270. <p><span data-i18n="settings:about.version"></span><span id="nowVersion">${OJBetter.state.version}</span></p>
  5271. <p> @北极小狐 <a target="_blank" href="https://github.com/beijixiaohu/OJBetter">Github</a>
  5272. <a target="_blank" href="https://gf.qytechs.cn/zh-CN/scripts/465777">GreasyFork</a></p>
  5273. </div>
  5274. <hr>
  5275. <h5 data-i18n="settings:about.update.title"></h5>
  5276. <div id="thanksforDevChannelNotice" class='OJBetter_setting_list alert_info'>
  5277. <div data-i18n="[html]settings:about.update.thanksforDevChannelNotice"></div>
  5278. </div>
  5279. <div class='OJBetter_setting_list'>
  5280. <label for="updateChannel"><span data-i18n="settings:about.update.channel.label"></span></label>
  5281. <div class="help_tip">
  5282. ${helpCircleHTML}
  5283. <div class="tip_text" data-i18n="[html]settings:about.update.channel.helpText"></div>
  5284. </div>
  5285. <select id="updateChannel" name="updateChannel">
  5286. <option value="release" data-i18n="settings:about.update.channel.options.release"></option>
  5287. <option value="dev" data-i18n="settings:about.update.channel.options.dev"></option>
  5288. </select>
  5289. </div>
  5290. <div class='OJBetter_setting_list'>
  5291. <label for="updateSource"><span data-i18n="settings:about.update.source.label"></span></label>
  5292. <div class="help_tip">
  5293. ${helpCircleHTML}
  5294. <div class="tip_text" data-i18n="[html]settings:about.update.source.helpText"></div>
  5295. </div>
  5296. <select id="updateSource" name="updateSource">
  5297. <option value="greasyfork" data-i18n="settings:about.update.source.options.greasyfork"></option>
  5298. <option value="github" data-i18n="settings:about.update.source.options.github"></option>
  5299. <option value="aliyunoss" data-i18n="settings:about.update.source.options.aliyunoss"></option>
  5300. </select>
  5301. </div>
  5302. </div>
  5303. `;
  5304.  
  5305. const OJBetter_setting_content_HTML = `
  5306. <div class="OJBetter_setting_content">
  5307. ${basic_settings_HTML}
  5308. ${l10n_settings_HTML}
  5309. ${translation_settings_HTML}
  5310. ${clist_rating_settings_HTML}
  5311. ${code_editor_settings_HTML}
  5312. ${preference_settings_HTML}
  5313. ${dev_settings_HTML}
  5314. ${about_settings_HTML}
  5315. </div>
  5316. `;
  5317.  
  5318. // 设置界面HTML
  5319. const CFBetterSettingMenu_HTML = `
  5320. <dialog class='OJBetter_setting_menu' id='OJBetter_setting_menu'>
  5321. <div class="tool-box">
  5322. <button class="btn-close">×</button>
  5323. </div>
  5324. <div class="OJBetter_setting_container">
  5325. ${OJBetter_setting_sidebar_HTML}
  5326. ${OJBetter_setting_content_HTML}
  5327. </div>
  5328. </dialog>
  5329. `;
  5330.  
  5331. const apiCustomConfigHTML = (prefix) => {
  5332. return `
  5333. <div class="OJBetter_setting_list">
  5334. <label for='${prefix}_header'>
  5335. <div style="display: flex;align-items: center;">
  5336. <span class="input_label" data-i18n="config:common.advanced.header.label"></span>
  5337. <div class="help_tip">
  5338. ${helpCircleHTML}
  5339. <div class="tip_text" data-i18n="[html]config:common.advanced.header.tipText"></div>
  5340. </div>
  5341. </div>
  5342. </label>
  5343. <textarea id="${prefix}_header" placeholder='' require = false data-i18n="[placeholder]config:common.advanced.header.placeholder"></textarea>
  5344. </div>
  5345. <div class="OJBetter_setting_list">
  5346. <label for='${prefix}_data'>
  5347. <div style="display: flex;align-items: center;">
  5348. <span class="input_label" data-i18n="config:common.advanced.data.label"></span>
  5349. <div class="help_tip">
  5350. ${helpCircleHTML}
  5351. <div class="tip_text" data-i18n="[html]config:common.advanced.data.tipText"></div>
  5352. </div>
  5353. </div>
  5354. </label>
  5355. <textarea id="${prefix}_data" placeholder='' require = false data-i18n="[placeholder]config:common.advanced.data.placeholder"></textarea>
  5356. </div>
  5357. `;
  5358. };
  5359.  
  5360. const apiQuotaConfigHTML = (prefix) => {
  5361. return `
  5362. <div class="OJBetter_setting_list">
  5363. <label for='${prefix}_quota_url'>
  5364. <div style="display: flex;align-items: center;">
  5365. <span class="input_label" data-i18n="config:common.quota.url.label"></span>
  5366. <div class="help_tip">
  5367. ${helpCircleHTML}
  5368. <div class="tip_text" data-i18n="[html]config:common.quota.url.tipText"></div>
  5369. </div>
  5370. </div>
  5371. </label>
  5372. <input type='text' id='${prefix}_quota_url' class='no_default' placeholder='' require = true data-i18n="[placeholder]config:common.quota.url.placeholder">
  5373. </div>
  5374. <div class="OJBetter_setting_list">
  5375. <label for="${prefix}_quota_method" style="display: flex;" data-i18n="config:common.quota.method.label"></label>
  5376. <div class="help_tip">
  5377. ${helpCircleHTML}
  5378. <div class="tip_text" data-i18n="[html]config:common.quota.method.tipText"></div>
  5379. </div>
  5380. <select id="${prefix}_quota_method" name="${prefix}_quota_method">
  5381. <option value="get">GET</option>
  5382. <option value="post">POST</option>
  5383. </select>
  5384. </div>
  5385. <div class="OJBetter_setting_list">
  5386. <label for='${prefix}_quota_header'>
  5387. <div style="display: flex;align-items: center;">
  5388. <span class="input_label" data-i18n="config:common.quota.header.label"></span>
  5389. <div class="help_tip">
  5390. ${helpCircleHTML}
  5391. <div class="tip_text" data-i18n="[html]config:common.quota.header.tipText"></div>
  5392. </div>
  5393. </div>
  5394. </label>
  5395. <textarea id="${prefix}_quota_header" placeholder='' require = false data-i18n="[placeholder]config:common.quota.header.placeholder"></textarea>
  5396. </div>
  5397. <div class="OJBetter_setting_list">
  5398. <label for='${prefix}_quota_data'>
  5399. <div style="display: flex;align-items: center;">
  5400. <span class="input_label" data-i18n="config:common.quota.data.label"></span>
  5401. <div class="help_tip">
  5402. ${helpCircleHTML}
  5403. <div class="tip_text" data-i18n="[html]config:common.quota.data.tipText"></div>
  5404. </div>
  5405. </div>
  5406. </label>
  5407. <textarea id="${prefix}_quota_data" placeholder='' require = false data-i18n="[placeholder]config:common.quota.data.placeholder"></textarea>
  5408. </div>
  5409. <div class="OJBetter_setting_list">
  5410. <div style="display: flex;align-items: center;">
  5411. <span class="input_label" data-i18n="config:common.quota.surplus.label"></span>
  5412. <div class="help_tip">
  5413. ${helpCircleHTML}
  5414. <div class="tip_text" data-i18n="[html]config:common.quota.surplus.tipText"></div>
  5415. </div>
  5416. </div>
  5417. </label>
  5418. <input type='text' id='${prefix}_quota_surplus' class='no_default' placeholder='' require = true data-i18n="[placeholder]config:common.quota.surplus.placeholder">
  5419. </div>
  5420. `;
  5421. }
  5422.  
  5423. const deeplConfigEditHTML = `
  5424. <dialog class='OJBetter_setting_menu' id='config_edit_menu'>
  5425. <div class='OJBetter_setting_content'>
  5426. <div class="tool-box">
  5427. <button class="btn-close">×</button>
  5428. </div>
  5429. <h4 data-i18n="config:deepl.title"></h4>
  5430. <h5 data-i18n="config:deepl.basic.title"></h5>
  5431. <hr>
  5432. <div class="OJBetter_setting_list">
  5433. <label for='name'>
  5434. <span class="input_label" data-i18n="config:deepl.basic.name.label"></span>
  5435. </label>
  5436. <input type='text' id='name' class='no_default' placeholder='' require = true data-i18n="[placeholder]config:deepl.basic.name.placeholder">
  5437. </div>
  5438. <div class='OJBetter_setting_list'>
  5439. <label for="deepl_apiGenre" style="display: flex;" data-i18n="config:deepl.genre.label"></label>
  5440. <div class="help_tip">
  5441. ${helpCircleHTML}
  5442. <div class="tip_text" data-i18n="[html]config:deepl.genre.tipText"></div>
  5443. </div>
  5444. <select id="deepl_apiGenre" name="deepl_apiGenre">
  5445. <option value="api-free">api-free</option>
  5446. <option value="api-pro">api-pro</option>
  5447. <option value="deeplx">deeplx</option>
  5448. </select>
  5449. </div>
  5450. <div class="OJBetter_setting_list">
  5451. <label for='deepl_key'>
  5452. <div style="display: flex;align-items: center;">
  5453. <span class="input_label" data-i18n="config:deepl.basic.key.label"></span>
  5454. <div class="help_tip">
  5455. ${helpCircleHTML}
  5456. <div class="tip_text" data-i18n="[html]config:deepl.basic.key.tipText"></div>
  5457. </div>
  5458. </div>
  5459. </label>
  5460. <input type='text' id='deepl_key' class='no_default' placeholder='' require = true data-i18n="[placeholder]config:deepl.basic.key.placeholder">
  5461. </div>
  5462. <div class="OJBetter_setting_list">
  5463. <label for='deepl_proxy'>
  5464. <div style="display: flex;align-items: center;">
  5465. <span class="input_label" data-i18n="config:deepl.basic.proxy.label">Proxy API:</span>
  5466. <div class="help_tip">
  5467. ${helpCircleHTML}
  5468. <div class="tip_text" data-i18n="[html]config:deepl.basic.proxy.tipText"></div>
  5469. </div>
  5470. </div>
  5471. </label>
  5472. <input type='text' id='deepl_proxy' placeholder='' require = false>
  5473. </div>
  5474. <hr>
  5475. <details>
  5476. <summary data-i18n="config:common.advanced.title"></summary>
  5477. ${apiCustomConfigHTML('deepl')}
  5478. </details>
  5479. <details>
  5480. <summary data-i18n="config:common.quota.title"></summary>
  5481. ${apiQuotaConfigHTML('deepl')}
  5482. </details>
  5483. <button id='tempConfig_save' data-i18n="common:save"></button>
  5484. </div>
  5485. </dialog>
  5486. `;
  5487.  
  5488. const chatgptConfigEditHTML = `
  5489. <dialog class='OJBetter_setting_menu' id='config_edit_menu'>
  5490. <div class='OJBetter_setting_content'>
  5491. <div class="tool-box">
  5492. <button class="btn-close">×</button>
  5493. </div>
  5494. <h4 data-i18n="config:chatgpt.title"></h4>
  5495. <h5 data-i18n="config:chatgpt.basic.title"></h5>
  5496. <hr>
  5497. <div class="OJBetter_setting_list">
  5498. <label for='name'>
  5499. <span class="input_label" data-i18n="config:chatgpt.basic.name.label"></span>
  5500. </label>
  5501. <input type='text' id='name' class='no_default' placeholder='' require = true data-i18n="[placeholder]config:chatgpt.basic.name.placeholder">
  5502. </div>
  5503. <div class="OJBetter_setting_list">
  5504. <label for='chatgpt_model'>
  5505. <div style="display: flex;align-items: center;">
  5506. <span class="input_label" data-i18n="[html]config:chatgpt.basic.model.label"></span>
  5507. <div class="help_tip">
  5508. ${helpCircleHTML}
  5509. <div class="tip_text" data-i18n="[html]config:chatgpt.basic.model.tipText"></div>
  5510. </div>
  5511. </div>
  5512. </label>
  5513. <input type='text' id='chatgpt_model' placeholder='gpt-3.5-turbo' require = false>
  5514. </div>
  5515. <div class="OJBetter_setting_list">
  5516. <label for='chatgpt_key'>
  5517. <div style="display: flex;align-items: center;">
  5518. <span class="input_label" data-i18n="config:chatgpt.basic.key.label"></span>
  5519. <div class="help_tip">
  5520. ${helpCircleHTML}
  5521. <div class="tip_text" data-i18n="[html]config:chatgpt.basic.key.tipText"></div>
  5522. </div>
  5523. </div>
  5524. </label>
  5525. <input type='text' id='chatgpt_key' class='no_default' placeholder='' require = true data-i18n="[placeholder]config:chatgpt.basic.key.placeholder">
  5526. </div>
  5527. <div class="OJBetter_setting_list">
  5528. <label for='chatgpt_proxy'>
  5529. <div style="display: flex;align-items: center;">
  5530. <span class="input_label" data-i18n="config:chatgpt.basic.proxy.label">Proxy API:</span>
  5531. <div class="help_tip">
  5532. ${helpCircleHTML}
  5533. <div class="tip_text" data-i18n="[html]config:chatgpt.basic.proxy.tipText"></div>
  5534. </div>
  5535. </div>
  5536. </label>
  5537. <input type='text' id='chatgpt_proxy' placeholder='https://api.openai.com/v1/chat/completions' require = false>
  5538. </div>
  5539. <hr>
  5540. <details>
  5541. <summary data-i18n="config:common.advanced.title"></summary>
  5542. ${apiCustomConfigHTML('chatgpt')}
  5543. </details>
  5544. <details>
  5545. <summary data-i18n="config:common.quota.title"></summary>
  5546. ${apiQuotaConfigHTML('chatgpt')}
  5547. </details>
  5548. <button id='tempConfig_save' data-i18n="common:save"></button>
  5549. </div>
  5550. </dialog>
  5551. `;
  5552.  
  5553. const CompletConfigEditHTML = `
  5554. <dialog class='OJBetter_setting_menu' id='config_edit_menu'>
  5555. <div class='OJBetter_setting_content'>
  5556. <div class="tool-box">
  5557. <button class="btn-close">×</button>
  5558. </div>
  5559. <h4 data-i18n="config:complet.title"></h4>
  5560. <hr>
  5561. <div class="OJBetter_setting_list">
  5562. <label for='name'>
  5563. <span class="input_label" data-i18n="config:complet.name.label"></span>
  5564. </label>
  5565. <input type='text' id='name' class='no_default' placeholder='' require = true data-i18n="[placeholder]config:complet.name.placeholder">
  5566. </div>
  5567. <div class='OJBetter_setting_list'>
  5568. <label for="complet_isChoose"><span id="loaded_span" data-i18n="config:complet.choose.label"></span></label>
  5569. <input type="checkbox" id="complet_isChoose" name="complet_isChoose" require = false>
  5570. </div>
  5571. <div class='OJBetter_setting_list'>
  5572. <label for="complet_genre" style="display: flex;" data-i18n="config:complet.genre.label"></label>
  5573. <div class="help_tip">
  5574. ${helpCircleHTML}
  5575. <div class="tip_text" data-i18n="[html]config:complet.genre.tipText"></div>
  5576. </div>
  5577. <select id="complet_genre" name="complet_genre">
  5578. <option value="monaco">monaco</option>
  5579. <option value="ace">ace</option>
  5580. </select>
  5581. </div>
  5582. <div class='OJBetter_setting_list'>
  5583. <label for="complet_language" style="display: flex;" data-i18n="config:complet.language.label"></label>
  5584. <select id="complet_language" name="complet_language">
  5585. <option value="cpp">cpp</option>
  5586. <option value="python">python</option>
  5587. <option value="java">java</option>
  5588. <option value="c">c</option>
  5589. </select>
  5590. </div>
  5591. <div class="OJBetter_setting_list">
  5592. <label for='complet_jsonUrl'>
  5593. <div style="display: flex;align-items: center;">
  5594. <span class="input_label">JSON URL:</span>
  5595. <div class="help_tip">
  5596. ${helpCircleHTML}
  5597. <div class="tip_text" data-i18n="[html]config:complet.jsonurl.tipText"></div>
  5598. </div>
  5599. </div>
  5600. </label>
  5601. <div class='OJBetter_setting_list alert_warn' data-i18n="[html]config:complet.jsonurl.alert"></div>
  5602. <input type='text' id='complet_jsonUrl' class='no_default' placeholder='' require = true data-i18n="[placeholder]config:complet.jsonurl.placeholder">
  5603. </div>
  5604. <button id='tempConfig_save' data-i18n="common:save"></button>
  5605. </div>
  5606. </dialog>
  5607. `;
  5608.  
  5609. /**
  5610. * 加载设置按钮面板
  5611. */
  5612. async function initSettingsPanel() {
  5613. // 添加右上角设置按钮
  5614. function insertCFBetterSettingButton(location, method) {
  5615. $(location)[method](`<button class='ojb_btn OJBetter_setting'>
  5616. Codeforces Better ${i18next.t('settings', { ns: 'common' })}</button>`);
  5617. }
  5618.  
  5619. insertCFBetterSettingButton(".lang-chooser", "before");
  5620. insertCFBetterSettingButton(".enter-or-register-box", "after");
  5621. if (OJBetter.typeOfPage.is_completeProblemset) insertCFBetterSettingButton(".lang", "before");
  5622.  
  5623. const $settingBtns = $(".OJBetter_setting");
  5624. $settingBtns.click(() => {
  5625. $settingBtns.prop("disabled", true).addClass("open");
  5626.  
  5627. // 设置面板div
  5628. const settingMenu = $(CFBetterSettingMenu_HTML)
  5629. $("body").append(settingMenu);
  5630.  
  5631. elementLocalize(settingMenu); // 加载i18n
  5632. OJB_showModal(settingMenu);
  5633. OJB_addDraggable($('#OJBetter_setting_menu')); // 窗口支持拖拽
  5634.  
  5635. // help帮助悬浮窗位置更新
  5636. $(document).on('mouseenter', '.help-icon', function (event) {
  5637. var menuOffset = $('.OJBetter_setting_menu:last').offset();
  5638. var mouseX = event.pageX - menuOffset.left;
  5639. var mouseY = event.pageY - menuOffset.top;
  5640.  
  5641. $('.tip_text').css({
  5642. 'top': mouseY + 'px',
  5643. 'left': mouseX + 'px'
  5644. });
  5645. });
  5646.  
  5647. // 选项卡切换
  5648. $('.OJBetter_setting_sidebar a').click(function (event) {
  5649. event.preventDefault();
  5650. $('.OJBetter_setting_sidebar a').removeClass('active');
  5651. $('.settings-page').removeClass('active');
  5652. $(this).addClass('active');
  5653. const targetPageId = $(this).attr('href').substring(1);
  5654. $('#' + targetPageId).addClass('active');
  5655. });
  5656.  
  5657. /**
  5658. * 更新单选按钮组的可用状态
  5659. * @param {string} selector 单选按钮组的选择器
  5660. * @param {string} targetLanguage 目标语言
  5661. * @param {Object} translationSupport 翻译支持的语言对应表
  5662. */
  5663. const updateRadioButtonsAvailability = (selector, targetLanguage) => {
  5664. Object.entries(OJBetter.supportList.translationSupport).forEach(([service, languages]) => {
  5665. const radioButton = $(selector).find(`input[value="${service}"]`);
  5666. const isEnabled = languages[targetLanguage];
  5667. $(radioButton).prop('disabled', !isEnabled);
  5668. if (!isEnabled) {
  5669. $(radioButton).prop('checked', false);
  5670. }
  5671. });
  5672. };
  5673.  
  5674. /**
  5675. * 检查下拉框选中项是否有效,若无效则清空
  5676. * @param {string} selector 下拉框的选择器
  5677. */
  5678. const validateSelectOption = (selector) => {
  5679. const selectedValue = $(selector).val();
  5680. if (!selectedValue) {
  5681. $(selector).val('');
  5682. }
  5683. };
  5684.  
  5685. /**
  5686. * 更新翻译目标语言下拉框的可用状态
  5687. * @param {string} selector 下拉框的选择器
  5688. * @param {string} targetLanguage 目标语言
  5689. * @param {Object} translationSupport 翻译支持的语言对应表
  5690. */
  5691. const updateSelectOptionsAvailability = (selector, targetLanguage) => {
  5692. $(selector).children('option').each(function () {
  5693. const optionValue = $(this).val();
  5694. const isEnabled = OJBetter.supportList.translationSupport[optionValue] ? OJBetter.supportList.translationSupport[optionValue][targetLanguage] : true;
  5695. $(this).prop('disabled', !isEnabled);
  5696. });
  5697. validateSelectOption(selector);
  5698. };
  5699.  
  5700. /**
  5701. * 更新翻译服务复选框的可用状态
  5702. * @param {string} selector 复选框的选择器
  5703. * @param {string} targetLanguage 目标语言
  5704. * @param {Object} translationSupport 翻译支持的语言对应表
  5705. */
  5706. const updateCheckboxesAvailability = (selector, targetLanguage) => {
  5707. $(selector).children('input').each(function () {
  5708. const checkboxValue = $(this).val();
  5709. const isEnabled = OJBetter.supportList.translationSupport[checkboxValue][targetLanguage];
  5710. $(this).prop('disabled', !isEnabled);
  5711. if (!isEnabled) {
  5712. $(this).prop('checked', false);
  5713. }
  5714. });
  5715. };
  5716.  
  5717. /**
  5718. * 更新更新源下拉框的可用状态
  5719. * @param {string} selector 下拉框的选择器
  5720. * @param {string} targetLanguage 目标语言
  5721. * @param {Object} translationSupport 翻译支持的语言对应表
  5722. */
  5723. const updateUpdateSourceSelectOptionsAvailability = (selector, updateChannel) => {
  5724. $(selector).children('option').each(function () {
  5725. const optionValue = $(this).val();
  5726. const isEnabled = OJBetter.supportList.updateSourceSupportList[optionValue][updateChannel];
  5727. $(this).prop('disabled', !isEnabled);
  5728. });
  5729. validateSelectOption(selector);
  5730. };
  5731.  
  5732. /**
  5733. * 创建配置结构
  5734. * @param {string} type - 该字段的在表单中的类型
  5735. * @param {string} value - 在配置中的键值
  5736. * @param {boolean} require - 是否是表单的必填项
  5737. * @param {string} [check=""] check - 调用的合法性检查
  5738. */
  5739. function createStructure(type, value, require, check = "") {
  5740. return { type, value, require, check };
  5741. }
  5742.  
  5743. // deepl配置
  5744. const deeplStructure = {
  5745. '#name': createStructure('text', 'name', true),
  5746. '#deepl_apiGenre': createStructure('text', 'apiGenre', true),
  5747. '#deepl_key': createStructure('text', 'key', false),
  5748. '#deepl_proxy': createStructure('text', 'proxy', false),
  5749. '#deepl_header': createStructure('text', '_header', false, 'keyValuePairs'),
  5750. '#deepl_data': createStructure('text', '_data', false, 'keyValuePairs'),
  5751. '#deepl_quota_url': createStructure('text', 'quota_url', false),
  5752. '#deepl_quota_method': createStructure('text', 'quota_method', false),
  5753. '#deepl_quota_header': createStructure('text', 'quota_header', false, 'keyValuePairs'),
  5754. '#deepl_quota_data': createStructure('text', 'quota_data', false, 'keyValuePairs'),
  5755. '#deepl_quota_surplus': createStructure('text', 'quota_surplus', false, 'dotSeparatedPath'),
  5756. };
  5757. let tempConfig_deepl = GM_getValue('deepl_config'); // 获取配置信息
  5758. const configManager_deepl = new ConfigManager('#deepl_config', 'deepl_config_', tempConfig_deepl, deeplStructure, deeplConfigEditHTML);
  5759. configManager_deepl.registerChoiceChange();
  5760.  
  5761. // chatgpt配置
  5762. const chatgptStructure = {
  5763. '#name': createStructure('text', 'name', true),
  5764. '#chatgpt_model': createStructure('text', 'model', false),
  5765. '#chatgpt_key': createStructure('text', 'key', true),
  5766. '#chatgpt_proxy': createStructure('text', 'proxy', false),
  5767. '#chatgpt_header': createStructure('text', '_header', false, 'keyValuePairs'),
  5768. '#chatgpt_data': createStructure('text', '_data', false, 'keyValuePairs'),
  5769. '#chatgpt_quota_url': createStructure('text', 'quota_url', false),
  5770. '#chatgpt_quota_header': createStructure('text', 'quota_header', false, 'keyValuePairs'),
  5771. '#chatgpt_quota_data': createStructure('text', 'quota_data', false, 'keyValuePairs'),
  5772. '#chatgpt_quota_surplus': createStructure('text', 'quota_surplus', false, 'dotSeparatedPath'),
  5773. '#chatgpt_quota_method': createStructure('text', 'quota_method', false),
  5774. };
  5775. let tempConfig_chatgpt = GM_getValue('chatgpt_config'); // 获取配置信息
  5776. const configManager_chatgpt = new ConfigManager('#chatgpt_config', 'chatgpt_config_', tempConfig_chatgpt, chatgptStructure, chatgptConfigEditHTML);
  5777. configManager_chatgpt.registerChoiceChange();
  5778.  
  5779. // Complet配置
  5780. const CompletStructure = {
  5781. '#name': createStructure('text', 'name', true),
  5782. '#complet_isChoose': createStructure('checkbox', 'isChoose', true),
  5783. '#complet_genre': createStructure('text', 'genre', true),
  5784. '#complet_language': createStructure('text', 'language', true),
  5785. '#complet_jsonUrl': createStructure('text', 'jsonUrl', true)
  5786. };
  5787. let tempConfig_Complet = GM_getValue('Complet_config'); // 获取配置信息
  5788. const configManager_complet = new ConfigManager('#Complet_config', 'complet_config_', tempConfig_Complet, CompletStructure, CompletConfigEditHTML, false);
  5789.  
  5790. // 状态更新
  5791. $("input[name='darkMode'][value='" + OJBetter.basic.darkMode + "']").prop("checked", true);
  5792. $("#showLoading").prop("checked", GM_getValue("showLoading") === true);
  5793. $("#expandFoldingblocks").prop("checked", GM_getValue("expandFoldingblocks") === true);
  5794. $("#renderPerfOpt").prop("checked", GM_getValue("renderPerfOpt") === true);
  5795. $("#commentPaging").prop("checked", GM_getValue("commentPaging") === true);
  5796. $("#standingsRecolor").prop("checked", GM_getValue("standingsRecolor") === true);
  5797. $("#showJumpToLuogu").prop("checked", GM_getValue("showJumpToLuogu") === true);
  5798. $("#hoverTargetAreaDisplay").prop("checked", GM_getValue("hoverTargetAreaDisplay") === true);
  5799. $("#showClistRating_contest").prop("checked", GM_getValue("showClistRating_contest") === true);
  5800. $("#showClistRating_problemset").prop("checked", GM_getValue("showClistRating_problemset") === true);
  5801. $("#showClistRating_problem").prop("checked", GM_getValue("showClistRating_problem") === true);
  5802. $("#RatingHidden").prop("checked", GM_getValue("RatingHidden") === true);
  5803. $('#scriptL10nLanguage').val(GM_getValue("scriptL10nLanguage"));
  5804. $('#localizationLanguage').val(GM_getValue("localizationLanguage"));
  5805. $("input[name='translation'][value='" + OJBetter.translation.choice + "']").prop("checked", true);
  5806. $("input[name='translation']").css("color", "gray");
  5807. $('#deepl_type').val(GM_getValue("deepl_type"));
  5808. $("#deepl_config_config_bar_ul").find(`input[name='deepl_config_config_item'][value='${tempConfig_deepl.choice}']`).prop("checked", true);
  5809. $('#enableEmphasisProtection').prop("checked", GM_getValue("enableEmphasisProtection") === true);
  5810. $('#enableLinkProtection').prop("checked", GM_getValue("enableLinkProtection") === true);
  5811. $("#chatgpt_config_config_bar_ul").find(`input[name='chatgpt_config_config_item'][value='${tempConfig_chatgpt.choice}']`).prop("checked", true);
  5812. $("#openai_isStream").prop("checked", GM_getValue("openai_isStream") === true);
  5813. $('#comment_translation_choice').val(GM_getValue("commentTranslationChoice"));
  5814. $('#iconButtonSize').val(GM_getValue("iconButtonSize"));
  5815. $("#autoTranslation").prop("checked", GM_getValue("autoTranslation") === true);
  5816. $('#shortTextLength').val(GM_getValue("shortTextLength"));
  5817. $("#allowMixTrans").prop("checked", GM_getValue("allowMixTrans") === true);
  5818. $('.OJBetter_checkboxs').find('input[type="checkbox"][name="mixedTranslation"]').each(function () {
  5819. if (OJBetter.translation.auto.mixTrans.servers.indexOf($(this).val()) > -1) {
  5820. $(this).prop('checked', true);
  5821. }
  5822. });
  5823. // 翻译目标语言下拉框
  5824. $('#transTargetLang').change(function () {
  5825. var selectedLang = $(this).val();
  5826. updateRadioButtonsAvailability('#translationServices', selectedLang);
  5827. updateSelectOptionsAvailability('#comment_translation_choice', selectedLang);
  5828. updateCheckboxesAvailability('.OJBetter_checkboxs', selectedLang);
  5829. });
  5830. $('#transTargetLang').val(GM_getValue("transTargetLang"));
  5831. $('#transTargetLang').change();
  5832. //
  5833. $('#comment_translation_mode').val(GM_getValue("commentTranslationMode"));
  5834. $("#memoryTranslateHistory").prop("checked", GM_getValue("memoryTranslateHistory") === true);
  5835. $('#transWaitTime').val(GM_getValue("transWaitTime"));
  5836. $('#translation_replaceSymbol').val(GM_getValue("replaceSymbol"));
  5837. $("#filterTextWithoutEmphasis").prop("checked", GM_getValue("filterTextWithoutEmphasis") === true);
  5838. $('#translation_retransAction').val(GM_getValue("retransAction"));
  5839. $("#clist_Authorization").val(GM_getValue("clist_Authorization"));
  5840. $("#problemPageCodeEditor").prop("checked", GM_getValue("problemPageCodeEditor") === true);
  5841. $("#isCodeSubmitConfirm").prop("checked", GM_getValue("isCodeSubmitConfirm") === true);
  5842. $("#alwaysConsumeMouseWheel").prop("checked", GM_getValue("alwaysConsumeMouseWheel") === true);
  5843. $("#submitButtonPosition").val(GM_getValue("submitButtonPosition"));
  5844. $("#cppCodeTemplateComplete").prop("checked", GM_getValue("cppCodeTemplateComplete") === true);
  5845. $("#useLSP").prop("checked", GM_getValue("useLSP") === true);
  5846. $("#OJBetter_Bridge_WorkUri").val(GM_getValue("OJBetter_Bridge_WorkUri"));
  5847. $("#OJBetter_Bridge_SocketUrl").val(GM_getValue("OJBetter_Bridge_SocketUrl"));
  5848. $("input[name='compiler'][value='" + OJBetter.monaco.onlineCompilerChoice + "']").prop("checked", true);
  5849. $("input[name='compiler']").css("color", "gray");
  5850. // 调试
  5851. $("#notWaiteLoaded").prop("checked", GM_getValue("notWaiteLoaded") === true);
  5852. // TODO 3
  5853. $('#l10n_refreshScrpitCacheButton').click(clearI18nextCache);
  5854. $('#indexedDB_clearButton').click(async () => { await clearDatabase(); });
  5855. $('#indexedDB_exportButton').click(async () => { downloadDataAsFile(await exportDatabase(), 'database_export.json') });
  5856. $('#indexedDB_importButton').click(() => { readFileInput(async (fileContent) => { await importDatabase(fileContent); }); });
  5857. $('#configuration_clearButton').click(deleteAllConfigSettings);
  5858. $('#configuration_exportButton').click(() => { downloadDataAsFile(exportSettingsToJSON(), 'configuration_export.json') });
  5859. $('#configuration_importButton').click(() => { readFileInput((fileContent) => { importSettingsFromJSON(fileContent); }) });
  5860. // 关于
  5861. $('#updateChannel').val(GM_getValue("updateChannel"));
  5862. $('#updateSource').val(GM_getValue("updateSource"));
  5863. $('#updateChannel').change(function () {
  5864. var selectedLang = $(this).val();
  5865. updateUpdateSourceSelectOptionsAvailability('#updateSource', selectedLang);
  5866. if (selectedLang == "dev") $('#thanksforDevChannelNotice').show();
  5867. else $('#thanksforDevChannelNotice').hide();
  5868. });
  5869. $('#updateChannel').change();
  5870.  
  5871. // 关闭
  5872. const $settingMenu = $(".OJBetter_setting_menu");
  5873. $settingMenu.on("click", ".btn-close", async () => {
  5874. // 设置的数据
  5875. const settings = {
  5876. darkMode: $("input[name='darkMode']:checked").val(),
  5877. showLoading: $("#showLoading").prop("checked"),
  5878. hoverTargetAreaDisplay: $("#hoverTargetAreaDisplay").prop("checked"),
  5879. expandFoldingblocks: $("#expandFoldingblocks").prop("checked"),
  5880. renderPerfOpt: $("#renderPerfOpt").prop("checked"),
  5881. commentPaging: $("#commentPaging").prop("checked"),
  5882. standingsRecolor: $("#standingsRecolor").prop("checked"),
  5883. showJumpToLuogu: $("#showJumpToLuogu").prop("checked"),
  5884. scriptL10nLanguage: $('#scriptL10nLanguage').val(),
  5885. localizationLanguage: $('#localizationLanguage').val(),
  5886. transTargetLang: $('#transTargetLang').val(),
  5887. translation: $("input[name='translation']:checked").val(),
  5888. deepl_type: $('#deepl_type').val(),
  5889. enableEmphasisProtection: $("#enableEmphasisProtection").prop("checked"),
  5890. enableLinkProtection: $("#enableLinkProtection").prop("checked"),
  5891. openai_isStream: $("#openai_isStream").prop("checked"),
  5892. commentTranslationChoice: $('#comment_translation_choice').val(),
  5893. iconButtonSize: $('#iconButtonSize').val(),
  5894. autoTranslation: $("#autoTranslation").prop("checked"),
  5895. shortTextLength: $('#shortTextLength').val(),
  5896. allowMixTrans: $("#allowMixTrans").prop("checked"),
  5897. mixedTranslation: (() => {
  5898. let mixedTranslation = [];
  5899. $('.OJBetter_checkboxs').find('input[type="checkbox"][name="mixedTranslation"]').each(function () {
  5900. if ($(this).is(":checked")) {
  5901. mixedTranslation.push($(this).val());
  5902. }
  5903. });
  5904. return mixedTranslation;
  5905. })(),
  5906. commentTranslationMode: $('#comment_translation_mode').val(),
  5907. memoryTranslateHistory: $('#memoryTranslateHistory').prop("checked"),
  5908. transWaitTime: $('#transWaitTime').val(),
  5909. replaceSymbol: $('#translation_replaceSymbol').val(),
  5910. filterTextWithoutEmphasis: $('#filterTextWithoutEmphasis').prop("checked"),
  5911. retransAction: $('#translation_retransAction').val(),
  5912. showClistRating_contest: $('#showClistRating_contest').prop("checked"),
  5913. showClistRating_problemset: $('#showClistRating_problemset').prop("checked"),
  5914. showClistRating_problem: $('#showClistRating_problem').prop("checked"),
  5915. RatingHidden: $('#RatingHidden').prop("checked"),
  5916. clist_Authorization: $('#clist_Authorization').val(),
  5917. problemPageCodeEditor: $("#problemPageCodeEditor").prop("checked"),
  5918. isCodeSubmitConfirm: $("#isCodeSubmitConfirm").prop("checked"),
  5919. alwaysConsumeMouseWheel: $("#alwaysConsumeMouseWheel").prop("checked"),
  5920. submitButtonPosition: $('#submitButtonPosition').val(),
  5921. cppCodeTemplateComplete: $("#cppCodeTemplateComplete").prop("checked"),
  5922. useLSP: $("#useLSP").prop("checked"),
  5923. OJBetter_Bridge_WorkUri: $('#OJBetter_Bridge_WorkUri').val().replace(/\\/g, '/').replace(/\/$/, ''),
  5924. OJBetter_Bridge_SocketUrl: $('#OJBetter_Bridge_SocketUrl').val(),
  5925. onlineCompilerChoice: $("input[name='compiler']:checked").val(),
  5926. notWaiteLoaded: $("#notWaiteLoaded").prop("checked"),
  5927. updateChannel: $('#updateChannel').val(),
  5928. updateSource: $('#updateSource').val()
  5929. };
  5930. // tempConfigs的数据
  5931. const tempConfigs = {
  5932. 'deepl_config': configManager_deepl.getTempConfig(),
  5933. 'chatgpt_config': configManager_chatgpt.getTempConfig(),
  5934. 'Complet_config': configManager_complet.getTempConfig()
  5935. }
  5936.  
  5937. // 判断是否改变
  5938. let changes = {};
  5939. const combinedConfigs = Object.assign({}, settings, tempConfigs); // 合并settings和tempConfigs对象
  5940. for (const [key, value] of Object.entries(combinedConfigs)) {
  5941. const storedValue = GM_getValue(key);
  5942. if (!OJB_deepEquals(value, storedValue)) {
  5943. changes[key] = { oldValue: storedValue, newValue: value };
  5944. }
  5945. }
  5946.  
  5947. // 如果changes对象不为空,则有变化
  5948. if (Object.keys(changes).length > 0) {
  5949. console.log("Changes detected:", changes);
  5950. const shouldSave = await OJB_createDialog(
  5951. i18next.t('saveSetting.title', { ns: 'dialog' }),
  5952. i18next.t('saveSetting.content', { ns: 'dialog' }),
  5953. [
  5954. i18next.t('saveSetting.buttons.0', { ns: 'dialog' }),
  5955. i18next.t('saveSetting.buttons.1', { ns: 'dialog' })
  5956. ]
  5957. ); // 配置改变保存确认
  5958. if (shouldSave) {
  5959. // 数据校验
  5960. // TODO
  5961. if (settings.deepl_type !== 'free') {
  5962. let selectedIndex = $('input[name="deepl_config_config_item"]:checked').length > 0;
  5963. if (!selectedIndex) {
  5964. $('.deepl_config a').removeClass('active');
  5965. $('.settings-page').removeClass('active');
  5966. $('#sidebar-translation-settings').addClass('active');
  5967. $('#translation-settings').addClass('active');
  5968.  
  5969. $('#deepl_config').addClass('missing');
  5970. return;
  5971. } else {
  5972. $('#deepl_config').removeClass('missing');
  5973. }
  5974. }
  5975. if (settings.translation === "openai") {
  5976. let selectedIndex = $('input[name="chatgpt_config_config_item"]:checked').length > 0;
  5977. if (!selectedIndex) {
  5978. $('.chatgpt_config a').removeClass('active');
  5979. $('.settings-page').removeClass('active');
  5980. $('#sidebar-translation-settings').addClass('active');
  5981. $('#translation-settings').addClass('active');
  5982.  
  5983. $('#chatgpt_config').addClass('missing');
  5984. return;
  5985. } else {
  5986. $('#chatgpt_config').removeClass('missing');
  5987. }
  5988. }
  5989. {
  5990. let selectedIndex = $('input[name="translation"]:checked').length > 0;
  5991. if (!selectedIndex) {
  5992. $('.OJBetter_setting_sidebar a').removeClass('active');
  5993. $('.settings-page').removeClass('active');
  5994. $('#sidebar-translation-settings').addClass('active');
  5995. $('#translation-settings').addClass('active');
  5996.  
  5997. $('#translationServices').addClass('missing');
  5998. return;
  5999. } else {
  6000. $('#translationServices').removeClass('missing');
  6001. }
  6002. }
  6003.  
  6004. // 保存数据
  6005. let refreshPage = false; // 是否需要刷新页面
  6006. for (const [key, value] of Object.entries(settings)) {
  6007. if (!refreshPage && !(key == 'translation' || key == 'darkMode' || key == 'commentTranslationChoice')) {
  6008. if (GM_getValue(key) != value) refreshPage = true;
  6009. }
  6010. GM_setValue(key, value);
  6011. }
  6012. for (const [key, value] of Object.entries(tempConfigs)) {
  6013. if (!refreshPage && (JSON.stringify(GM_getValue(key)) != JSON.stringify(value))) refreshPage = true;
  6014. GM_setValue(key, value);
  6015. }
  6016.  
  6017. if (refreshPage) location.reload();
  6018. else {
  6019. // 切换黑暗模式
  6020. if (OJBetter.basic.darkMode != settings.darkMode) {
  6021. OJBetter.basic.darkMode = settings.darkMode;
  6022. // 移除旧的事件监听器
  6023. changeEventListeners.forEach(listener => {
  6024. mediaQueryList.removeEventListener('change', listener);
  6025. });
  6026.  
  6027. if (OJBetter.basic.darkMode == "follow") {
  6028. changeEventListeners.push(handleColorSchemeChange);
  6029. mediaQueryList.addEventListener('change', handleColorSchemeChange);
  6030. $('html').removeAttr('data-theme');
  6031. } else if (OJBetter.basic.darkMode == "dark") {
  6032. $('html').attr('data-theme', 'dark');
  6033. if (OJBetter.monaco.editor) {
  6034. monaco.editor.setTheme('vs-dark');
  6035. }
  6036. } else {
  6037. $('html').attr('data-theme', 'light');
  6038. if (OJBetter.monaco.editor) {
  6039. monaco.editor.setTheme('vs');
  6040. }
  6041. // 移除旧的事件监听器
  6042. const mediaQueryList = window.matchMedia('(prefers-color-scheme: dark)');
  6043. window.matchMedia('(prefers-color-scheme: dark)');
  6044. }
  6045. }
  6046. // 更新配置信息
  6047. OJBetter.translation.choice = settings.translation;
  6048. OJBetter.translation.comment.choice = settings.commentTranslationChoice;
  6049. }
  6050. }
  6051. }
  6052. OJB_closeAndRemoveModal(settingMenu);
  6053. $settingBtns.prop("disabled", false).removeClass("open");
  6054. });
  6055. });
  6056. };
  6057.  
  6058. // html2markdown转换/处理规则
  6059. const turndownService = new TurndownService({ bulletListMarker: '-' });
  6060.  
  6061. // 保留原始
  6062. turndownService.keep(['del']);
  6063.  
  6064. // 丢弃
  6065. turndownService.addRule('remove-by-class', {
  6066. filter: function (node) {
  6067. return node.classList.contains('sample-tests') ||
  6068. node.classList.contains('header') ||
  6069. node.classList.contains('overlay') ||
  6070. node.classList.contains('html2md-panel') ||
  6071. node.classList.contains('likeForm');
  6072. },
  6073. replacement: function (content, node) {
  6074. return "";
  6075. }
  6076. });
  6077. turndownService.addRule('remove-script', {
  6078. filter: function (node, options) {
  6079. return node.tagName.toLowerCase() == "script" && node.type.startsWith("math/tex");
  6080. },
  6081. replacement: function (content, node) {
  6082. return "";
  6083. }
  6084. });
  6085.  
  6086. // inline math
  6087. turndownService.addRule('inline-math', {
  6088. filter: function (node, options) {
  6089. return node.tagName.toLowerCase() == "span" && node.className == "MathJax";
  6090. },
  6091. replacement: function (content, node) {
  6092. var latex = $(node).next().text();
  6093. latex = latex.replace(/</g, "&lt;").replace(/>/g, "&gt;");
  6094. return "$" + latex + "$";
  6095. }
  6096. });
  6097.  
  6098. // block math
  6099. turndownService.addRule('block-math', {
  6100. filter: function (node, options) {
  6101. return node.tagName.toLowerCase() == "div" && node.className == "MathJax_Display";
  6102. },
  6103. replacement: function (content, node) {
  6104. var latex = $(node).next().text();
  6105. latex = latex.replace(/</g, "&lt;").replace(/>/g, "&gt;");
  6106. return "\n$$\n" + latex + "\n$$\n";
  6107. }
  6108. });
  6109.  
  6110. // texFontStyle
  6111. turndownService.addRule('texFontStyle', {
  6112. filter: function (node) {
  6113. return (
  6114. node.nodeName === 'SPAN' &&
  6115. node.classList.contains('tex-font-style-bf')
  6116. )
  6117. },
  6118. replacement: function (content) {
  6119. return '**' + content + '**'
  6120. }
  6121. })
  6122.  
  6123. // sectionTitle
  6124. turndownService.addRule('sectionTitle', {
  6125. filter: function (node) {
  6126. return (
  6127. node.nodeName === 'DIV' &&
  6128. node.classList.contains('section-title')
  6129. )
  6130. },
  6131. replacement: function (content) {
  6132. return '**' + content + '**'
  6133. }
  6134. })
  6135.  
  6136. // property-title
  6137. turndownService.addRule('property-title', {
  6138. filter: function (node) {
  6139. return (
  6140. node.nodeName === 'DIV' &&
  6141. node.classList.contains('property-title')
  6142. )
  6143. },
  6144. replacement: function (content) {
  6145. return content + ': '
  6146. }
  6147. })
  6148.  
  6149.  
  6150. // bordertable
  6151. turndownService.addRule('bordertable', {
  6152. filter: 'table',
  6153. replacement: function (content, node) {
  6154. if (node.classList.contains('bordertable')) {
  6155. var output = [],
  6156. thead = '',
  6157. trs = node.querySelectorAll('tr');
  6158. if (trs.length > 0) {
  6159. var ths = trs[0].querySelectorAll('td,th');
  6160. if (ths.length > 0) {
  6161. thead = '| ' + Array.from(ths).map(th => turndownService.turndown(th.innerHTML.trim())).join(' | ') + ' |\n'
  6162. + '| ' + Array.from(ths).map(() => ' --- ').join('|') + ' |\n';
  6163. }
  6164. }
  6165. var rows = node.querySelectorAll('tr');
  6166. Array.from(rows).forEach(function (row, i) {
  6167. if (i > 0) {
  6168. var cells = row.querySelectorAll('td,th');
  6169. var trow = '| ' + Array.from(cells).map(cell => turndownService.turndown(cell.innerHTML.trim())).join(' | ') + ' |';
  6170. output.push(trow);
  6171. }
  6172. });
  6173. return thead + output.join('\n');
  6174. } else {
  6175. return content;
  6176. }
  6177. }
  6178. });
  6179.  
  6180. /**
  6181. * 任务队列
  6182. */
  6183. class TaskQueue {
  6184. constructor() {
  6185. this.taskQueues = {};
  6186. this.isProcessing = {}; // 处理状态
  6187. this.delays = {}; // 等待时间(毫秒)
  6188. }
  6189.  
  6190. getDelay(type) {
  6191. if (type === 'openai') {
  6192. return 0;
  6193. } else {
  6194. return OJBetter.translation.waitTime;
  6195. }
  6196. }
  6197.  
  6198. /**
  6199. * 添加任务
  6200. * @param {string} type 任务类型
  6201. * @param {function} fn 任务函数
  6202. * @param {boolean} isNonQueueTask 是否为非队列任务
  6203. */
  6204. addTask(type, fn, isNonQueueTask = false) {
  6205. if (!this.taskQueues[type]) {
  6206. this.taskQueues[type] = [];
  6207. }
  6208.  
  6209. if (isNonQueueTask) {
  6210. fn();
  6211. } else {
  6212. this.taskQueues[type].push(fn);
  6213.  
  6214. if (!this.isProcessing[type]) {
  6215. this.processQueue(type);
  6216. }
  6217. }
  6218. }
  6219.  
  6220. async processQueue(type) {
  6221. this.isProcessing[type] = true;
  6222.  
  6223. while (this.taskQueues[type].length > 0) {
  6224. const task = this.taskQueues[type].shift();
  6225. await task();
  6226.  
  6227. if (this.taskQueues[type].length > 0) {
  6228. await this.wait(this.getDelay(type));
  6229. }
  6230. }
  6231.  
  6232. this.isProcessing[type] = false;
  6233. }
  6234.  
  6235. wait(delay) {
  6236. return new Promise(resolve => {
  6237. setTimeout(resolve, delay);
  6238. });
  6239. }
  6240. }
  6241.  
  6242. /**
  6243. * 检测文本是否可能为代码片段
  6244. * @param {string} text 待检测的文本
  6245. * @returns {boolean} 是否可能为代码片段
  6246. */
  6247. function isLikelyCodeSnippet(text) {
  6248. // 移除LaTeX公式部分
  6249. const cleanedText = text.replace(/(\$\$?[\s\S]*?\$\$?)/g, '');
  6250.  
  6251. // 代码的关键字
  6252. const keywords = [
  6253. 'int', 'float', 'return', 'if', 'else', 'while', 'for', 'switch', 'case', 'break', 'continue',
  6254. 'class', 'public', 'private', 'protected', 'void', 'static', 'const', 'enum', 'struct',
  6255. 'char', 'double', 'long', 'include', 'def', 'import', 'from', 'as', 'elif', 'try', 'except',
  6256. 'raise', 'with', 'lambda', 'print'
  6257. ];
  6258. // 代码的特殊字符
  6259. const codeChars = [';', '{', '}', '<', '>', '=', '+', '-',
  6260. '&', '|', '#', ':', '\'\'\'', '\"\"\"', '->'];
  6261.  
  6262. // 普通文本的标点符号
  6263. const textChars = ['.', ',', '?', '!', ':', '"', "'"];
  6264.  
  6265. // 关键字的数量
  6266. const keywordCount = keywords.reduce((count, keyword) => {
  6267. const regex = new RegExp("\\b" + keyword + "\\b", 'gi');
  6268. return count + (cleanedText.match(regex) || []).length;
  6269. }, 0);
  6270.  
  6271. // 特殊字符的数量
  6272. const codeCharCount = codeChars.reduce((count, char) => {
  6273. const regex = new RegExp("\\" + char, 'g');
  6274. return count + (cleanedText.match(regex) || []).length;
  6275. }, 0);
  6276.  
  6277. // 普通文本字符的数量
  6278. const textCharCount = textChars.reduce((count, char) => {
  6279. const regex = new RegExp("\\" + char, 'g');
  6280. return count + (cleanedText.match(regex) || []).length;
  6281. }, 0);
  6282.  
  6283. // 检查Python的缩进特征
  6284. const hasPythonIndentation = cleanedText.includes('\n ') || cleanedText.includes('\n\t');
  6285.  
  6286. // 如果代码关键字数量或者特殊代码字符数量显著高于普通文本标点符号数量,或者存在Python缩进,则可能是代码
  6287. if (keywordCount > textCharCount * 2 || codeCharCount > textCharCount * 2 || hasPythonIndentation) {
  6288. return true;
  6289. }
  6290.  
  6291. return false;
  6292. }
  6293.  
  6294. /**
  6295. * 加载按钮相关函数
  6296. */
  6297. async function initButtonFunc() {
  6298. // 鼠标悬浮时为目标元素区域添加一个覆盖层
  6299. $.fn.addHoverOverlay = function (target) {
  6300. let position = $(target).css('position');
  6301. let display = $(target).css('display');
  6302.  
  6303. this.hover(() => {
  6304. $(target)
  6305. .addClass('overlay')
  6306. .css('position', 'relative');
  6307. if (display == "inline" || display == "contents") {
  6308. $(target).css('display', 'block');
  6309. }
  6310. }, () => {
  6311. $(target)
  6312. .removeClass('overlay')
  6313. .css('position', position);
  6314. if (display == "inline" || display == "contents") {
  6315. $(target).css('display', display);
  6316. }
  6317. })
  6318. }
  6319.  
  6320. /**
  6321. * 为按钮设置图标
  6322. * @param {string} icon 图标
  6323. * @returns {JQuery<HTMLElement>} 按钮
  6324. */
  6325. $.fn.setButtonIcon = function (icon) {
  6326. let i = this.find("i");
  6327. if (i.length != 0 && i.hasClass("iconfont")) {
  6328. i.html(icon);
  6329. } else {
  6330. i = $(`<i>${icon}</i>`);
  6331. this.prepend(i);
  6332. }
  6333. return this;
  6334. }
  6335.  
  6336. /**
  6337. * 设置按钮为加载等待状态
  6338. */
  6339. $.fn.setButtonLoading = function () {
  6340. this.addClass("loading");
  6341. this.prop("disabled", true);
  6342. return this;
  6343. }
  6344.  
  6345. /**
  6346. * 解除按钮的加载等待状态
  6347. */
  6348. $.fn.setButtonLoaded = function () {
  6349. this.removeClass("loading");
  6350. this.prop("disabled", false);
  6351. return this;
  6352. }
  6353.  
  6354. /**
  6355. * 为按钮设置popover提示文本
  6356. * @param {string} text 文本
  6357. * @returns {JQuery<HTMLElement>} 按钮
  6358. */
  6359. $.fn.setButtonPopover = function (text) {
  6360. // find if has popover_content class element
  6361. let popover_content = this.find(".popover_content");
  6362. if (popover_content.length != 0) {
  6363. popover_content.text(text);
  6364. } else {
  6365. popover_content = $(`<span class="popover_content">${text}</span>`);
  6366. this.append(popover_content);
  6367. }
  6368. return this;
  6369. }
  6370.  
  6371. /**
  6372. * 获取MarkDown
  6373. * @returns {string} MarkDown
  6374. */
  6375. $.fn.getMarkdown = function () {
  6376. const markdown = this.data('markdown');
  6377. if (markdown === undefined) {
  6378. const htmlContent = this.html();
  6379. const newMarkdown = turndownService.turndown(htmlContent);
  6380. this.data('markdown', newMarkdown);
  6381. return newMarkdown;
  6382. }
  6383. return markdown;
  6384. }
  6385.  
  6386. // 设置按钮状态
  6387. $.fn.setButtonState = function (state, popoverText = null, disabled = false) {
  6388. this.data('buttonState', state)
  6389. .prop('disabled', disabled)
  6390. .css('cursor', disabled ? 'not-allowed' : 'pointer')
  6391. .removeClass('running success enabled error loading redo');
  6392. if (popoverText) this.setButtonPopover(popoverText);
  6393.  
  6394. if (state !== 'initial') this.addClass(state);
  6395. return this;
  6396. };
  6397.  
  6398. // 为按钮添加鼠标悬浮重试
  6399. $.fn.setHoverRedo = function () {
  6400. this.hover(() => {
  6401. prevState = this.getButtonState();
  6402. if (prevState !== "normal" && prevState !== "running") {
  6403. this.setButtonState('redo');
  6404. }
  6405. }, () => {
  6406. const currentState = this.getButtonState();
  6407. if (prevState !== "normal" && ["normal", "redo"].includes(currentState)) {
  6408. this.setButtonState(prevState);
  6409. prevState = null;
  6410. }
  6411. });
  6412. };
  6413.  
  6414. // 获取按钮状态
  6415. $.fn.getButtonState = function () {
  6416. return this.data('buttonState') || 'normal';
  6417. };
  6418.  
  6419. // 设置翻译按钮状态
  6420. $.fn.setTransButtonState = function (state, text = null) {
  6421. const popoverText = text || i18next.t(`trans.${state}`, { ns: 'button' });
  6422. const disabled = state === 'running' || state === 'loading';
  6423. this.setButtonState(state, popoverText, disabled);
  6424. return this;
  6425. };
  6426.  
  6427. // 存翻译结果
  6428. $.fn.pushResultToTransButton = function (result) {
  6429. let resultStack = this.data('resultStack');
  6430. if (!resultStack) resultStack = [];
  6431. resultStack.push(result);
  6432. this.data('resultStack', resultStack);
  6433. }
  6434.  
  6435. // 获取翻译结果
  6436. $.fn.getResultFromTransButton = function () {
  6437. return this.data('resultStack');
  6438. }
  6439.  
  6440. // 标记为不自动翻译
  6441. $.fn.setNotAutoTranslate = function () {
  6442. this.data('notAutoTranslate', true);
  6443. }
  6444.  
  6445. // 获取是否为不自动翻译
  6446. $.fn.getNotAutoTranslate = function () {
  6447. return this.data('notAutoTranslate');
  6448. }
  6449.  
  6450. // 判断是否已经翻译
  6451. $.fn.IsTranslated = function () {
  6452. if (this.hasAttr('translated')) {
  6453. return true;
  6454. } else {
  6455. return false;
  6456. }
  6457. }
  6458.  
  6459. // 判断是否为评论区按钮
  6460. $.fn.IsCommentButton = function () {
  6461. let isCommentButton = this.data('isCommentButton');
  6462. if (isCommentButton == undefined) {
  6463. this.parents('.comments').length > 0 ? isCommentButton = true : isCommentButton = false;
  6464. this.data('isCommentButton', isCommentButton);
  6465. }
  6466. return isCommentButton;
  6467. }
  6468.  
  6469. // 按钮点击效果
  6470. $(document).on('mousedown', '.ojb_btn', function () {
  6471. $(this).addClass('active').on('animationend', () => $(this).removeClass('active'));
  6472. });
  6473. }
  6474.  
  6475. /**
  6476. * 添加题目markdown转换/复制/翻译按钮面板
  6477. * @param {HTMLElement} element 需要添加按钮面板的元素
  6478. * @param {string} suffix 按钮面板id后缀
  6479. * @param {string} type 按钮面板添加位置
  6480. * @param {boolean} is_simple 是否是简单模式
  6481. * @returns {object} 返回按钮面板元素
  6482. */
  6483. function addButtonPanel(element, suffix, type, is_simple = false) {
  6484. let text;
  6485. if (OJBetter.translation.comment.transMode == "1") text = i18next.t('trans.segment', { ns: 'button' });
  6486. else if (OJBetter.translation.comment.transMode == "2") text = i18next.t('trans.select', { ns: 'button' });
  6487. else text = i18next.t('trans.normal', { ns: 'button' });
  6488.  
  6489. let panel = $(`<div class='html2md-panel input-output-copier ${is_simple ? 'is_simple' : ''}'></div>`);
  6490. let viewButton = $(`
  6491. <button class='ojb_btn ojb_btn_popover top' id='html2md-view${suffix}'>
  6492. <i class="iconfont">&#xe7e5;</i>
  6493. <span class="popover_content">${i18next.t('md.normal', { ns: 'button' })}</span>
  6494. </button>`);
  6495. let copyButton = $(`
  6496. <button class='ojb_btn ojb_btn_popover top' id='html2md-cb${suffix}'>
  6497. <i class="iconfont">&#xe608;</i>
  6498. <span class="popover_content">${i18next.t('copy.normal', { ns: 'button' })}</span>
  6499. </button>`);
  6500. let translateButton = $(`
  6501. <button class='ojb_btn translateButton ojb_btn_popover top' id='translateButton${suffix}'>
  6502. <i class="iconfont">&#xe6be;</i>
  6503. <span class="popover_content">${text}</span>
  6504. </button>`);
  6505. if (!is_simple) panel.append(viewButton);
  6506. if (!is_simple) panel.append(copyButton);
  6507. panel.append(translateButton);
  6508. if (type === "this_level") {
  6509. $(element).before(panel);
  6510. } else if (type === "child_level") {
  6511. $(element).prepend(panel);
  6512. }
  6513.  
  6514. return {
  6515. panel: panel,
  6516. viewButton: viewButton,
  6517. copyButton: copyButton,
  6518. translateButton: translateButton
  6519. }
  6520. }
  6521.  
  6522. /**
  6523. * 添加MD视图按钮
  6524. * @param {JQuery<HTMLElement>} button 按钮
  6525. * @param {JQuery<HTMLElement>} element 目标元素
  6526. * @param {string} suffix id后缀
  6527. * @param {string} type 类型
  6528. * @returns {void}
  6529. */
  6530. async function addButtonWithHTML2MD(button, element, suffix, type) {
  6531. /**
  6532. * 改变按钮状态
  6533. * @param {string} state 状态
  6534. */
  6535. function changeButtonState(state) {
  6536. if (state == "loading") {
  6537. button.setButtonLoading();
  6538. button.setButtonPopover(i18next.t('state.waitMathJax', { ns: 'button' }));
  6539. } else if (state == "loaded") {
  6540. button.setButtonLoaded();
  6541. button.setButtonPopover(i18next.t('md.normal', { ns: 'button' }));
  6542. } else if (state == "normal") {
  6543. button.removeClass("enabled");
  6544. button.setButtonPopover(i18next.t('md.normal', { ns: 'button' }));
  6545. } else if (state == "mdView") {
  6546. button.addClass("enabled");
  6547. button.setButtonPopover(i18next.t('md.reduction', { ns: 'button' }));
  6548. } else if (state == "disabled") {
  6549. button.prop("disabled", true);
  6550. button.setButtonPopover(i18next.t('md.disabled', { ns: 'button' }));
  6551. }
  6552. }
  6553.  
  6554. if (OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru) {
  6555. changeButtonState("disabled");
  6556. return;
  6557. } else {
  6558. changeButtonState("loading");
  6559. await waitForMathJaxIdle();
  6560. changeButtonState("loaded");
  6561. }
  6562.  
  6563. button.click(OJB_debounce(function () {
  6564. var target = $(element).get(0);
  6565.  
  6566. /**
  6567. * 检查是否是MarkDown视图
  6568. * @returns {boolean} 是否是MarkDown视图
  6569. */
  6570. function checkViewmd() {
  6571. if ($(element).attr("viewmd") === "true") {
  6572. return true;
  6573. } else {
  6574. return false;
  6575. }
  6576. }
  6577.  
  6578. /**
  6579. * 设置是否是MarkDown视图
  6580. * @param {boolean} value 是否是MarkDown视图
  6581. * @returns {void}
  6582. */
  6583. function setViewmd(value) {
  6584. $(element).attr("viewmd", value);
  6585. if (value) {
  6586. changeButtonState("mdView");
  6587. } else {
  6588. changeButtonState("normal");
  6589. }
  6590. }
  6591.  
  6592. if (checkViewmd()) {
  6593. setViewmd(false);
  6594. $(element).next(".mdViewContent").remove();
  6595. $(element).show();
  6596. } else {
  6597. setViewmd(true);
  6598. var markdown = $(element).getMarkdown();
  6599. var mdViewContent = $(`<span class="mdViewContent" style="width:auto; height:auto;">${markdown}</span>`);
  6600. $(element).after(mdViewContent);
  6601. $(element).hide();
  6602. }
  6603. }));
  6604.  
  6605. if (OJBetter.preference.hoverTargetAreaDisplay && !OJBetter.typeOfPage.is_oldLatex && !OJBetter.typeOfPage.is_acmsguru) {
  6606. button.addHoverOverlay($(element));
  6607. }
  6608. }
  6609.  
  6610. /**
  6611. * 添加复制按钮
  6612. * @param {JQuery<HTMLElement>} button 按钮
  6613. * @param {JQuery<HTMLElement>} element 目标元素
  6614. * @param {string} suffix 后缀
  6615. * @param {string} type 类型
  6616. */
  6617. async function addButtonWithCopy(button, element, suffix, type) {
  6618. /**
  6619. * 改变按钮状态
  6620. * @param {string} state 状态
  6621. */
  6622. function changeButtonState(state) {
  6623. if (state == "loading") {
  6624. button.setButtonLoading();
  6625. button.setButtonPopover(i18next.t('state.waitMathJax', { ns: 'button' }));
  6626. } else if (state == "loaded") {
  6627. button.setButtonLoaded();
  6628. button.setButtonPopover(i18next.t('copy.normal', { ns: 'button' }));
  6629. } else if (state == "normal") {
  6630. button.setButtonPopover(i18next.t('copy.normal', { ns: 'button' }));
  6631. } else if (state == "copied") {
  6632. button.setButtonPopover(i18next.t('copy.copied', { ns: 'button' }));
  6633. } else if (state == "disabled") {
  6634. button.prop("disabled", true);
  6635. button.setButtonPopover(i18next.t('copy.disabled', { ns: 'button' }));
  6636. }
  6637. }
  6638.  
  6639. // 等待MathJax队列完成
  6640. if (OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru) {
  6641. changeButtonState("disabled");
  6642. return;
  6643. } else {
  6644. changeButtonState("loading");
  6645. await waitForMathJaxIdle();
  6646. changeButtonState("loaded");
  6647. }
  6648.  
  6649. button.click(OJB_debounce(function () {
  6650. var target = $(element).get(0);
  6651.  
  6652. var markdown = $(element).getMarkdown();
  6653.  
  6654. GM_setClipboard(markdown);
  6655.  
  6656. $(this).addClass("success");
  6657. changeButtonState("copied");
  6658.  
  6659.  
  6660. // 更新复制按钮文本
  6661. setTimeout(() => {
  6662. $(this).removeClass("success");
  6663. changeButtonState("normal")
  6664. }, 2000);
  6665. }));
  6666.  
  6667. if (OJBetter.preference.hoverTargetAreaDisplay && !OJBetter.typeOfPage.is_oldLatex && !OJBetter.typeOfPage.is_acmsguru) {
  6668. button.addHoverOverlay($(element));
  6669. }
  6670. }
  6671.  
  6672. /**
  6673. * 添加翻译按钮
  6674. * @param {JQuery<HTMLElement>} button 按钮
  6675. * @param {JQuery<HTMLElement>} element 目标元素
  6676. * @param {string} suffix 后缀
  6677. * @param {string} type 类型
  6678. * @param {boolean} is_comment 是否是评论
  6679. */
  6680. async function addButtonWithTranslation(button, element, suffix, type, is_comment = false) {
  6681. // 添加可指定翻译服务的方法调用
  6682. button.data("translatedItBy", function (translation) {
  6683. button.setTransButtonState('running', i18next.t('trans.wait', { ns: 'button' }));
  6684. OJBetter.common.taskQueue.addTask(translation, () => transTask(button, element, type, is_comment, translation), translation == 'openai');
  6685. });
  6686.  
  6687. // 等待MathJax队列完成
  6688. button.setButtonLoading();
  6689. await waitForMathJaxIdle();
  6690. button.setButtonLoaded();
  6691.  
  6692. // 标记目标文本是短字符文本
  6693. {
  6694. let text = $(element).getMarkdown();
  6695. let length = text.length;
  6696. if (length > OJBetter.translation.auto.shortTextLength || isLikelyCodeSnippet(text)) {
  6697. button.setNotAutoTranslate();
  6698. }
  6699. // button.after(`<span>${length}</span>`); // 显示字符数
  6700. }
  6701.  
  6702. button.click(OJB_debounce(async function () {
  6703. // 重新翻译
  6704. let resultStack = $(this).getResultFromTransButton();
  6705. if (resultStack) {
  6706. let pElements = $(element).find("p.block_selected:not(li p), li.block_selected");
  6707. for (let item of resultStack) {
  6708. if (OJBetter.translation.retransAction == "0") {
  6709. // 选段翻译不直接移除旧结果
  6710. if (OJBetter.translation.comment.transMode == "2") {
  6711. // 只移除即将要翻译的段的结果
  6712. if (pElements.is(item.translateDiv.getDiv().prev())) {
  6713. item.translateDiv.close();
  6714. }
  6715. } else {
  6716. item.translateDiv.close();
  6717. $($(element)).find(".translate-problem-statement, .translate-problem-statement-panel").remove();
  6718. }
  6719. } else {
  6720. item.translateDiv.foldMainDiv();
  6721. }
  6722. }
  6723. }
  6724.  
  6725. // 翻译
  6726. button.setTransButtonState('running', i18next.t('trans.wait', { ns: 'button' }));
  6727. OJBetter.common.taskQueue.addTask(OJBetter.translation.choice, () => transTask(button, element, type, is_comment), OJBetter.translation.choice == 'openai');
  6728. }));
  6729.  
  6730. // 重新翻译提示
  6731. let prevState;
  6732. button.hover(() => {
  6733. prevState = button.getButtonState();
  6734. if (prevState !== "normal" && prevState !== "running") {
  6735. button.setTransButtonState('redo');
  6736. }
  6737. }, () => {
  6738. const currentState = button.getButtonState();
  6739. if (prevState !== "normal" && ["normal", "redo"].includes(currentState)) {
  6740. button.setTransButtonState(prevState);
  6741. prevState = null;
  6742. }
  6743. });
  6744.  
  6745. // 目标区域指示
  6746. if (OJBetter.preference.hoverTargetAreaDisplay) {
  6747. button.addHoverOverlay($(element));
  6748. }
  6749.  
  6750. // 翻译右键切换菜单
  6751. $(document).on('contextmenu', '#translateButton' + suffix, function (e) {
  6752. e.preventDefault();
  6753.  
  6754. // 是否为评论的翻译
  6755. let is_comment = button.IsCommentButton();
  6756.  
  6757. // 移除旧的
  6758. if (!$(e.target).closest('.OJBetter_contextmenu').length) {
  6759. $('.OJBetter_contextmenu').remove();
  6760. }
  6761.  
  6762. var menu = $('<div class="OJBetter_contextmenu"></div>');
  6763. var translations = [
  6764. { value: 'deepl', name: i18next.t('translation.options.services.deepl', { ns: 'settings' }) },
  6765. { value: 'iflyrec', name: i18next.t('translation.options.services.iflyrec', { ns: 'settings' }) },
  6766. { value: 'youdao', name: i18next.t('translation.options.services.youdao', { ns: 'settings' }) },
  6767. { value: 'google', name: i18next.t('translation.options.services.google', { ns: 'settings' }) },
  6768. { value: 'caiyun', name: i18next.t('translation.options.services.caiyun', { ns: 'settings' }) },
  6769. { value: 'openai', name: i18next.t('translation.options.services.openai.name', { ns: 'settings' }) }
  6770. ];
  6771.  
  6772. // Function to check if the service supports the target language
  6773. function supportsTargetLanguage(service, targetLang) {
  6774. return OJBetter.supportList.translationSupport[service] && OJBetter.supportList.translationSupport[service][targetLang] !== undefined;
  6775. }
  6776.  
  6777. if (is_comment) {
  6778. var label = $(`<label><input type="radio" name="translation" value="0">
  6779. <span class="OJBetter_contextmenu_label_text">
  6780. ${i18next.t('translation.preference.comment_translation_choice.services.follow', { ns: 'settings' })}
  6781. </span></label>`);
  6782. menu.append(label);
  6783. }
  6784. translations.forEach(function (translation) {
  6785. if (supportsTargetLanguage(translation.value, OJBetter.translation.targetLang)) {
  6786. var label = $(`<label><input type="radio" name="translation" value="${translation.value}">
  6787. <span class="OJBetter_contextmenu_label_text">${translation.name}</span></label>`);
  6788. menu.append(label);
  6789. }
  6790. });
  6791.  
  6792. // 初始化
  6793. if (is_comment) {
  6794. menu.find(`input[name="translation"][value="${OJBetter.translation.comment.choice}"]`).prop('checked', true);
  6795. } else {
  6796. menu.find(`input[name="translation"][value="${OJBetter.translation.choice}"]`).prop('checked', true);
  6797. }
  6798. menu.css({
  6799. top: e.pageY + 'px',
  6800. left: e.pageX + 'px'
  6801. }).appendTo('body');
  6802.  
  6803. $(document).one('change', 'input[name="translation"]', function () {
  6804. if (is_comment) {
  6805. OJBetter.translation.comment.choice = $('input[name="translation"]:checked').val();
  6806. GM_setValue("commentTranslationChoice", OJBetter.translation.comment.choice);
  6807. } else {
  6808. OJBetter.translation.choice = $('input[name="translation"]:checked').val();
  6809. GM_setValue("translation", OJBetter.translation.choice);
  6810. }
  6811. $('.OJBetter_contextmenu').remove();
  6812. });
  6813.  
  6814. // 点击区域外关闭菜单
  6815. function handleClick(event) {
  6816. if (!$(event.target).closest('.OJBetter_contextmenu').length) {
  6817. $('.OJBetter_contextmenu').remove();
  6818. $(document).off('change', 'input[name="translation"]');
  6819. } else {
  6820. $(document).one('click', handleClick);
  6821. }
  6822. }
  6823. $(document).one('click', handleClick);
  6824. });
  6825. }
  6826.  
  6827. /**
  6828. * 创建翻译任务
  6829. * @param {JQuery<HTMLElement>} button 按钮
  6830. * @param {HTMLElement} element 目标元素
  6831. * @param {string} type 类型
  6832. * @param {boolean} is_comment 是否是评论
  6833. */
  6834. async function transTask(button, element, type, is_comment, translation) {
  6835. var target, element;
  6836. var count = {
  6837. errerNum: 0,
  6838. skipNum: 0
  6839. };
  6840. if (OJBetter.translation.comment.transMode == "1") {
  6841. // 分段翻译
  6842. var pElements = $(element).find("p:not(li p), li, .OJBetter_acmsguru");
  6843. for (let i = 0; i < pElements.length; i++) {
  6844. target = $(pElements[i]).eq(0).clone();
  6845. element_node = pElements[i];
  6846. await process(button, target, element_node, type, is_comment, count, translation);
  6847. }
  6848. } else if (OJBetter.translation.comment.transMode == "2") {
  6849. // 选段翻译
  6850. var pElements = $(element).find("p.block_selected:not(li p), li.block_selected, .OJBetter_acmsguru");
  6851. for (let i = 0; i < pElements.length; i++) {
  6852. target = $(pElements[i]).eq(0).clone();
  6853. element_node = pElements[i];
  6854. await process(button, target, element_node, type, is_comment, count, translation);
  6855. }
  6856. $(element).find("p.block_selected:not(li p), li.block_selected").removeClass('block_selected');
  6857. } else {
  6858. // 普通翻译
  6859. target = $(element).eq(0).clone();
  6860. if (type === "child_level") $(target).children(':first').remove();
  6861. element_node = $($(element)).get(0);
  6862. await process(button, target, element_node, type, is_comment, count, translation);
  6863. }
  6864.  
  6865. // 翻译完成
  6866. if (!count.errerNum && !count.skipNum) {
  6867. button.setTransButtonState('success');
  6868. }
  6869. }
  6870.  
  6871. /**
  6872. * 翻译处理
  6873. * @param {JQuery<HTMLElement>} button 按钮
  6874. * @param {HTMLElement} target 目标元素
  6875. * @param {HTMLElement} element_node 目标节点
  6876. * @param {string} type 类型
  6877. * @param {boolean} is_comment 是否是评论
  6878. */
  6879. async function process(button, target, element_node, type, is_comment, count, translation) {
  6880. if (type === "child_level") {
  6881. let div = $("<div>");
  6882. $(element_node).append(div);
  6883. element_node = div.get(0);
  6884. }
  6885.  
  6886. //是否跳过折叠块
  6887. if ($(target).find('.spoiler').length > 0) {
  6888. const shouldSkip = await OJB_createDialog(
  6889. i18next.t('skipFold.title', { ns: 'dialog' }),
  6890. i18next.t('skipFold.content', { ns: 'dialog' }),
  6891. [
  6892. i18next.t('skipFold.buttons.0', { ns: 'dialog' }),
  6893. i18next.t('skipFold.buttons.1', { ns: 'dialog' })
  6894. ],
  6895. true
  6896. ); //跳过折叠块确认
  6897. if (shouldSkip) {
  6898. $(target).find('.spoiler').remove();
  6899. } else {
  6900. $(target).find('.html2md-panel').remove();
  6901. }
  6902. }
  6903.  
  6904. // 等待结果
  6905. let result;
  6906. button.setTransButtonState('running');
  6907. result = await blockProcessing(button, target, element_node, is_comment, translation);
  6908. button.pushResultToTransButton(result);
  6909.  
  6910. if (result.status == "error") count.errerNum += 1;
  6911. else if (result.status == "skip") count.skipNum += 1;
  6912. $(target).remove();
  6913. }
  6914.  
  6915. // 块处理
  6916. async function blockProcessing(button, target, element_node, is_comment, translation) {
  6917. if (OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru) {
  6918. target.markdown = $(target).html();
  6919. } else if (!target.markdown) {
  6920. target.markdown = turndownService.turndown($(target).html());
  6921. }
  6922. var result = await translateProblemStatement(button, target.markdown, element_node, is_comment, translation);
  6923. if (result.status == "skip") {
  6924. button.setTransButtonState('error', i18next.t('trans.tooLong', { ns: 'button' }));
  6925. result.translateDiv.close();
  6926. } else if (result.status == "error" || !result.rawData.done) {
  6927. result.translateDiv.setError();
  6928. result.translateDiv.setRawData(result.rawData);
  6929. result.translateDiv.showDebugButton();
  6930. button.setTransButtonState('error', i18next.t('trans.error', { ns: 'button' }));
  6931. $(target).remove();
  6932. }
  6933. return result;
  6934. }
  6935.  
  6936. /**
  6937. * 选段翻译支持
  6938. */
  6939. async function multiChoiceTranslation() {
  6940. GM_addStyle(`
  6941. .topic .content .ttypography {
  6942. overflow: initial;
  6943. }
  6944. `);
  6945.  
  6946. $(document).on('click', 'p, li:not(:has(.comment)), .OJBetter_acmsguru', function (e) {
  6947. let $this = $(this);
  6948. e.stopPropagation();
  6949. if ($this.hasClass('block_selected')) {
  6950. $this.removeClass('block_selected');
  6951. // 移除对应的按钮
  6952. $('.OJBetter_MiniTranslateButton').remove("#translateButton_selected_" + $this.attr('OJBetter_p_id'));
  6953. } else {
  6954. let id = OJB_getRandomNumber(8);
  6955. $this.attr('OJBetter_p_id', id);
  6956. $this.addClass('block_selected');
  6957. // 添加按钮
  6958. let menu = $(`<div class="OJBetter_MiniTranslateButton" id='translateButton_selected_${id}'>${translateIcon}</div>`)
  6959. .css({
  6960. left: $($this).outerWidth(true) + $($this).position().left + 10 + 'px',
  6961. });
  6962. $this.before(menu);
  6963.  
  6964. $("#translateButton_selected_" + id).click(async function () {
  6965. // 处理旧的结果
  6966. if ($this.attr('translated')) {
  6967. let result = $this.data("resultData");
  6968. if (OJBetter.translation.retransAction == "0") {
  6969. result.translateDiv.close();
  6970. } else {
  6971. result.translateDiv.foldMainDiv();
  6972. }
  6973. }
  6974. // 翻译
  6975. let target = $this.eq(0).clone();
  6976. let result = await blockProcessing(OJBetter.translation.choice, target, $this.eq(0), $("#translateButton_selected_" + id), false);
  6977. $this.data("resultData", result);
  6978. $this.removeClass('block_selected');
  6979. // 移除对应的按钮
  6980. $('.OJBetter_MiniTranslateButton').remove("#translateButton_selected_" + id);
  6981. $this.attr('translated', '1'); // 标记已翻译
  6982. });
  6983. }
  6984. });
  6985. }
  6986.  
  6987. /**
  6988. * 为acmsguru题面重新划分div
  6989. */
  6990. async function acmsguruReblock() {
  6991. if (OJBetter.translation.comment.transMode == '0') {
  6992. // 普通模式下的划分方式
  6993. var html = $('.ttypography').children().html();
  6994. var separator = /(<div align="left" style="margin-top: 1\.0em;"><b>.*?<\/b><\/div>)/g;
  6995. var result = html.split(separator); // 分割代码
  6996. var outputHtml = '';
  6997. var header = '';
  6998. for (var i = 0; i < result.length; i++) {
  6999. if (separator.test(result[i])) {
  7000. header = result[i];
  7001. continue;
  7002. }
  7003. outputHtml += '<div class="ttypography">' + header + result[i] + '</div>';
  7004. header = '';
  7005. }
  7006. $('.ttypography').html(outputHtml);
  7007. }
  7008. else {
  7009. // 分段/选段模式下的划分方式
  7010. $('.ttypography').children().each(function () {
  7011. var html = $(this).html();
  7012. var replacedHtml = html.replace(/(?:<\/div>|<br><br>)(?<text>[\s\S]+?)(?=<br><br>)/g,
  7013. '<div align="left" class="OJBetter_acmsguru" >$<text></div>');
  7014. $(this).html(replacedHtml);
  7015. });
  7016. }
  7017. }
  7018.  
  7019. /**
  7020. * 添加MD/复制/翻译按钮
  7021. */
  7022. async function addConversionButton() {
  7023. // 题目页添加按钮
  7024. if (OJBetter.typeOfPage.is_problem) {
  7025. let exContentsPageClasses = ["sample-tests"];
  7026. $('.problem-statement').children('div').each((i, e) => {
  7027. var className = $(e).attr('class');
  7028. if (!exContentsPageClasses.includes(className)) {
  7029. var id = "_problem_" + OJB_getRandomNumber(8);
  7030. let panel = addButtonPanel(e, id, "this_level");
  7031. addButtonWithHTML2MD(panel.viewButton, e, id, "this_level");
  7032. addButtonWithCopy(panel.copyButton, e, id, "this_level");
  7033. addButtonWithTranslation(panel.translateButton, e, id, "this_level");
  7034. if (i == 0) panel.translateButton.setNotAutoTranslate(); // 题目标题块跳过,不自动翻译
  7035. }
  7036. });
  7037. }
  7038. // 添加按钮到ttypography部分
  7039. $(".ttypography").each(function () {
  7040. // 是否为评论
  7041. let is_comment = false;
  7042. if ($(this).parents('.comments').length > 0) is_comment = true;
  7043. // 题目页不添加
  7044. if (!OJBetter.typeOfPage.is_problem || OJBetter.typeOfPage.is_acmsguru) {
  7045. let id = "_ttypography_" + OJB_getRandomNumber(8);
  7046. let panel = addButtonPanel(this, id, "this_level");
  7047. addButtonWithHTML2MD(panel.viewButton, this, id, "this_level");
  7048. addButtonWithCopy(panel.copyButton, this, id, "this_level");
  7049. addButtonWithTranslation(panel.translateButton, this, id, "this_level", is_comment);
  7050. }
  7051. });
  7052.  
  7053. // 完整题目集页特殊处理
  7054. if (OJBetter.typeOfPage.is_completeProblemset) {
  7055. let exContentsPageClasses = ["sample-tests"];
  7056. $('.problem-statement').each(function () {
  7057. $(this).children('div').each(function (i, e) {
  7058. var className = $(e).attr('class');
  7059. if (!exContentsPageClasses.includes(className)) {
  7060. var id = "_problem_" + OJB_getRandomNumber(8);
  7061. let panel = addButtonPanel(e, id, "this_level");
  7062. addButtonWithHTML2MD(panel.viewButton, e, id, "this_level");
  7063. addButtonWithCopy(panel.copyButton, e, id, "this_level");
  7064. addButtonWithTranslation(panel.translateButton, e, id, "this_level");
  7065. if (i == 0) panel.translateButton.setNotAutoTranslate(); // 题目标题块跳过,不自动翻译
  7066. }
  7067. });
  7068. });
  7069. }
  7070.  
  7071. // 添加按钮到spoiler部分
  7072. $('.spoiler-content').each(function () {
  7073. if ($(this).find('.html2md-panel').length === 0) {
  7074. let id = "_spoiler_" + OJB_getRandomNumber(8);
  7075. let panel = addButtonPanel(this, id, "child_level");
  7076. addButtonWithHTML2MD(panel.viewButton, this, id, "child_level");
  7077. addButtonWithCopy(panel.copyButton, this, id, "child_level");
  7078. addButtonWithTranslation(panel.translateButton, this, id, "child_level");
  7079. }
  7080. });
  7081.  
  7082. // 添加按钮到titled部分
  7083. (function () {
  7084. var elements = [".Virtual.participation", ".Attention", ".Practice"];//只为部分titled添加
  7085. $.each(elements, (i, e) => {
  7086. $(e).each(function () {
  7087. let id = "_titled_" + OJB_getRandomNumber(8);
  7088. let nextDiv = $(this).next().children().get(0);
  7089. if (!nextDiv) return;
  7090. let panel = addButtonPanel(nextDiv, id, "child_level", true);
  7091. addButtonWithTranslation(panel.translateButton, nextDiv, id, "child_level");
  7092. });
  7093. });
  7094. })();
  7095. if (OJBetter.typeOfPage.is_mSite) {
  7096. $("div[class='_IndexPage_notice']").each(function () {
  7097. let id = "_titled_" + OJB_getRandomNumber(8);
  7098. let panel = addButtonPanel(this, id, "this_level", true);
  7099. addButtonWithTranslation(panel.translateButton, this, id, "this_level");
  7100. });
  7101. }
  7102.  
  7103. // 添加按钮到比赛QA部分
  7104. $(".question-response").each(function () {
  7105. let id = "_question_" + OJB_getRandomNumber(8);
  7106. let panel = addButtonPanel(this, id, "this_level", true);
  7107. addButtonWithTranslation(panel.translateButton, this, id, "this_level");
  7108. });
  7109. if (OJBetter.typeOfPage.is_mSite) {
  7110. $("div._ProblemsPage_announcements table tbody tr:gt(0)").each(function () {
  7111. var $nextDiv = $(this).find("td:first");
  7112. let id = "_question_" + OJB_getRandomNumber(8);
  7113. let panel = addButtonPanel($nextDiv, id, "this_level", true);
  7114. addButtonWithTranslation(panel.translateButton, $nextDiv, id, "this_level");
  7115. });
  7116. }
  7117.  
  7118. // 添加按钮到弹窗confirm-proto部分
  7119. $(".confirm-proto").each(function () {
  7120. let id = "_titled_" + OJB_getRandomNumber(8);
  7121. var $nextDiv = $(this).children().get(0);
  7122. let panel = addButtonPanel($nextDiv, id, "this_level", true);
  7123. addButtonWithTranslation(panel.translateButton, $nextDiv, id, "this_level");
  7124. });
  7125.  
  7126. // 添加按钮到_CatalogHistorySidebarFrame_item部分
  7127. $("._CatalogHistorySidebarFrame_item").each(function () {
  7128. let id = "_history_sidebar_" + OJB_getRandomNumber(8);
  7129. let panel = addButtonPanel(this, id, "this_level", true);
  7130. addButtonWithTranslation(panel.translateButton, this, id, "this_level");
  7131. });
  7132.  
  7133. $(".problem-lock-link").on("click", function () {
  7134. $(".popup .content div").each(function () {
  7135. let id = "_popup_" + OJB_getRandomNumber(8);
  7136. let panel = addButtonPanel(this, id, "this_level", true);
  7137. addButtonWithTranslation(panel.translateButton, this, id, "this_level");
  7138. });
  7139. });
  7140.  
  7141. // 添加按钮到弹窗alert部分
  7142. $(".alert:not(.OJBetter_alert)").each(function () {
  7143. let id = "_alert_" + OJB_getRandomNumber(8);
  7144. let panel = addButtonPanel(this, id, "child_level", true);
  7145. addButtonWithTranslation(panel.translateButton, this, id, "child_level");
  7146. });
  7147.  
  7148. // 添加按钮到talk-text部分
  7149. $(".talk-text").each(function () {
  7150. let id = "_talk-text_" + OJB_getRandomNumber(8);
  7151. let panel = addButtonPanel(this, id, "child_level", true);
  7152. addButtonWithTranslation(panel.translateButton, this, id, "child_level");
  7153. });
  7154. };
  7155.  
  7156. /**
  7157. * 等待LaTeX渲染队列全部完成
  7158. * @returns {Promise} 完成渲染
  7159. */
  7160. function waitForMathJaxIdle() {
  7161. return new Promise((resolve, reject) => {
  7162. var intervalId = setInterval(() => {
  7163. var queue = MathJax.Hub.queue;
  7164. if (queue.pending === 0 && queue.running === 0) {
  7165. clearInterval(intervalId);
  7166. resolve();
  7167. }
  7168. }, 100);
  7169. });
  7170. }
  7171.  
  7172. // 块替换
  7173. function replaceBlock(text, matches, replacements) {
  7174. try {
  7175. for (let i = 0; i < matches.length; i++) {
  7176. let match = matches[i];
  7177. let replacement = '';
  7178. if (OJBetter.translation.replaceSymbol === "1") {
  7179. replacement = `【${i + 1}】`;
  7180. } else if (OJBetter.translation.replaceSymbol === "2") {
  7181. replacement = `{${i + 1}}`;
  7182. } else if (OJBetter.translation.replaceSymbol === "3") {
  7183. replacement = `[${i + 1}]`;
  7184. }
  7185. text = text.replace(match, replacement);
  7186. replacements[replacement] = match;
  7187. }
  7188. } catch (e) { }
  7189. return text;
  7190. }
  7191.  
  7192. // 块还原
  7193. function recoverBlock(translatedText, matches, replacements) {
  7194. for (let i = 0; i < matches.length; i++) {
  7195. let match = matches[i];
  7196. let replacement = replacements[`【${i + 1}】`] || replacements[`[${i + 1}]`] || replacements[`{${i + 1}}`];
  7197.  
  7198. let latexMatch = '(?<latex_block>\\$\\$(\\\\.|[^\\$])*?\\$\\$)|(?<latex_inline>\\$(\\\\.|[^\\$])*?\\$)|';
  7199.  
  7200. let regex = new RegExp(latexMatch + `【\\s*${i + 1}\\s*】|\\[\\s*${i + 1}\\s*\\]|{\\s*${i + 1}\\s*}`, 'g');
  7201. translatedText = translatedText.replace(regex, function (match, ...args) {
  7202. // LaTeX中的不替换
  7203. const groups = args[args.length - 1]; // groups是replace方法的最后一个参数
  7204. if (groups.latex_block || groups.latex_inline) return match;
  7205. // 没有空格则加一个
  7206. const offset = args[args.length - 3]; // offset是replace方法的倒数第三个参数
  7207. let leftSpace = "", rightSpace = "";
  7208. if (!/\s/.test(translatedText[offset - 1])) leftSpace = " ";
  7209. if (!/\s/.test(translatedText[offset + match.length])) rightSpace = " ";
  7210. return leftSpace + replacement + rightSpace;
  7211. });
  7212.  
  7213. regex = new RegExp(latexMatch + `【\\s*${i + 1}(?![】\\d])|(?<![【\\d])${i + 1}\\s*】|\\[\\s*${i + 1}(?![\\]\\d])|(?<![\\[\\d])${i + 1}\\s*\\]|{\\s*${i + 1}(?![}\\d])|(?<![{\\d])${i + 1}\\s*}`, 'g');
  7214. translatedText = translatedText.replace(regex, function (match, ...args) {
  7215. // LaTeX中的不替换
  7216. const groups = args[args.length - 1];
  7217. if (groups.latex_block || groups.latex_inline) return match;
  7218. // 没有空格则加一个
  7219. const offset = args[args.length - 3];
  7220. let leftSpace = "", rightSpace = "";
  7221. if (!/\s/.test(translatedText[offset - 1])) leftSpace = " ";
  7222. if (!/\s/.test(translatedText[offset + match.length])) rightSpace = " ";
  7223. return leftSpace + replacement + rightSpace;
  7224. });
  7225. }
  7226. return translatedText;
  7227. }
  7228.  
  7229. /**
  7230. * 翻译结果面板
  7231. */
  7232. class TranslateDiv {
  7233. /**
  7234. * 构造函数
  7235. * @param {string} id 指定翻译框的id
  7236. */
  7237. constructor(id) {
  7238. this.id = id;
  7239. this.div = $('<div>').attr('id', id).addClass('translateDiv bounce-in');
  7240. if (!OJBetter.typeOfPage.is_completeProblemset) {
  7241. this.div.addClass('input-output-copier');
  7242. }
  7243. this.panelDiv = $('<div>').addClass('translate-problem-statement-panel');
  7244. this.div.append(this.panelDiv);
  7245.  
  7246. // 主要信息
  7247. this.mainDiv = $('<div>').addClass('translate-problem-statement');
  7248. this.span = $('<span>');
  7249. this.mainDiv.append(this.span);
  7250. this.div.append(this.mainDiv);
  7251. this.mainDivState = {
  7252. current: 'transHTML',
  7253. transHTML: '',
  7254. rawDataHTML: ''
  7255. };
  7256.  
  7257. // 顶栏信息
  7258. this.topText = $('<div>').addClass('topText');
  7259. this.panelDiv.append(this.topText);
  7260.  
  7261. // 右侧
  7262. this.rightDiv = $('<div>').css('display', 'flex');
  7263. this.panelDiv.append(this.rightDiv);
  7264. this.debugButton = $(`
  7265. <button class='ojb_btn ojb_btn_popover top'>
  7266. <i class="iconfont">&#xe641;</i>
  7267. <span class="popover_content">${i18next.t('rawData.normal', { ns: 'button' })}</span>
  7268. </button>`).hide();
  7269. this.rightDiv.append(this.debugButton);
  7270. this.queryBalanceButton = $(`
  7271. <button class='ojb_btn ojb_btn_popover top'>
  7272. <i class="iconfont">&#xe6ae;</i>
  7273. <span class="popover_content">${i18next.t('queryBalance.normal', { ns: 'button' })}</span>
  7274. </button>`).hide();
  7275. this.rightDiv.append(this.queryBalanceButton);
  7276. this.copyButton = $(`
  7277. <button class='ojb_btn ojb_btn_popover top'>
  7278. <i class="iconfont">&#xe608;</i>
  7279. <span class="popover_content">${i18next.t('copy.normal', { ns: 'button' })}</span>
  7280. </button>`);
  7281. this.rightDiv.append(this.copyButton);
  7282. this.upButton = $(`
  7283. <button class='ojb_btn ojb_btn_popover top'>
  7284. <i class="iconfont">&#xe601;</i>
  7285. <span class="popover_content">${i18next.t('fold.normal', { ns: 'button' })}</span>
  7286. </button>`);
  7287. this.rightDiv.append(this.upButton);
  7288. this.closeButton = $(`
  7289. <button class='ojb_btn ojb_btn_popover top'>
  7290. <i class="iconfont">&#xe614;</i>
  7291. <span class="popover_content">${i18next.t('close.normal', { ns: 'button' })}</span>
  7292. </button>`);
  7293. this.rightDiv.append(this.closeButton);
  7294. }
  7295.  
  7296. /**
  7297. * 获取翻译框
  7298. * @returns {JQuery<HTMLElement>} 返回翻译框
  7299. */
  7300. getDiv() {
  7301. return this.div;
  7302. }
  7303.  
  7304. /**
  7305. * 设置翻译框顶部的文本
  7306. * @param {string} text 翻译框顶部的文本
  7307. */
  7308. setTopText(text) {
  7309. this.div.attr("data-topText", text);
  7310. this.topText.text(text);
  7311. }
  7312.  
  7313. /**
  7314. * 获取翻译框顶部的文本
  7315. * @returns {string} 返回翻译框顶部的文本
  7316. */
  7317. getTopText() {
  7318. return this.topText.text();
  7319. }
  7320.  
  7321. /**
  7322. * 更新翻译框内容
  7323. * @param {string} text 文本内容
  7324. * @param {boolean} is_escapeHTML 是否转义HTML标签,为true则HTML标签将作为普通文本处理,默认为true
  7325. * @param {boolean} is_renderLaTeX 是否渲染LaTeX,为true则会渲染LaTeX,默认为true
  7326. */
  7327. updateTranslateDiv(text, is_escapeHTML = true, is_renderLaTeX = true,) {
  7328. // 渲染MarkDown
  7329. let md = window.markdownit({
  7330. html: !is_escapeHTML,
  7331. });
  7332. if (!text) text = "";
  7333. let html = md.render(text);
  7334. this.mainDiv.html(html);
  7335. // 渲染Latex
  7336. if (is_renderLaTeX) {
  7337. MathJax.Hub.Queue(["Typeset", MathJax.Hub, this.mainDiv.get(0)]);
  7338. }
  7339. }
  7340.  
  7341. /**
  7342. * 关闭元素
  7343. */
  7344. close() {
  7345. this.closeButton.click();
  7346. }
  7347.  
  7348. /**
  7349. * 注册(不可用)收起按钮事件
  7350. */
  7351. registerUpButtonEvent() {
  7352. this.upButton.on("click", () => {
  7353. // 如果没有reverse类,说明是展开状态
  7354. if (!this.upButton.hasClass("reverse")) {
  7355. // 执行收起操作
  7356. this.upButton.addClass("reverse");
  7357. this.upButton.setButtonState('initial', i18next.t('fold.unfold', { ns: 'button' }));
  7358. OJB_toggleCollapseExpand(this.mainDiv.get(0));
  7359. } else {
  7360. // 执行展开操作
  7361. this.upButton.removeClass("reverse");
  7362. this.upButton.setButtonState('initial', i18next.t('fold.normal', { ns: 'button' }));
  7363. OJB_toggleCollapseExpand(this.mainDiv.get(0));
  7364. }
  7365. });
  7366. }
  7367.  
  7368. /**
  7369. * 注册(不可用)关闭按钮事件
  7370. */
  7371. registerCloseButtonEvent() {
  7372. this.closeButton.on("click", () => {
  7373. $(this.div).remove();
  7374. $(this.panelDiv).remove();
  7375. if (OJBetter.typeOfPage.is_problem && OJBetter.translation.memory.enabled) {
  7376. OJBetter.translation.memory.ttTree.rmTransResultMap(this.id); // 移除ttTree中的数据
  7377. OJBetter.translation.memory.ttTree.refreshNode(".ttypography");
  7378. updateTransDBData(OJBetter.translation.memory.ttTree.getNodeDate(), OJBetter.translation.memory.ttTree.getTransResultMap()); // 更新DB中的数据
  7379. }
  7380. });
  7381. }
  7382.  
  7383. /**
  7384. * 注册(不可用)复制按钮事件
  7385. * @param {string} text 复制的文本
  7386. */
  7387. registerCopyButtonEvent(text) {
  7388. this.copyButton.on("click", () => {
  7389. GM_setClipboard(text);
  7390. this.copyButton.setButtonState('success', i18next.t('copy.copied', { ns: 'button' }));
  7391. // 复制提示
  7392. setTimeout(() => {
  7393. this.copyButton.setButtonState('initial', i18next.t('copy.normal', { ns: 'button' }));
  7394. }, 2000);
  7395. });
  7396. }
  7397.  
  7398. /**
  7399. * 禁用复制按钮
  7400. */
  7401. disableCopyButton() {
  7402. this.copyButton.css({ 'fill': '#ccc' });
  7403. this.copyButton.off("click");
  7404. }
  7405.  
  7406. /**
  7407. * 设置面板为error状态
  7408. */
  7409. setError() {
  7410. this.div.addClass('error');
  7411. this.panelDiv.addClass('error');
  7412. this.mainDiv.addClass('error');
  7413. }
  7414.  
  7415. /**
  7416. * 设置原始数据数据
  7417. * @param {Object} Object 原始数据
  7418. */
  7419. setRawData(Object) {
  7420. this.mainDivState.rawDataHTML = $("<pre>").text(JSON.stringify(Object, null, 4)).get(0);
  7421. if (this.mainDivState.current === 'rawDataHTML') {
  7422. this.renderMainDiv();
  7423. }
  7424. }
  7425.  
  7426. /**
  7427. * 切换结果面板与原始数据面板
  7428. */
  7429. switchMainDiv() {
  7430. // 在切换之前,保存当前内容的状态
  7431. this.mainDivState[this.mainDivState.current] = this.mainDiv.html();
  7432. // 切换当前状态
  7433. this.debugButton.setButtonState(this.mainDivState.current === 'transHTML' ? 'enabled' : 'initial');
  7434. this.mainDivState.current = this.mainDivState.current === 'transHTML' ? 'rawDataHTML' : 'transHTML';
  7435. // 渲染新的当前状态
  7436. this.renderMainDiv();
  7437. }
  7438.  
  7439. // 渲染当前内容到 mainDiv
  7440. renderMainDiv() {
  7441. requestAnimationFrame(() => {
  7442. this.mainDiv.html(this.mainDivState[this.mainDivState.current]);
  7443. });
  7444. }
  7445.  
  7446. /**
  7447. * 注册(不可用)debug按钮事件
  7448. */
  7449. registerDebugButtonEvent() {
  7450. this.debugButton.on("click", () => {
  7451. this.switchMainDiv();
  7452. });
  7453. }
  7454.  
  7455. /**
  7456. * 显示debug按钮
  7457. */
  7458. showDebugButton() {
  7459. this.debugButton.show();
  7460. this.registerDebugButtonEvent();
  7461. }
  7462.  
  7463. /**
  7464. * 注册(不可用)查询余额按钮事件
  7465. * @param {function} callback 查询回调函数
  7466. */
  7467. registerQueryBalanceButtonEvent(callback) {
  7468. this.queryBalanceButton.on("click", async () => {
  7469. this.queryBalanceButton.setButtonState('loading', i18next.t('queryBalance.loading', { ns: 'button' }));
  7470. try {
  7471. const balance = await callback();
  7472. this.queryBalanceButton.setButtonState('success', `${i18next.t('queryBalance.success', { ns: 'button' })} ${balance}`);
  7473. } catch (error) {
  7474. this.queryBalanceButton.setButtonState('error', `${i18next.t('queryBalance.error', { ns: 'button' })} ${error.message}`);
  7475. }
  7476. });
  7477. }
  7478.  
  7479. /**
  7480. * 显示余额查询按钮
  7481. * @param {string} server 服务名称
  7482. */
  7483. showQueryBalanceButton(server) {
  7484. if (server == 'deepl') {
  7485. const quotaConfig = OJBetter.deepl.config.quota;
  7486. if (quotaConfig.url && quotaConfig.surplus && quotaConfig.header) {
  7487. this.queryBalanceButton.show();
  7488. this.registerQueryBalanceButtonEvent(() => {
  7489. return queryServerBalance(OJBetter.deepl.config.quota);
  7490. });
  7491. }
  7492. } else if (server == 'openai') {
  7493. const quotaConfig = OJBetter.chatgpt.config.quota;
  7494. if (quotaConfig.url && quotaConfig.surplus && quotaConfig.header) {
  7495. this.queryBalanceButton.show();
  7496. this.registerQueryBalanceButtonEvent(() => {
  7497. return queryServerBalance(OJBetter.chatgpt.config.quota);
  7498. });
  7499. }
  7500. }
  7501. }
  7502. }
  7503.  
  7504. // 元素关系树
  7505. class ElementsTree {
  7506. constructor(elements) {
  7507. this.node = [];
  7508. this.transResultMap = {};
  7509. this.index = 0;
  7510. this.tagNames = ["DIV", "P", "UL", "LI"]
  7511. this.init($(elements));
  7512. }
  7513.  
  7514. // Iterate through all elements, because there may be multiple ttypography
  7515. init(elements) {
  7516. elements.each((i, e) => {
  7517. this.node.push({}); // add one element
  7518. this.index = 0; // reset index
  7519. this.create(i, $(e));
  7520. });
  7521. }
  7522.  
  7523. // 刷新关系树
  7524. refreshNode(elements) {
  7525. this.node = [];
  7526. this.index = 0;
  7527. this.init($(elements));
  7528. }
  7529.  
  7530. // 创建节点间的关系树
  7531. create(i_, element) {
  7532. var prev = null;
  7533. var node = this.node[i_];
  7534. element.children().each((i, e) => {
  7535. // only add element with tagNames
  7536. if (this.tagNames.includes($(e).prop("tagName"))) {
  7537. prev = this.addNode(i_, prev, e);
  7538. }
  7539. // recursively child element
  7540. if ($(e).children().length > 0 && prev !== null) {
  7541. node[prev].firstChild = this.index;
  7542. this.create(i_, $(e));
  7543. }
  7544. });
  7545. }
  7546.  
  7547. // 向树中添加一个节点
  7548. addNode(i_, prev, e) {
  7549. var node = this.node[i_];
  7550. node[this.index] = {
  7551. prev: prev,
  7552. next: null,
  7553. firstChild: null,
  7554. type: $(e).prop("tagName"),
  7555. isTranslateDiv: $(e).hasClass("translateDiv"),
  7556. topText: $(e).attr("data-topText"),
  7557. id: $(e).attr("id"),
  7558. };
  7559.  
  7560. if (prev !== null) {
  7561. node[prev].next = this.index;
  7562. }
  7563.  
  7564. prev = this.index;
  7565.  
  7566. this.index++;
  7567. return prev;
  7568. }
  7569.  
  7570. getNodeDate() {
  7571. return this.node;
  7572. }
  7573.  
  7574. setNodeDate(node) {
  7575. this.node = node;
  7576. }
  7577.  
  7578. getTransResultMap() {
  7579. return this.transResultMap;
  7580. }
  7581.  
  7582. setTransResultMap(transResultMap) {
  7583. this.transResultMap = transResultMap;
  7584. }
  7585.  
  7586. rmTransResultMap(id) {
  7587. delete this.transResultMap[id];
  7588. }
  7589.  
  7590. addTransResultMap(id, text) {
  7591. this.transResultMap[id] = text;
  7592. }
  7593.  
  7594. getTranslateDivNum(ttTree) {
  7595. var num = 0;
  7596. for (var i in ttTree) {
  7597. if (ttTree[i].isTranslateDiv) {
  7598. num++;
  7599. }
  7600. }
  7601. return num;
  7602. }
  7603.  
  7604. // 恢复目标元素中的translateDiv
  7605. recover(elements) {
  7606. elements.each((i, e) => {
  7607. var ttTreeNode = this.node[i];
  7608. var missingTranslateDivs = this.getTranslateDivNum(ttTreeNode);
  7609. if (missingTranslateDivs > 0) {
  7610. this.recoverOneElement($(e), ttTreeNode);
  7611. }
  7612. });
  7613. }
  7614.  
  7615. recoverOneElement(element, ttTreeNode) {
  7616. this.recoverOneFork(element.children().eq(0), ttTreeNode, 0);
  7617. }
  7618.  
  7619. // 恢复一个分支
  7620. recoverOneFork(pElement, ttTreeNode, index) {
  7621. do {
  7622. // only recover element with tagNames
  7623. if (!this.tagNames.includes(pElement.prop("tagName"))) {
  7624. if (pElement.next().length > 0) {
  7625. pElement = pElement.next();
  7626. } else {
  7627. return;
  7628. }
  7629. }
  7630. if (pElement.prop("tagName") !== ttTreeNode[index].type) {
  7631. // console.warn(`类型不同, 元素结构可能已经发生了变化: \nindex: ${index}`);
  7632. // console.warn(pElement);
  7633. return;
  7634. } else {
  7635. // recursively child element
  7636. var node = ttTreeNode[index];
  7637. if (node.firstChild !== null) {
  7638. this.recoverOneFork(
  7639. pElement.children().eq(0),
  7640. ttTreeNode,
  7641. node.firstChild
  7642. );
  7643. }
  7644. // check if next node is translateDiv
  7645. if (node.next !== null) {
  7646. index = node.next;
  7647. var ne_node = ttTreeNode[index];
  7648. if (ne_node.isTranslateDiv) {
  7649. var id = ne_node.id;
  7650. var topText = ne_node.topText;
  7651. var text = this.transResultMap[id];
  7652. // create element after pElement
  7653. this.reCreateTransDiv(pElement, id, text, topText);
  7654. }
  7655. pElement = pElement.next(); // go to next element
  7656. }
  7657. }
  7658. } while (node.next !== null);
  7659. }
  7660.  
  7661. // 重新创建translateDiv
  7662. reCreateTransDiv(pElement, id, translatedText, topText) {
  7663. const translateDiv = new TranslateDiv(id);
  7664. pElement.after(translateDiv.getDiv());
  7665. translateDiv.setTopText(topText);
  7666. translateDiv.registerUpButtonEvent();
  7667. translateDiv.registerCloseButtonEvent();
  7668. if (!OJBetter.typeOfPage.is_oldLatex && !OJBetter.typeOfPage.is_acmsguru) {
  7669. translateDiv.registerCopyButtonEvent(translatedText);
  7670. } else {
  7671. translateDiv.disableCopyButton();
  7672. }
  7673. translateDiv.updateTranslateDiv(translatedText, !(OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru));
  7674. // 标记已翻译并添加到翻译按钮的结果栈中
  7675. let transButton = pElement.prev('.html2md-panel').find('.translateButton');
  7676. if (transButton.length == 0) {
  7677. // 如果没有找到,则应该是得在父元素中找到
  7678. transButton = pElement.parent().prev('.html2md-panel').find('.translateButton');
  7679. }
  7680. transButton.pushResultToTransButton({
  7681. translateDiv: translateDiv,
  7682. status: 0
  7683. });
  7684. transButton.setTransButtonState('success');
  7685. }
  7686. }
  7687.  
  7688. // 更新TransDB中的翻译数据
  7689. async function updateTransDBData(nodeDate, transResultMap) {
  7690. var url = window.location.href.replace(/#/, "");
  7691. try {
  7692. await OJBetter.common.database.translateData.put({ url, transResultMap, nodeDate });
  7693. return 'translateData saved successfully';
  7694. } catch (error) {
  7695. throw new Error(`Failed to save translateData: ${error}`);
  7696. }
  7697. }
  7698.  
  7699. // 获取TransDB中保存的翻译数据
  7700. async function getTransDBData() {
  7701. var url = window.location.href.replace(/#/, "");
  7702. try {
  7703. const result = await OJBetter.common.database.translateData.get(url);
  7704. return result;
  7705. } catch (error) {
  7706. throw new Error(`Failed to get translateData: ${error}`);
  7707. }
  7708. }
  7709.  
  7710. /**
  7711. * 翻译结果恢复功能初始化
  7712. * @returns
  7713. */
  7714. async function initTransResultsRecover() {
  7715. OJBetter.translation.memory.ttTree = new ElementsTree(".ttypography"); // 初始化当前页面.ttypography元素的结构树
  7716. let result = await getTransDBData();
  7717. if (!result) return;
  7718. OJBetter.translation.memory.ttTree.setNodeDate(result.nodeDate);
  7719. OJBetter.translation.memory.ttTree.setTransResultMap(result.transResultMap);
  7720. OJBetter.translation.memory.ttTree.recover($(".ttypography"));
  7721. }
  7722.  
  7723. /**
  7724. * 自动翻译
  7725. */
  7726. async function initTransWhenViewable() {
  7727. await waitForMathJaxIdle();
  7728.  
  7729. const elements = $('.ttypography, .comments').find('.translateButton');
  7730. const observers = [];
  7731.  
  7732. // Use a single Intersection Observer for all elements
  7733. const observer = new IntersectionObserver((entries, obs) => {
  7734. entries.forEach((entry) => {
  7735. if (entry.isIntersecting) {
  7736. const button = $(entry.target);
  7737. const state = button.getButtonState();
  7738. const notAutoTranslate = button.getNotAutoTranslate();
  7739. // Check if the button meets the criteria
  7740. if (state === 'normal' && !notAutoTranslate) {
  7741. let trans = OJBetter.translation.choice;
  7742.  
  7743. if (OJBetter.translation.auto.mixTrans.enabled && button.IsCommentButton() && OJBetter.translation.auto.mixTrans.servers.length > 0) {
  7744. const randomIndex = Math.floor(Math.random() * OJBetter.translation.auto.mixTrans.servers.length);
  7745. trans = OJBetter.translation.auto.mixTrans.servers[randomIndex];
  7746. }
  7747. button.data("translatedItBy")(trans);
  7748. }
  7749.  
  7750. // Stop observing the element
  7751. obs.unobserve(entry.target);
  7752. }
  7753. });
  7754. });
  7755.  
  7756. // Observe each element
  7757. elements.each((i, e) => {
  7758. observer.observe(e);
  7759. });
  7760.  
  7761. // Store the observer in case you need to disconnect it later
  7762. observers.push(observer);
  7763. }
  7764.  
  7765. // 翻译主方法
  7766. async function translateProblemStatement(button, text, element_node, is_comment, translation_) {
  7767. let status = "ok";
  7768. let id = OJB_getRandomNumber(8);
  7769. let matches = [];
  7770. let replacements = {};
  7771. let translatedText = "";
  7772. let rawData = {
  7773. done: false
  7774. };
  7775.  
  7776. /**
  7777. * LaTeX替换
  7778. * @param {string} text
  7779. * @returns {string}
  7780. */
  7781. function replaceLatex(text) {
  7782. if (OJBetter.typeOfPage.is_oldLatex) {
  7783. let regex = /<span\s+class="tex-span">.*?<\/span>/gi;
  7784. matches = matches.concat(text.match(regex));
  7785. text = replaceBlock(text, matches, replacements);
  7786. text = text.replace(/<p>(.*?)<\/p>/g, "$1\n\n"); // <p/>标签换为换行
  7787. } else if (OJBetter.typeOfPage.is_acmsguru) {
  7788. let regex = /<i>.*?<\/i>|<sub>.*?<\/sub>|<sup>.*?<\/sup>|<pre>.*?<\/pre>/gi;
  7789. matches = matches.concat(text.match(regex));
  7790. text = replaceBlock(text, matches, replacements);
  7791. } else if (realTranlate != "openai") {
  7792. // 使用GPT翻译时不必替换latex公式
  7793. let regex = /\$\$(\\.|[^\$])*?\$\$|\$(\\.|[^\$])*?\$/g;
  7794. matches = matches.concat(text.match(regex));
  7795. text = replaceBlock(text, matches, replacements);
  7796. }
  7797. return text;
  7798. }
  7799.  
  7800. /**
  7801. * LaTeX恢复
  7802. * @param {*} translatedText
  7803. * @returns {string}
  7804. */
  7805. function recoverLatex(translatedText) {
  7806. translatedText = translatedText.replace(/】\s*【/g, '】 【');
  7807. translatedText = translatedText.replace(/\]\s*\[/g, '] [');
  7808. translatedText = translatedText.replace(/\}\s*\{/g, '} {');
  7809. if (OJBetter.typeOfPage.is_oldLatex) {
  7810. translatedText = translatedText.replace(/(.+?)(\n\n|$)/g, "<p>$1</p>"); // 换行符还原为<p/>标签
  7811. translatedText = recoverBlock(translatedText, matches, replacements);
  7812. } else if (OJBetter.typeOfPage.is_acmsguru) {
  7813. translatedText = recoverBlock(translatedText, matches, replacements);
  7814. } else if (realTranlate != "openai") {
  7815. translatedText = recoverBlock(translatedText, matches, replacements);
  7816. }
  7817. return translatedText;
  7818. }
  7819.  
  7820. /**
  7821. * 格式化翻译结果
  7822. * @param {string} translatedText
  7823. * @returns {string} 处理后的翻译结果
  7824. */
  7825. function formatText(translatedText) {
  7826. // 转义LaTex中的特殊符号
  7827. if (!OJBetter.typeOfPage.is_oldLatex && !OJBetter.typeOfPage.is_acmsguru) {
  7828. const escapeRules = [
  7829. { pattern: /(?<!\\)>(?!\s)/g, replacement: " &gt; " }, // >符号
  7830. { pattern: /(?<!\\)</g, replacement: " &lt; " }, // <符号
  7831. { pattern: /(?<!\\)\*/g, replacement: " &#42; " }, // *符号
  7832. { pattern: /(?<!\\)_/g, replacement: " &#95; " }, // _符号
  7833. { pattern: /(?<!\\)\\\\(?=\s)/g, replacement: "\\\\\\\\" }, // \\符号
  7834. { pattern: /(?<!\\)\\(?![\\a-zA-Z0-9])/g, replacement: "\\\\" }, // \符号
  7835. ];
  7836.  
  7837. let latexMatches = [...translatedText.matchAll(/\$\$([\s\S]*?)\$\$|\$(.*?)\$|\$([\s\S]*?)\$/g)];
  7838.  
  7839. for (const match of latexMatches) {
  7840. const matchedText = match[0];
  7841. let escapedText = matchedText;
  7842.  
  7843. for (const rule of escapeRules) {
  7844. escapedText = escapedText.replaceAll(rule.pattern, rule.replacement);
  7845. }
  7846. escapedText = escapedText.replace(/\$\$/g, "$$$$$$$$");// $$符号(因为后面需要作为replacement)
  7847. translatedText = translatedText.replace(matchedText, escapedText);
  7848. }
  7849. }
  7850.  
  7851. // 使符合mathjx的转换语法
  7852. const mathjaxRuleMap = [
  7853. { pattern: /\$/g, replacement: "$$$$$$" }, // $$ 行间
  7854. ];
  7855. mathjaxRuleMap.forEach(({ pattern, replacement }) => {
  7856. translatedText = translatedText.replace(pattern, replacement);
  7857. });
  7858.  
  7859. // markdown修正
  7860. const mdRuleMap = [
  7861. { pattern: /(\s_[\u4e00-\u9fa5]+_)([\u4e00-\u9fa5]+)/g, replacement: "$1 $2" }, // 斜体
  7862. { pattern: /(_[\u4e00-\u9fa5]+_\s)([\u4e00-\u9fa5]+)/g, replacement: " $1$2" },
  7863. { pattern: /(_[\u4e00-\u9fa5]+_)([\u4e00-\u9fa5]+)/g, replacement: " $1 $2" },
  7864. { pattern: /(([\s\S]*?))/g, replacement: "($1)" }, // 中文()
  7865. // { pattern: /:/g, replacement: ":" }, // 中文:
  7866. { pattern: /\*\* (.*?) \*\*/g, replacement: "\*\*$1\*\*" } // 加粗
  7867. ];
  7868. mdRuleMap.forEach(({ pattern, replacement }) => {
  7869. translatedText = translatedText.replace(pattern, replacement);
  7870. });
  7871.  
  7872. return translatedText;
  7873. }
  7874.  
  7875. // 创建翻译结果元素并放在element_node的后面
  7876. const translateDiv = new TranslateDiv(id);
  7877. $(element_node).after(translateDiv.getDiv());
  7878.  
  7879. // 当前实际翻译服务
  7880. let realTranlate;
  7881. if (translation_) {
  7882. realTranlate = translation_;
  7883. } else {
  7884. if (is_comment && OJBetter.translation.comment.choice != "0") realTranlate = OJBetter.translation.comment.choice;
  7885. else realTranlate = OJBetter.translation.choice;
  7886. }
  7887.  
  7888. // 信息
  7889. translateDiv.setTopText(i18next.t('servers.' + realTranlate, { ns: 'translator' }) +
  7890. i18next.t('translateDiv.topTextSuffix', { ns: 'translator' }));
  7891.  
  7892. // 注册(不可用)按钮
  7893. translateDiv.registerUpButtonEvent();
  7894. translateDiv.registerCloseButtonEvent();
  7895. if (OJBetter.translation.choice == 'openai' || OJBetter.translation.choice == 'deepl') {
  7896. translateDiv.showQueryBalanceButton(OJBetter.translation.choice); // 额度查询
  7897. }
  7898.  
  7899. // 翻译内容是否可能为代码片段
  7900. if (isLikelyCodeSnippet(text)) {
  7901. const shouldContinue = await OJB_createDialog(
  7902. i18next.t('isLikelyCodeSnippet.title', { ns: 'dialog' }),
  7903. i18next.t('isLikelyCodeSnippet.content', { ns: 'dialog' }),
  7904. [
  7905. i18next.t('isLikelyCodeSnippet.buttons.0', { ns: 'dialog' }),
  7906. i18next.t('isLikelyCodeSnippet.buttons.1', { ns: 'dialog' })
  7907. ],
  7908. true
  7909. );
  7910. if (shouldContinue) {
  7911. return {
  7912. translateDiv: translateDiv,
  7913. status: "skip",
  7914. rawData: rawData
  7915. };
  7916. }
  7917. }
  7918.  
  7919. // 替换latex公式
  7920. text = replaceLatex(text);
  7921.  
  7922. // 过滤**号
  7923. if (OJBetter.translation.filterTextWithoutEmphasis && GM_getValue("translation") !== "openai") { // TODO
  7924. text = text.replace(/\*\*/g, "");
  7925. }
  7926.  
  7927. // 字符数上限
  7928. const translationLimits = {
  7929. deepl: 5000,
  7930. iflyrec: 2000,
  7931. youdao: 600,
  7932. google: 5000,
  7933. caiyun: 5000
  7934. };
  7935. if (translationLimits.hasOwnProperty(realTranlate) && text.length > translationLimits[realTranlate]) {
  7936. let textLength = translationLimits[realTranlate];
  7937. let realTextLength = text.length;
  7938. const shouldContinue = await OJB_createDialog(
  7939. i18next.t('transTextLimits.title', { ns: 'dialog' }),
  7940. i18next.t('transTextLimits.content', { ns: 'dialog', textLength: textLength, realTextLength: realTextLength }),
  7941. [
  7942. i18next.t('transTextLimits.buttons.0', { ns: 'dialog' }),
  7943. i18next.t('transTextLimits.buttons.1', { ns: 'dialog' })
  7944. ],
  7945. true
  7946. ); // 字数超限确认
  7947. if (shouldContinue) {
  7948. return {
  7949. translateDiv: translateDiv,
  7950. status: "skip",
  7951. rawData: rawData
  7952. };
  7953. }
  7954. }
  7955.  
  7956. // 翻译
  7957. async function translate(translation) {
  7958. const is_renderLaTeX = !(OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru);
  7959. const servername = i18next.t('servers.' + realTranlate, { ns: 'translator' });
  7960. let rawData = {};
  7961. try {
  7962. if (translation == "deepl") {
  7963. if (OJBetter.deepl.config.type == 'free') {
  7964. rawData = await translate_deepl(text);
  7965. translateDiv.updateTranslateDiv(`${i18next.t('transingTip.basic', { ns: 'translator', server: servername })}`, is_renderLaTeX);
  7966. } else if (OJBetter.deepl.config.type == 'api') {
  7967. translateDiv.updateTranslateDiv(`${i18next.t('transingTip.deeplApi', { ns: 'translator', deepl_configName: OJBetter.deepl.config.name })}`, is_renderLaTeX);
  7968. if (OJBetter.deepl.config.apiGenre == 'deeplx') {
  7969. rawData = await translate_deeplx(text);
  7970. } else {
  7971. if (OJBetter.deepl.enableEmphasisProtection) text = convertBoldMarkdownToHTML(text);
  7972. if (OJBetter.deepl.enableLinkProtection) text = convertLinksMarkdownToHTML(text);
  7973. if (OJBetter.deepl.config.apiGenre == 'api-free') {
  7974. rawData = await translate_deepl_api_free(text);
  7975. } else if (OJBetter.deepl.config.apiGenre == 'api-pro') {
  7976. rawData = await translate_deepl_api_pro(text);
  7977. }
  7978. if (OJBetter.deepl.enableEmphasisProtection) rawData.text = convertBoldHTMLToMarkdown(rawData.text);
  7979. if (OJBetter.deepl.enableLinkProtection) rawData.text = convertLinksHTMLToMarkdown(rawData.text);
  7980. }
  7981. }
  7982. } else if (translation == "iflyrec") {
  7983. translateDiv.updateTranslateDiv(`${i18next.t('transingTip.basic', { ns: 'translator', server: servername })}`, is_renderLaTeX);
  7984. rawData = await translate_iflyrec(text);
  7985. } else if (translation == "youdao") {
  7986. translateDiv.updateTranslateDiv(`${i18next.t('transingTip.basic', { ns: 'translator', server: servername })}`, is_renderLaTeX);
  7987. rawData = await translate_youdao_mobile(text);
  7988. } else if (translation == "google") {
  7989. translateDiv.updateTranslateDiv(`${i18next.t('transingTip.basic', { ns: 'translator', server: servername })}`, is_renderLaTeX);
  7990. rawData = await translate_gg(text);
  7991. } else if (translation == "caiyun") {
  7992. translateDiv.updateTranslateDiv(`${i18next.t('transingTip.basic', { ns: 'translator', server: servername })}`, is_renderLaTeX);
  7993. await translate_caiyun_startup();
  7994. rawData = await translate_caiyun(text);
  7995. } else if (translation == "openai") {
  7996. translateDiv.updateTranslateDiv(`${i18next.t('transingTip.openai', { ns: 'translator', openai_name: OJBetter.chatgpt.config.name })}${!OJBetter.chatgpt.isStream
  7997. ? i18next.t('transingTip.openai_isStream', { ns: 'translator' }) : ""}`,
  7998. is_renderLaTeX);
  7999. if (OJBetter.chatgpt.isStream) {
  8000. // 流式传输
  8001. rawData = await translate_openai_stream(text, translateDiv);
  8002. } else {
  8003. // 普通模式
  8004. rawData = await translate_openai(text);
  8005. }
  8006. }
  8007. translatedText = rawData.text;
  8008. if (!rawData.done) {
  8009. status = "error";
  8010. }
  8011. } catch (e) {
  8012. status = "error";
  8013. rawData.message = i18next.t('error.unexpected', { ns: 'translator' });
  8014. console.warn(e);
  8015. }
  8016. return rawData;
  8017. }
  8018. rawData = await translate(realTranlate);
  8019.  
  8020. if (status == "error") {
  8021. translateDiv.updateTranslateDiv(rawData.message);
  8022. return {
  8023. status: status,
  8024. translateDiv: translateDiv,
  8025. rawData: rawData
  8026. };
  8027. }
  8028.  
  8029. // 还原latex公式
  8030. translatedText = recoverLatex(translatedText);
  8031.  
  8032. // 注册(不可用)结果复制按钮
  8033. if (!OJBetter.typeOfPage.is_oldLatex && !OJBetter.typeOfPage.is_acmsguru) {
  8034. translateDiv.registerCopyButtonEvent(translatedText);
  8035. } else {
  8036. translateDiv.disableCopyButton();
  8037. }
  8038.  
  8039. // 翻译结果格式化
  8040. translatedText = formatText(translatedText);
  8041.  
  8042. // 保存翻译结果
  8043. if ((OJBetter.typeOfPage.is_problem || OJBetter.typeOfPage.is_completeProblemset) && OJBetter.translation.memory.enabled) {
  8044. OJBetter.translation.memory.ttTree.refreshNode(".ttypography"); // 刷新当前页面.ttypography元素的结构树实例
  8045. OJBetter.translation.memory.ttTree.addTransResultMap(id, translatedText);
  8046. updateTransDBData(OJBetter.translation.memory.ttTree.getNodeDate(), OJBetter.translation.memory.ttTree.getTransResultMap()); // 更新翻译结果到transDB
  8047. }
  8048.  
  8049. // 翻译结果面板更新
  8050. translateDiv.updateTranslateDiv(translatedText, !(OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru));
  8051.  
  8052. return {
  8053. status: status,
  8054. translateDiv: translateDiv,
  8055. rawData: rawData
  8056. };
  8057. }
  8058.  
  8059. //弹窗翻译
  8060. function alertZh() {
  8061. // var _alert = window.alert;
  8062. // window.alert = async function (msg) {
  8063. // _alert(msg + "\n=========翻译=========\n" + await translate_deepl(msg));
  8064. // return true;
  8065. // }
  8066. };
  8067.  
  8068. /**
  8069. * 折叠块展开
  8070. */
  8071. function ExpandFoldingblocks() {
  8072. $('.spoiler').addClass('spoiler-open');
  8073. $('.spoiler-content').attr('style', '');
  8074. };
  8075.  
  8076. /**
  8077. * 折叠块渲染优化
  8078. */
  8079. function RenderPerfOpt() {
  8080. GM_addStyle(`
  8081. .spoiler-content {
  8082. contain: layout style;
  8083. }
  8084. `);
  8085. }
  8086.  
  8087. /**
  8088. * 评论区分页
  8089. */
  8090. function CommentPagination() {
  8091. GM_addStyle(`
  8092. .comments > .comment {
  8093. display: none;
  8094. }
  8095. #next-page-btn, #prev-page-btn {
  8096. display: none;
  8097. }
  8098. #jump-input, #items-per-page{
  8099. height: 22px;
  8100. border: 1px solid #dcdfe6;
  8101. border-radius: 0.3rem;
  8102. }
  8103. #jump-input:focus-visible{
  8104. border-style: solid;
  8105. border-color: #3f51b5;
  8106. outline: none;
  8107. }
  8108. `);
  8109. $('.comments').after(`
  8110. <div id="pagBar" style="display: flex; align-items: center; justify-content: center; color: #606266;">
  8111. <label for="items-per-page">${i18next.t('perpage', { ns: 'comments' })}</label>
  8112. <select id="items-per-page" style="margin-right: 15px;">
  8113. <option value="5">5</option>
  8114. <option value="10">10</option>
  8115. <option value="20">20</option>
  8116. </select>
  8117. <div class="paging" style="margin-right: 15px;">
  8118. <span id="current-page">1</span> / <span id="total-pages"></span>
  8119. </div>
  8120. <input type="text" id="jump-input" placeholder="${i18next.t('jumpTo', { ns: 'comments' })}">
  8121. <button type="button" id="jump-btn" class="ojb_btn">${i18next.t('jump', { ns: 'comments' })}</button>
  8122. <button id="prev-page-btn" class="ojb_btn">${i18next.t('prev', { ns: 'comments' })}</button>
  8123. <button id="next-page-btn" class="ojb_btn">${i18next.t('next', { ns: 'comments' })}</button>
  8124. </div>
  8125. `);
  8126.  
  8127. let batchSize = 5;
  8128. let elements = $(".comments > .comment").slice(0, -1);
  8129. let start = 0;
  8130. let end = batchSize;
  8131. let currentPage = 1;
  8132. let displayedIndexes = []; // 存储已显示元素的索引
  8133.  
  8134. function showBatch(start, end) {
  8135. // 隐藏上一页
  8136. for (var i = 0; i < displayedIndexes.length; i++) {
  8137. elements.eq(displayedIndexes[i]).hide();
  8138. }
  8139.  
  8140. displayedIndexes = [];
  8141.  
  8142. // 显示当前页
  8143. elements.slice(start, end).each(function (index) {
  8144. $(this).show();
  8145. displayedIndexes.push(start + index);
  8146. });
  8147.  
  8148. // 更新页码和翻页按钮
  8149. $("#current-page").text(currentPage);
  8150. $("#total-pages").text(Math.ceil(elements.length / batchSize));
  8151.  
  8152. if (currentPage === 1) $("#prev-page-btn").hide();
  8153. else $("#prev-page-btn").show();
  8154.  
  8155. if (end >= elements.length) $("#next-page-btn").hide();
  8156. else $("#next-page-btn").show();
  8157. }
  8158.  
  8159. // 初始化
  8160. var commentID = null;
  8161. var pageURL = window.location.href;
  8162. if (pageURL.includes("#comment-")) {
  8163. // 带评论区锚点的链接
  8164. var startIndex = pageURL.lastIndexOf("#comment-") + 9;
  8165. commentID = pageURL.substring(startIndex);
  8166. var indexInComments = null;
  8167. $(".comments > .comment").each(function (index) {
  8168. $(this).find(".comment-table").each(function () {
  8169. var tableCommentID = $(this).attr("commentid");
  8170. if (tableCommentID === commentID) {
  8171. indexInComments = index;
  8172. return false;
  8173. }
  8174. });
  8175. });
  8176. let page = Math.ceil((indexInComments + 1) / batchSize);
  8177. currentPage = !page ? 1 : page;
  8178. showBatch((currentPage - 1) * batchSize, currentPage * batchSize);
  8179. setTimeout(function () {
  8180. window.location.href = pageURL;
  8181. }, 1000);
  8182. } else {
  8183. showBatch(0, batchSize);
  8184. }
  8185.  
  8186. $("#prev-page-btn").on("click", function () {
  8187. var itemsPerPage = parseInt($("#items-per-page").val());
  8188. start = (currentPage - 2) * itemsPerPage;
  8189. end = (currentPage - 1) * itemsPerPage;
  8190. currentPage--;
  8191. showBatch(start, end);
  8192. });
  8193.  
  8194. $("#next-page-btn").on("click", function () {
  8195. var itemsPerPage = parseInt($("#items-per-page").val());
  8196. start = currentPage * itemsPerPage;
  8197. end = (currentPage + 1) * itemsPerPage;
  8198. currentPage++;
  8199. showBatch(start, end);
  8200. });
  8201.  
  8202. $("#jump-btn").on("click", function () {
  8203. var inputPage = parseInt($("#jump-input").val());
  8204.  
  8205. if (inputPage >= 1 && inputPage <= Math.ceil(elements.length / parseInt($("#items-per-page").val()))) {
  8206. var itemsPerPage = parseInt($("#items-per-page").val());
  8207. start = (inputPage - 1) * itemsPerPage;
  8208. end = inputPage * itemsPerPage;
  8209. currentPage = inputPage; // 更新当前页码
  8210. showBatch(start, end);
  8211. }
  8212. });
  8213.  
  8214. $("#items-per-page").on("change", function () {
  8215. batchSize = parseInt($(this).val());
  8216. let page = Math.ceil(end / batchSize);
  8217. currentPage = !page ? 1 : page;
  8218. let maxPage = Math.ceil(elements.length / batchSize);
  8219. if (currentPage > maxPage) currentPage = maxPage;
  8220. showBatch((currentPage - 1) * batchSize, currentPage * batchSize);
  8221. });
  8222. }
  8223.  
  8224. /**
  8225. * 题目页相关链接栏
  8226. */
  8227. class ProblemPageLinkbar {
  8228. constructor() {
  8229. this.containerElement = this.createToolbar();
  8230. this.commandInvoker = new CommandInvoker();
  8231. }
  8232.  
  8233. /**
  8234. * 创建工具栏
  8235. */
  8236. createToolbar() {
  8237. const toolbarElement = $("<div>").attr("id", "problemToolbar").insertBefore($(".problemindexholder"));
  8238. return new DOMContainer(toolbarElement);
  8239. }
  8240.  
  8241. /**
  8242. * 添加按钮
  8243. * @param {string} id 按钮id
  8244. * @param {string} url 按钮链接
  8245. * @param {string} text 按钮文字
  8246. * @param {JQueryObject} icon 按钮图标
  8247. * @param {string} iconHeight 图标高度
  8248. * @returns {object} 按钮对象
  8249. */
  8250. addLinkButton(id, url, text, icon = $('<div>'), iconHeight = "22px") {
  8251. const linkElement = $("<a>")
  8252. .attr("href", url)
  8253. .attr("target", "_blank")
  8254. .addClass("ojb_btn")
  8255. .attr("id", id);
  8256.  
  8257. linkElement.append(icon);
  8258. icon.css("height", iconHeight);
  8259.  
  8260. const textSpan = $("<span>").html(text);
  8261. linkElement.append(textSpan);
  8262.  
  8263. this.commandInvoker.execute(new AddElementCommand(this.containerElement, linkElement));
  8264. return {
  8265. element: linkElement,
  8266. text: textSpan,
  8267. icon: icon
  8268. };
  8269. }
  8270.  
  8271. /**
  8272. * 更新链接
  8273. * @param {object} button 按钮对象
  8274. * @param {string} url 按钮链接
  8275. */
  8276. updateUrl(button, url) {
  8277. button.element.attr("href", url);
  8278. }
  8279.  
  8280. /**
  8281. * 更新文字
  8282. * @param {object} button 按钮对象
  8283. * @param {string} text 按钮文字
  8284. */
  8285. updateText(button, text) {
  8286. button.text.html(text);
  8287. }
  8288.  
  8289. /**
  8290. * 设置文字为粗体
  8291. * @param {object} button 按钮对象
  8292. */
  8293. setBold(button) {
  8294. button.text.css("font-weight", "bold");
  8295. }
  8296.  
  8297. /**
  8298. * 更新图标
  8299. * @param {object} button 按钮对象
  8300. * @param {JQueryObject} icon 按钮图标
  8301. * @param {string} iconHeight 图标高度
  8302. */
  8303. updateIcon(button, icon, iconHeight = "16px") {
  8304. button.icon.remove();
  8305. button.text.prepend(icon);
  8306. icon.css("height", iconHeight);
  8307. button.icon = icon;
  8308. }
  8309.  
  8310. /**
  8311. * 添加类
  8312. * @param {object} button 按钮对象
  8313. * @param {string} className 类名
  8314. */
  8315. addClass(button, className) {
  8316. button.element.addClass(className);
  8317. }
  8318.  
  8319. /**
  8320. * 禁用链接按钮
  8321. * @param {object} button 按钮对象
  8322. */
  8323. disableButton(button) {
  8324. button.element.addClass("disabled");
  8325. }
  8326.  
  8327. /**
  8328. * 启用链接按钮
  8329. * @param {object} button 按钮对象
  8330. */
  8331. enableButton(button) {
  8332. button.element.removeClass("disabled");
  8333. }
  8334. }
  8335.  
  8336. /**
  8337. * 获取题目的id
  8338. * @param {String} url 题目的链接
  8339. * @returns 题目的id,形如2000A
  8340. */
  8341. function getProblemId(url) {
  8342. const regex = url.includes('/contest/')
  8343. ? /\/contest\/(\d+)\/problem\/([A-Za-z\d]+)/
  8344. : /\/problemset\/problem\/(\d+)\/([A-Za-z\d]+)/;
  8345. const matchResult = url.match(regex);
  8346. return matchResult && matchResult.length >= 3 ? `${matchResult[1]}${matchResult[2]}` : '';
  8347. };
  8348.  
  8349. /**
  8350. * 跳转到洛谷
  8351. * @param {ProblemPageLinkbar} problemToolbar
  8352. */
  8353. async function CF2luogu(problemToolbar) {
  8354. const url = window.location.href;
  8355. const problemId = getProblemId(url);
  8356. const luoguButton = problemToolbar.addLinkButton(
  8357. "luoguButton",
  8358. "https://www.luogu.com.cn/",
  8359. i18next.t('state.loading', { ns: 'button' }),
  8360. $("<img>").attr("src", "https://cdn.luogu.com.cn/fe/logo.png")
  8361. );
  8362. const checkLinkExistence = (url) => {
  8363. return new Promise((resolve, reject) => {
  8364. GM.xmlHttpRequest({
  8365. method: "GET",
  8366. url,
  8367. headers: { "Range": "bytes=0-9999" }, // 获取前10KB数据
  8368. onload(response) {
  8369. if (response.responseText.match(/题目未找到/g)) {
  8370. resolve(false);
  8371. } else {
  8372. resolve(true);
  8373. }
  8374. },
  8375. onerror(error) {
  8376. reject(error);
  8377. }
  8378. });
  8379. });
  8380. };
  8381.  
  8382. const LuoguUrl = `https://www.luogu.com.cn/problem/CF${problemId}`;
  8383. const result = await checkLinkExistence(LuoguUrl);
  8384. if (problemId && result) {
  8385. problemToolbar.updateText(luoguButton, "");
  8386. problemToolbar.updateUrl(luoguButton, LuoguUrl);
  8387. } else {
  8388. problemToolbar.updateText(luoguButton, i18next.t('state.404', { ns: 'button' }));
  8389. problemToolbar.disableButton(luoguButton);
  8390. }
  8391. }
  8392.  
  8393. // RatingClass
  8394. const ratingClassMap = {
  8395. NaN: "rating_by_clist_colorNaN",
  8396. 0: "rating_by_clist_color0",
  8397. 1200: "rating_by_clist_color1",
  8398. 1400: "rating_by_clist_color2",
  8399. 1600: "rating_by_clist_color3",
  8400. 1900: "rating_by_clist_color4",
  8401. 2100: "rating_by_clist_color5",
  8402. 2300: "rating_by_clist_color6",
  8403. 2400: "rating_by_clist_color7",
  8404. 2600: "rating_by_clist_color8",
  8405. 3000: "rating_by_clist_color9"
  8406. };
  8407. const cssMap = {
  8408. "rating_by_clist_colorNaN": "#cccccc",
  8409. "rating_by_clist_color0": "#808080",
  8410. "rating_by_clist_color1": "#73e473",
  8411. "rating_by_clist_color2": "#77ddbb",
  8412. "rating_by_clist_color3": "#aaaaff",
  8413. "rating_by_clist_color4": "#ff88ff",
  8414. "rating_by_clist_color5": "#ffcc88",
  8415. "rating_by_clist_color6": "#ffbb55",
  8416. "rating_by_clist_color7": "#ff7777",
  8417. "rating_by_clist_color8": "#ff3333",
  8418. "rating_by_clist_color9": "#aa0000"
  8419. };
  8420.  
  8421. /**
  8422. * clist 访问有效性检查
  8423. * @param {boolean} onlyCookie 是否只检查Cookie
  8424. * @returns {Promise<boolean>} 是否有效
  8425. */
  8426. async function validateClistConnection(onlyCookie = false) {
  8427. const clistApiUrl = "https://clist.by:443/api/v4/contest/?limit=1&resource_id=1";
  8428. const requestOptions = {
  8429. method: "GET",
  8430. url: clistApiUrl,
  8431. timeout: 5000,
  8432. };
  8433.  
  8434. // 尝试发送请求
  8435. async function tryRequest(options) {
  8436. try {
  8437. const response = await OJB_GMRequest(options);
  8438. if (response.status === 200) {
  8439. return { ok: true };
  8440. } else if (response.status === 401) {
  8441. throw new Error('unauthorized');
  8442. } else if (response.status === 404) {
  8443. throw new Error('not_found');
  8444. } else {
  8445. throw new Error('other_error');
  8446. }
  8447. } catch (error) {
  8448. console.warn(`Error accessing clist.by: ${error.message}`);
  8449. return { ok: false, error: error.message };
  8450. }
  8451. }
  8452.  
  8453. // 尝试携带Key发送请求
  8454. let result = await tryRequest(requestOptions);
  8455. if (!onlyCookie && !result.ok) {
  8456. requestOptions.headers = { "Authorization": OJBetter.clist.authorization };
  8457. result = await tryRequest(requestOptions);
  8458. }
  8459.  
  8460. // 根据结果显示错误信息
  8461. if (!result.ok) {
  8462. let errorType = result.error;
  8463. const loadingMessage = new LoadingMessage();
  8464. let state;
  8465. if (errorType === 'not_found') {
  8466. state = i18next.t('error.clist.404', { ns: 'alert' });
  8467. } else if (errorType === 'unauthorized') {
  8468. state = i18next.t('error.clist.cookie', { ns: 'alert' });
  8469. } else {
  8470. state = i18next.t('error.clist.other', { ns: 'alert' });
  8471. }
  8472. loadingMessage.updateStatus(`${OJBetter.state.name} —— ${state}`, 'error');
  8473. }
  8474. return result.ok;
  8475. }
  8476.  
  8477. /**
  8478. * 创建Rating相关css
  8479. * @param {boolean} [hasBorder=true] 是否有边框
  8480. */
  8481. function creatRatingCss(hasBorder = true) {
  8482. const defaultBorderColor = '#dcdfe6';
  8483. let dynamicCss = "";
  8484. let hoverSelector = OJBetter.clist.ratingHidden ? ":hover" : "";
  8485. for (let cssClass in cssMap) {
  8486. dynamicCss += `a.${cssClass}${hoverSelector}, a.${cssClass}${hoverSelector}:link {\n`;
  8487. let borderColor = hasBorder ? cssMap[cssClass] : defaultBorderColor;
  8488. dynamicCss += ` color: ${cssMap[cssClass]} ${OJBetter.clist.ratingHidden ? "!important" : ""};\n`;
  8489. dynamicCss += ` border: 1px solid ${borderColor} ${OJBetter.clist.ratingHidden ? "!important" : ""};\n`;
  8490. dynamicCss += `}\n`;
  8491. }
  8492. GM_addStyle(dynamicCss);
  8493. if (OJBetter.clist.ratingHidden) {
  8494. GM_addStyle(`
  8495. #clistButton {
  8496. color: #ffffff00;
  8497. }
  8498. `);
  8499. }
  8500. }
  8501.  
  8502. /**
  8503. * 模拟clist网页访问获取rating
  8504. * @param {string} problem 题目名称
  8505. * @param {string} problem_url 题目链接
  8506. * @param {string} contest 比赛名称
  8507. * @returns {Promise<{rating: number, problem: string}>} 题目难度
  8508. */
  8509. async function getRating(problem, problem_url, contest = null) {
  8510. problem = problem.replace(/\([\s\S]*?\)/g, '').replace(/^\s+|\s+$/g, '');
  8511. return new Promise((resolve, reject) => {
  8512. const queryString = `search=${problem}&resource=1`;
  8513. GM_xmlhttpRequest({
  8514. method: 'GET',
  8515. url: `https://clist.by/problems/?${queryString}`,
  8516. responseType: 'html',
  8517. onload: function (response) {
  8518. const html = response.responseText;
  8519. var cleanedHtml = html.replace(/src=(.|\s)*?"/g, '');
  8520. const trs = $(cleanedHtml).find('table').find('tbody tr');
  8521. let records = [];
  8522. trs.each(function (index) {
  8523. const rating = $(this).find('.problem-rating-column').text().trim();
  8524. const link = $(this).find('.problem-name-column').find('a').eq(1).attr('href');
  8525. var contests = [];
  8526. $(this).find('.problem-name-column').find('.pull-right a[title], .pull-right span[title]').each(function () {
  8527. var value = $(this).attr('title');
  8528. if (value) {
  8529. value = value.replace(/<br\/?><\/a>/g, '');
  8530. contests.push(value);
  8531. }
  8532. });
  8533. records.push({ rating: rating, link: link, contests: contests });
  8534. });
  8535. for (let record of records) {
  8536. let link;
  8537. if (typeof record.link !== 'undefined') link = record.link.replace(/http:/g, 'https:');
  8538. if (link == problem_url || link == problem_url + '/') {
  8539. resolve({
  8540. rating: parseInt(record.rating),
  8541. problem: problem
  8542. });
  8543. return;
  8544. } else if (contest != null) {
  8545. for (let item of record.contests) {
  8546. if (contest == item) {
  8547. resolve({
  8548. rating: parseInt(record.rating),
  8549. problem: problem
  8550. });
  8551. return;
  8552. }
  8553. }
  8554. }
  8555. }
  8556. reject(`No data found for the question of ${problem} .`);
  8557. },
  8558. onerror: function (response) {
  8559. reject(`An error occurred while handling the ${problem} problem.`);
  8560. }
  8561. });
  8562. });
  8563. }
  8564.  
  8565. /**
  8566. * 从clist API获取题目的rating
  8567. * @param {string} problem 题目名
  8568. * @param {string} problem_url 题目链接
  8569. * @returns {Promise<number>} 题目rating
  8570. */
  8571. async function getRatingFromApi_problem(problem, problem_url) {
  8572. return new Promise((resolve, reject) => {
  8573. GM_xmlhttpRequest({
  8574. method: "GET",
  8575. url: `https://clist.by:443/api/v4/problem/?name=${problem}&resource__regex=codeforces.com`,
  8576. headers: {
  8577. "Authorization": OJBetter.clist.authorization
  8578. },
  8579. onload: function (response) {
  8580. if (!response) reject('An unknown error occurred!');
  8581. let data = JSON.parse(response.responseText);
  8582. let objects = data.objects;
  8583. let problemsMap = new Map();
  8584. if (objects.length > 0) {
  8585. for (let i = 0; i < objects.length; i++) {
  8586. let problem = objects[i];
  8587. problemsMap.set(problem.url, problem.rating ? problem.rating : NaN);
  8588. }
  8589. resolve(problemsMap.get(problem_url));
  8590. }
  8591. }
  8592. });
  8593. });
  8594. }
  8595.  
  8596. /**
  8597. * 从clist API获取比赛的题目rating
  8598. * @param {string} event 比赛名
  8599. * @returns {Promise<Map<string, number>>} 题目rating
  8600. */
  8601. async function getRatingFromApi_contest(event) {
  8602. const options = {
  8603. method: "GET",
  8604. url: `https://clist.by:443/api/v4/contest/?limit=1&with_problems=true&event=${event}`,
  8605. headers: {
  8606. "Authorization": OJBetter.clist.authorization
  8607. }
  8608. }
  8609. let response = await OJB_GMRequest(options);
  8610. let data = JSON.parse(response.responseText);
  8611. let objects = data.objects;
  8612. let problemsMap = new Map();
  8613. if (objects.length > 0) {
  8614. var problems = objects[0].problems;
  8615. for (var i = 0; i < problems.length; i++) {
  8616. var problem = problems[i];
  8617. problemsMap.set(problem.url, problem.rating ? problem.rating : NaN);
  8618. }
  8619. }
  8620. return problemsMap;
  8621. }
  8622.  
  8623. /**
  8624. * 根据rating获取对应的颜色class名
  8625. * @param {number} rating 题目rating
  8626. * @returns {string} 颜色class名
  8627. */
  8628. function getClassNameByRating(rating) {
  8629. let className = "rating_by_clist_color9";
  8630. if (Number.isNaN(rating)) {
  8631. className = "rating_by_clist_colorNaN";
  8632. } else {
  8633. let keys = Object.keys(ratingClassMap);
  8634. for (let i = 0; i < keys.length; i++) {
  8635. if (rating < keys[i]) {
  8636. className = ratingClassMap[keys[i - 1]];
  8637. break;
  8638. }
  8639. }
  8640. }
  8641. return className;
  8642. }
  8643.  
  8644. /**
  8645. * problem页显示Rating
  8646. * @param {ProblemPageLinkbar} problemToolbar
  8647. * @returns {Promise<void>}
  8648. */
  8649. async function showRatingByClist_problem(problemToolbar) {
  8650. // 题目名
  8651. let problem = $('.header .title').eq(0).text().replace(/[\s\S]*?. /, '');
  8652. if (OJBetter.typeOfPage.is_acmsguru) problem = $('h4').eq(0).text().replace(/[\s\S]*?. /, '');
  8653.  
  8654. // 创建Rating按钮元素
  8655. creatRatingCss(false);
  8656. // TODO
  8657. const clistButton = problemToolbar.addLinkButton(
  8658. 'clistButton',
  8659. `https://clist.by/problems/?search=${problem}&resource=1`,
  8660. i18next.t('state.wait', { ns: 'button' }),
  8661. $("<img>").attr("src", "https://clist.by/static/img/logo-48.png"),
  8662. "15px"
  8663. );
  8664.  
  8665. // 检测clist连接
  8666. if (!await validateClistConnection()) {
  8667. problemToolbar.updateText(clistButton, i18next.t('state.netError', { ns: 'button' }));
  8668. return;
  8669. }
  8670.  
  8671. // 题目链接
  8672. let problem_url = window.location.href;
  8673. if (problem_url.includes('/contest/')) {
  8674. problem_url = problem_url.replace(/\/contest\/(\d+)\/problem\/(\w+)[^\w]*/, '/contest/$1/problem/$2');
  8675. } else {
  8676. problem_url = problem_url.replace(/\/problemset\/problem\/(\d+)\/(\w+)/, '/contest/$1/problem/$2');
  8677. }
  8678. if (OJBetter.typeOfPage.is_mSite) problem_url = problem_url.replace(/\/\/(\w+).codeforces.com/, '//codeforces.com'); // 轻量站
  8679.  
  8680. // 比赛名
  8681. // let contest = $('#sidebar').children().first().find('.rtable th').first().text();
  8682.  
  8683. // rating
  8684. problemToolbar.updateText(clistButton, i18next.t('state.loading', { ns: 'button' }));
  8685. let rating = await getRatingFromApi_problem(problem, problem_url);
  8686. if (rating) {
  8687. let className = getClassNameByRating(rating);
  8688. problemToolbar.updateText(clistButton, rating);
  8689. problemToolbar.setBold(clistButton);
  8690. problemToolbar.addClass(clistButton, className);
  8691. } else {
  8692. problemToolbar.updateText(clistButton, i18next.t('state.404', { ns: 'button' }));
  8693. problemToolbar.disableButton(clistButton);
  8694. }
  8695. }
  8696.  
  8697. /**
  8698. * contest页显示Rating
  8699. * @returns {Promise<void>}
  8700. */
  8701. async function showRatingByClist_contest() {
  8702. // 创建Rating显示框
  8703. creatRatingCss();
  8704. let ratingBadges = {};
  8705. $('.datatable .id.left').each(function () {
  8706. let href = 'https://codeforces.com' + $(this).find('a').attr('href');
  8707. let badge = $(`<a id="clistButton" class="ratingBadge">${i18next.t('state.wait', { ns: 'button' })}</a>`);
  8708. $(this).find('a').after(badge);
  8709. ratingBadges[href] = badge;
  8710. });
  8711.  
  8712. // 检测clist连接
  8713. if (!await validateClistConnection()) {
  8714. for (let href in ratingBadges) {
  8715. ratingBadges[href].text('error').addClass('ratingBadge_error');
  8716. }
  8717. return;
  8718. }
  8719.  
  8720. // 显示loading
  8721. for (let href in ratingBadges) {
  8722. ratingBadges[href].text(i18next.t('state.loading', { ns: 'button' })).addClass('ratingBadge_loading');
  8723. }
  8724.  
  8725. // 获取Rating
  8726. let event = encodeURIComponent($('#sidebar').children().first().find('.rtable th').first().text());
  8727. let problemsMap = await getRatingFromApi_contest(event);
  8728.  
  8729. // 填充数据
  8730. for (let href in ratingBadges) {
  8731. if (problemsMap.has(href)) {
  8732. let rating = problemsMap.get(href);
  8733. let className = getClassNameByRating(rating);
  8734. ratingBadges[href].text(rating).addClass(className);
  8735. } else {
  8736. ratingBadges[href].text(i18next.t('state.404', { ns: 'button' })).addClass('ratingBadge_no');
  8737. }
  8738. }
  8739. }
  8740.  
  8741. /**
  8742. * problemset页显示Rating
  8743. * @returns {Promise<void>}
  8744. */
  8745. async function showRatingByClist_problemset() {
  8746. creatRatingCss();
  8747. let ratingBadges = [];
  8748. const $problems = $('.problems');
  8749. const $trs = $problems.find('tbody tr:gt(0)');
  8750.  
  8751. // 先创建Rating显示框,并将关系存进数组ratingBadges
  8752. for (let i = 0; i < $trs.length; i++) {
  8753. const $tds = $($trs[i]).find('td');
  8754. let problem = $($tds[0]).text();
  8755. let problem_url = $($tds[0]).find('a').attr('href');
  8756. problem_url = problem_url.replace(/^\/problemset\/problem\/(\d+)\/(\w+)/, 'https://codeforces.com/contest/$1/problem/$2');
  8757.  
  8758. const ratingBadge = $(`<a id="clistButton" class="ratingBadge"></a>`);
  8759. const rating = $(`<span class="rating">${i18next.t('state.wait', { ns: 'button' })}</span>`);
  8760. ratingBadge.append(rating);
  8761. $($tds[0]).find('a').after(ratingBadge);
  8762. ratingBadges.push({ ratingBadge, rating, problem, problem_url });
  8763. }
  8764.  
  8765. // 检测clist连接
  8766. if (!await validateClistConnection()) {
  8767. for (let i = 0; i < rating.length; i++) {
  8768. ratingBadges[i].rating.text(i18next.t('state.netError', { ns: 'button' }));
  8769. }
  8770. return;
  8771. }
  8772.  
  8773. // 每次只获取3个rating
  8774. for (let i = 0; i < ratingBadges.length; i += 3) {
  8775. const promises = [];
  8776. const endIndex = Math.min(i + 3, ratingBadges.length);
  8777.  
  8778. for (let j = i; j < endIndex; j++) {
  8779. const ratingBadge = ratingBadges[j];
  8780. // 显示请求中
  8781. ratingBadge.rating.text(i18next.t('state.loading', { ns: 'button' }));
  8782. promises.push(getRating(ratingBadge.problem, ratingBadge.problem_url).catch(error => console.warn(error)));
  8783. }
  8784.  
  8785. const results = await Promise.all(promises);
  8786.  
  8787. for (let j = i; j < endIndex; j++) {
  8788. const result = results[j - i];
  8789. const ratingBadge = ratingBadges[j];
  8790. if (result) {
  8791. let className = getClassNameByRating(result.rating);
  8792. ratingBadge.ratingBadge.addClass(className);
  8793. ratingBadge.rating.text(result.rating);
  8794. } else {
  8795. ratingBadge.rating.text(i18next.t('state.404', { ns: 'button' }));
  8796. }
  8797. }
  8798. }
  8799. }
  8800.  
  8801. /**
  8802. * cf赛制榜单重新着色
  8803. */
  8804. async function recolorStandings() {
  8805. function getColorValue(value) {
  8806. value = Math.max(0, Math.min(1, value));
  8807.  
  8808. const scale = chroma.scale(['#b71c1c', '#ff9800', '#ffc107', '#00aa00']).mode('lch').domain([0, 0.45, 0.7, 1]);
  8809. return scale(value).hex();
  8810. }
  8811. var maxScores = $('.standings tr:first th:nth-child(n+5)')
  8812. .map(function () {
  8813. return $(this).find('span').text();
  8814. })
  8815. .get();
  8816. $('.standings tr:not(:first):not(:last)').each(function () {
  8817. var thElements = $(this).find('td:nth-child(n+5)');
  8818. thElements.each(function (index) {
  8819. var spanElement = $(this).find('span:first');
  8820. var value = parseInt(spanElement.text());
  8821. if (value <= 0 || /[a-zA-Z]/.test(maxScores[index])) return;
  8822. var colorValue = getColorValue(value / maxScores[index]);
  8823. spanElement.css('color', colorValue);
  8824. });
  8825. });
  8826. }
  8827.  
  8828. /**
  8829. * 存放编辑器语言select的值与Monaco语言对应关系的map.
  8830. * @type {Object.<string, string>}
  8831. */
  8832. const value_monacoLanguageMap = {
  8833. "4": "pascal", "6": "php", "7": "python", "9": "csharp", "13": "perl", "20": "scala", "31": "python",
  8834. "32": "go", "34": "javascript", "36": "java", "40": "python", "41": "python", "43": "cpp",
  8835. "50": "cpp", "51": "pascal", "52": "cpp", "54": "cpp", "55": "javascript", "59": "cpp", "60": "java",
  8836. "61": "cpp", "65": "csharp", "67": "ruby", "70": "python", "73": "cpp", "74": "java", "75": "rust",
  8837. "77": "kotlin", "79": "csharp", "80": "cpp", "83": "kotlin", "87": "java"
  8838. };
  8839.  
  8840. /**
  8841. * 更新代码提交页的HTML
  8842. * @param {string} submitUrl
  8843. * @param {string} cacheKey
  8844. * @returns {Promise<jQuery>}
  8845. */
  8846. async function CloneOriginalHTML(submitUrl, cacheKey) {
  8847. return new Promise((resolve, reject) => {
  8848. GM_xmlhttpRequest({
  8849. method: 'GET',
  8850. url: submitUrl,
  8851. responseType: 'html',
  8852. onload: function (response) {
  8853. const html = response.responseText;
  8854. const cloneHTML = $(html);
  8855. localStorage.setItem(cacheKey, html);
  8856. resolve(cloneHTML);
  8857. },
  8858. onerror: function (response) {
  8859. reject('A network error occurred while retrieving the HTML for the code submission page.');
  8860. }
  8861. });
  8862. });
  8863. }
  8864.  
  8865. /**
  8866. * 获取代码提交页的HTML元素
  8867. * @param {string} submitUrl
  8868. * @returns {Promise<jQuery>}
  8869. */
  8870. async function getSubmitHTML(submitUrl) {
  8871. const cacheKey = 'OJBetter_CloneOriginalHTML';
  8872. const cookieKey = 'OJBetter_CloneOriginalHTML_time';
  8873. if (OJB_getCookie(cookieKey) === '1') {
  8874. // 存在缓存
  8875. CloneOriginalHTML(submitUrl, cacheKey);
  8876. // 校验
  8877. let cloneHTML = $(localStorage.getItem(cacheKey));
  8878. if (cloneHTML.find('form.submit-form').length > 0) {
  8879. return cloneHTML;
  8880. } else {
  8881. // 存在错误,更新缓存
  8882. console.warn(`Cache error detected!\nattempting to update, cache destination submitUrl:\n${submitUrl}`);
  8883. return await CloneOriginalHTML(submitUrl, cacheKey);
  8884. }
  8885.  
  8886. } else {
  8887. // 没有缓存,更新
  8888. document.cookie = `${cookieKey}=1; path=/`;
  8889. return await CloneOriginalHTML(submitUrl, cacheKey);
  8890. }
  8891. }
  8892.  
  8893. // 代码自动保存
  8894. async function saveCode(url, code) {
  8895. try {
  8896. await OJBetter.common.database.editorCode.put({ url, code });
  8897. return 'Code saved successfully';
  8898. } catch (error) {
  8899. throw new Error('Failed to save code');
  8900. }
  8901. }
  8902.  
  8903. async function getCode(url) {
  8904. try {
  8905. const result = await OJBetter.common.database.editorCode.get(url);
  8906. return result ? result.code : null;
  8907. } catch (error) {
  8908. throw new Error('Failed to get code');
  8909. }
  8910. }
  8911.  
  8912. // 创建代码编辑调试表单元素
  8913. async function createCodeEditorForm(submitUrl, cloneHTML) {
  8914. // 表单
  8915. let formDiv = $('<form method="post" id="OJBetter_SubmitForm" class="input-output-copier"></form>');
  8916. $('.ttypography').after(formDiv);
  8917. formDiv.attr('action', submitUrl + "?csrf_token=" + OJBetter.common.cf_csrf_token);
  8918.  
  8919. // 顶部区域
  8920. let topDiv = $(`<div class="topDiv"></div>`);
  8921. let selectLang = cloneHTML.find('select[name="programTypeId"]'); // 语言选择
  8922. selectLang.css({ 'margin': '10px 0px' }).attr('id', 'programTypeId');
  8923. topDiv.append(selectLang);
  8924. let topRightDiv = $(`<div class="topRightDiv"></div>`);
  8925. topDiv.append(topRightDiv);
  8926. formDiv.append(topDiv);
  8927.  
  8928. // 问题选择/编号
  8929. let selectProblem = $('<input name="submittedProblemIndex" style="display:none;"></input>');
  8930. let problemCode;
  8931. if (OJBetter.typeOfPage.is_acmsguru) {
  8932. problemCode = $('h4').eq(0).text();
  8933. let matchResult = problemCode.match(/([A-Z0-9]+)/);
  8934. problemCode = matchResult[0];
  8935. } else if (OJBetter.typeOfPage.is_problemset_problem) {
  8936. let match = window.location.href.match(/\/problem\/([0-9]+?)\/([A-Z0-9]+?)(?!=[A-Z0-9])/);
  8937. problemCode = match[1] + match[2];
  8938. selectProblem.attr('name', 'submittedProblemCode');
  8939. } else {
  8940. problemCode = $('.header .title').eq(0).text();
  8941. let matchResult = problemCode.match(/([A-Z0-9]+)/);
  8942. problemCode = matchResult[0];
  8943. }
  8944. selectProblem.val(problemCode);
  8945. formDiv.append(selectProblem);
  8946.  
  8947. // 隐藏的代码记录
  8948. let sourceDiv = $('<textarea id="sourceCodeTextarea" name="source" style="display: none;"></textarea>');
  8949. formDiv.append(sourceDiv);
  8950.  
  8951. // 代码编辑器
  8952. let editorDiv = $('<div id="OJBetter_editor"></div>');
  8953. formDiv.append(editorDiv);
  8954.  
  8955. // monaco
  8956. let monaco = $('<div id="OJBetter_monaco"></div>');
  8957. editorDiv.append(monaco);
  8958.  
  8959. // 自定义调试
  8960. let customTestDiv = $(`
  8961. <details id="customTestBlock">
  8962. <summary >${i18next.t('customTestBlock.title', { ns: 'codeEditor' })}</summary>
  8963. <div id="customTests" style="min-height: 30px;"></div>
  8964. <div id="control" style="display:flex;">
  8965. <div style="display: flex;margin: 5px;">
  8966. <input type="checkbox" id="onlyCustomTest"}><label for="onlyCustomTest">
  8967. ${i18next.t('customTestBlock.onlyCustom', { ns: 'codeEditor' })}
  8968. </label>
  8969. </div>
  8970. <div style="display: flex;margin: 5px;">
  8971. <input type="checkbox" id="DontShowDiff"}>
  8972. <label for="DontShowDiff">
  8973. ${i18next.t('customTestBlock.DontShowDiff', { ns: 'codeEditor' })}
  8974. </label>
  8975. </div>
  8976. <button type="button" id="addCustomTest">${i18next.t('customTestBlock.add', { ns: 'codeEditor' })}</button>
  8977. </div>
  8978. </details>
  8979. `)
  8980. formDiv.append(customTestDiv);
  8981.  
  8982. // 调试/提交
  8983. let submitDiv = $('<div id="OJBetter_submitDiv"></div>');
  8984. let CompilerArgsInput = $('<input type="text" id="CompilerArgsInput">');
  8985. submitDiv.append(CompilerArgsInput);
  8986.  
  8987. let runButton = $(`
  8988. <button type="button" id="RunTestButton" class="ojb_btn ojb_btn_popover top">
  8989. <i class="iconfont">&#xe6c1;</i>
  8990. <span class="popover_content">${i18next.t('runTestButton.initial', { ns: 'codeEditor' })}</span>
  8991. </button>
  8992. `);
  8993. let submitButton = $(`
  8994. <button id="SubmitButton" class="ojb_btn ojb_btn_popover top" type="submit">
  8995. <i class="iconfont">&#xe633;</i>
  8996. <span class="popover_content">${i18next.t('submitButton', { ns: 'codeEditor' })}</span>
  8997. </button>
  8998. `);
  8999. if (OJBetter.monaco.setting.submitButtonPosition == "bottom") {
  9000. // 添加测试/提交按钮到底部
  9001. submitDiv.append(runButton);
  9002. submitDiv.append(submitButton);
  9003. }
  9004.  
  9005. formDiv.append(submitDiv);
  9006. let CompilerSetting = $(`
  9007. <div id="CompilerSetting"></div>
  9008. `);
  9009. formDiv.append(CompilerSetting);
  9010. let statePanel = $(`
  9011. <div id="statePanel"></div>
  9012. `);
  9013. formDiv.append(statePanel);
  9014.  
  9015. let from = {
  9016. formDiv: formDiv,
  9017. selectLang: selectLang,
  9018. topRightDiv: topRightDiv,
  9019. sourceDiv: sourceDiv,
  9020. editorDiv: editorDiv,
  9021. monaco: monaco,
  9022. runButton: runButton,
  9023. submitButton: submitButton,
  9024. submitDiv: submitDiv,
  9025. CompilerSetting: CompilerSetting,
  9026. statePanel: statePanel
  9027. };
  9028. return from;
  9029. }
  9030.  
  9031. // 解析ace格式的补全规则(acwing)
  9032. function parseAceCompleter(rules, range) {
  9033. const suggestions = [];
  9034. if (rules && rules.templates && rules.templates.items) {
  9035. const items = rules.templates.items;
  9036. for (let i = 0; i < items.length; i++) {
  9037. const item = items[i];
  9038. const parts = item.caption.split(' ');
  9039. for (let i = 0; i < parts.length; i++) {
  9040. if (item.value.startsWith(parts[i])) {
  9041. item.value = item.value.replace(parts[i], parts.slice(0, i + 1).join(' '));
  9042. break;
  9043. }
  9044. }
  9045. const completionItem = {
  9046. label: item.caption,
  9047. kind: monaco.languages.CompletionItemKind.Function,
  9048. insertText: item.value,
  9049. range: range
  9050. };
  9051. suggestions.push(completionItem);
  9052. }
  9053. }
  9054. return { suggestions };
  9055. }
  9056.  
  9057. // 解析monaco格式的补全规则
  9058. function parseMonacoCompleter(rules, range) {
  9059. const suggestions_ = [];
  9060. if (rules && rules.suggestions) {
  9061. const suggestion = rules.suggestions;
  9062. for (let i = 0; i < rules.suggestions.length; i++) {
  9063. const item = suggestion[i];
  9064. const completionItem = {
  9065. ...item,
  9066. range: range
  9067. };
  9068. suggestions_.push(completionItem);
  9069. }
  9070. }
  9071. return { suggestions: suggestions_ };
  9072. }
  9073.  
  9074. /**
  9075. * 创建monaco编辑器的一个实例
  9076. */
  9077. async function createMonacoEditor(language, form, support) {
  9078. // 判断monacoLoader是否加载完毕
  9079. async function waitForMonacoLoaderOnload() {
  9080. return new Promise((resolve) => {
  9081. const checkInitialized = () => {
  9082. if (OJBetter.monaco.loaderOnload) {
  9083. resolve();
  9084. } else {
  9085. setTimeout(checkInitialized, 100); // 每100毫秒检查一次initialized的值
  9086. }
  9087. };
  9088. checkInitialized();
  9089. });
  9090. }
  9091. if (!OJBetter.monaco.loaderOnload) await waitForMonacoLoaderOnload();
  9092.  
  9093. /**
  9094. * 通用参数
  9095. */
  9096. var id = 0; // 协议中的id标识
  9097. var workspace = language + "_workspace";
  9098. var rootUri = OJBetter.monaco.lsp.workUri + "/" + workspace;
  9099. // 文件名
  9100. var InstanceID = OJB_getRandomNumber(8).toString();
  9101. var filename = language == "java" ? "hello/src/" + InstanceID : InstanceID;
  9102. // 后缀名
  9103. var fileExtension =
  9104. language === "cpp"
  9105. ? ".cpp"
  9106. : language === "python"
  9107. ? ".py"
  9108. : language === "java"
  9109. ? ".java"
  9110. : "";
  9111. var uri = rootUri + "/" + filename + fileExtension;
  9112. var initialized = false; // 是否已初始化
  9113. var serverInfo; // 服务器返回的支持信息
  9114. var model; // model
  9115. var OJBetter_monaco = {};
  9116. window.OJBetter_monaco = OJBetter_monaco; // 全局方法
  9117.  
  9118. /**
  9119. * 一些工具函数
  9120. */
  9121. // 将lsp格式的rang转换为Monaco格式
  9122. OJBetter_monaco.lspRangeToMonacoRange = function (range) {
  9123. const { start, end } = range;
  9124. return new monaco.Range(
  9125. start.line + 1,
  9126. start.character + 1,
  9127. end.line + 1,
  9128. end.character + 1
  9129. );
  9130. };
  9131. // 将Monaco格式的rang转为lsp格式
  9132. OJBetter_monaco.MonacoRangeTolspRange = function (range) {
  9133. return {
  9134. start: {
  9135. line: range.startLineNumber - 1,
  9136. character: range.startColumn - 1,
  9137. },
  9138. end: {
  9139. line: range.endLineNumber - 1,
  9140. character: range.endColumn - 1,
  9141. },
  9142. };
  9143. };
  9144. // 将Monaco格式的position转为lsp格式的
  9145. OJBetter_monaco.MonacoPositionTolspPosition = function (position) {
  9146. return {
  9147. line: position.lineNumber - 1,
  9148. character: position.column - 1,
  9149. };
  9150. };
  9151. // 将Monaco格式的severity转为lsp格式的
  9152. OJBetter_monaco.MonacoSeverityTolspSeverity = function (severity) {
  9153. switch (severity) {
  9154. case 8:
  9155. return 1;
  9156. case 1:
  9157. return 4;
  9158. case 2:
  9159. return 3;
  9160. case 4:
  9161. return 2;
  9162. default:
  9163. return severity;
  9164. }
  9165. };
  9166. // 将lsp格式的severity转为Monaco格式的
  9167. OJBetter_monaco.lspSeverityToMonacoSeverity = function (severity) {
  9168. switch (severity) {
  9169. case 1:
  9170. return 8;
  9171. case 4:
  9172. return 1;
  9173. case 3:
  9174. return 2;
  9175. case 2:
  9176. return 4;
  9177. default:
  9178. return severity;
  9179. }
  9180. };
  9181. // 收集Monaco数据中的rang数据
  9182. OJBetter_monaco.CollectRange = function (item) {
  9183. return {
  9184. startLineNumber: item.startLineNumber,
  9185. startColumn: item.startColumn,
  9186. endLineNumber: item.endLineNumber,
  9187. endColumn: item.endColumn,
  9188. };
  9189. };
  9190. // 收集Monaco position数据中的rang数据
  9191. OJBetter_monaco.CollectRangeByPosition = function (item) {
  9192. var word = model.getWordUntilPosition(item);
  9193. return {
  9194. startLineNumber: item.lineNumber,
  9195. endLineNumber: item.lineNumber,
  9196. startColumn: word.startColumn,
  9197. endColumn: word.endColumn,
  9198. };
  9199. };
  9200. // 将lsp格式的Edit转换为Monaco格式
  9201. OJBetter_monaco.lspEditToMonacoEdit = function (edit) {
  9202. const edits = [];
  9203.  
  9204. if (language == "python") {
  9205. for (const item1 of edit.documentChanges) {
  9206. for (const item2 of item1.edits) {
  9207. const newElement = {
  9208. textEdit: {
  9209. range: OJBetter_monaco.lspRangeToMonacoRange(item2.range),
  9210. text: item2.newText,
  9211. },
  9212. resource: monaco.Uri.parse(item1.textDocument.uri),
  9213. versionId: model.getVersionId(),
  9214. };
  9215. edits.push(newElement);
  9216. }
  9217. }
  9218. } else if (language == "java") {
  9219. for (const item1 in edit.changes) {
  9220. edit.changes[item1].forEach((item2) => {
  9221. const newElement = {
  9222. textEdit: {
  9223. range: OJBetter_monaco.lspRangeToMonacoRange(item2.range),
  9224. text: item2.newText,
  9225. },
  9226. resource: uri,
  9227. versionId: model.getVersionId(),
  9228. };
  9229. edits.push(newElement);
  9230. });
  9231. }
  9232. } else {
  9233. for (const key in edit.changes) {
  9234. const arr = edit.changes[key];
  9235. for (const item of arr) {
  9236. const newElement = {
  9237. textEdit: {
  9238. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  9239. text: item.newText,
  9240. },
  9241. resource: monaco.Uri.parse(key),
  9242. versionId: model.getVersionId(),
  9243. };
  9244. edits.push(newElement);
  9245. }
  9246. }
  9247. }
  9248. return { edits: edits };
  9249. };
  9250.  
  9251. /**
  9252. * 实例化一个editor
  9253. */
  9254. uri = monaco.Uri.file(uri);
  9255. model = monaco.editor.createModel('', language, uri);
  9256. OJBetter.monaco.editor = monaco.editor.create(document.getElementById("OJBetter_monaco"), {
  9257. model: model,
  9258. rootUri: rootUri,
  9259. fontSize: 15,
  9260. tabSize: 4,
  9261. theme: OJBetter.basic.darkMode == "dark" ? "vs-dark" : "vs",
  9262. bracketPairColorization: {
  9263. enabled: true,
  9264. independentColorPoolPerBracketType: true,
  9265. },
  9266. automaticLayout: true,
  9267. lineNumbersMinChars: 3,
  9268. matchOnWordStartOnly: false,
  9269. wordWrap: "on",
  9270. wrappingIndent: "same",
  9271. glyphMargin: true,
  9272. formatOnType: true,
  9273. scrollbar: {
  9274. verticalScrollbarSize: 10,
  9275. horizontalScrollbarSize: 10,
  9276. alwaysConsumeMouseWheel: OJBetter.monaco.setting.alwaysConsumeMouseWheel
  9277. },
  9278. suggest: {
  9279. selectionMode: 'never' // 代码建议不自动选择
  9280. }
  9281. });
  9282.  
  9283. /**
  9284. * 添加快捷功能
  9285. */
  9286. (OJBetter_monaco.addShortCuts = async () => {
  9287. // 从配置信息更新字体大小
  9288. OJBetter.monaco.editor.updateOptions({ fontSize: parseInt(OJBetter.monaco.setting.fontsize) });
  9289.  
  9290. // 调整字体大小
  9291. let changeSize = $(`
  9292. <div class="ojb_btn ojb_btn_popover top">
  9293. <input type="number" id="fontSizeInput" value="${OJBetter.monaco.setting.fontsize}">
  9294. <span class="popover_content">${i18next.t('fontSizeInput', { ns: 'codeEditor' })}</span>
  9295. </div>`)
  9296. form.topRightDiv.append(changeSize);
  9297. changeSize.find('input#fontSizeInput').on('input', function () {
  9298. var size = $(this).val();
  9299. OJBetter.monaco.editor.updateOptions({ fontSize: parseInt(size) });
  9300. GM_setValue('editorFontSize', size);
  9301. });
  9302.  
  9303. // 全屏按钮
  9304. let fullscreenButton = $(`
  9305. <button type="button" class="ojb_btn ojb_btn_popover top">
  9306. <i class="iconfont">&#xe606;</i>
  9307. <span class="popover_content">${i18next.t('fullscreenButton', { ns: 'codeEditor' })}</span>
  9308. </button>
  9309. `);
  9310. form.topRightDiv.append(fullscreenButton);
  9311. fullscreenButton.on('click', enterFullscreen);
  9312.  
  9313. // 固定到底部按钮
  9314. let fixToBottomButton = $(`
  9315. <button type="button" class="ojb_btn ojb_btn_popover top">
  9316. <i class="iconfont">&#xe607;</i>
  9317. <span class="popover_content">${i18next.t('fixToBottomButton', { ns: 'codeEditor' })}</span>
  9318. </button>
  9319. `);
  9320. form.topRightDiv.append(fixToBottomButton);
  9321. fixToBottomButton.on('click', fixToBottom);
  9322.  
  9323. // 固定到右侧按钮
  9324. let fixToRightButton = $(`
  9325. <button type="button" class="ojb_btn ojb_btn_popover top">
  9326. <i class="iconfont">&#xe605;</i>
  9327. <span class="popover_content">${i18next.t('fixToRightButton', { ns: 'codeEditor' })}</span>
  9328. </button>
  9329. `);
  9330. form.topRightDiv.append(fixToRightButton);
  9331. fixToRightButton.on('click', fixToRight);
  9332.  
  9333. // 添加测试/提交按钮到顶部
  9334. if (OJBetter.monaco.setting.submitButtonPosition == "top") {
  9335. form.topRightDiv.append(form.runButton);
  9336. form.topRightDiv.append(form.submitButton);
  9337. }
  9338.  
  9339. // 选择记忆
  9340. if (!OJBetter.monaco.setting.position_initialized) {
  9341. OJBetter.monaco.setting.position_initialized = true; // 标记是否已经初始化过
  9342. if (OJBetter.monaco.setting.position == "full") {
  9343. fullscreenButton.click();
  9344. } else if (OJBetter.monaco.setting.position == "bottom") {
  9345. fixToBottomButton.click();
  9346. } else if (OJBetter.monaco.setting.position == "right") {
  9347. fixToRightButton.click();
  9348. }
  9349. }
  9350.  
  9351. // 禁用按钮
  9352. function disableButtons() {
  9353. fullscreenButton.prop("disabled", true);
  9354. fixToBottomButton.prop("disabled", true);
  9355. fixToRightButton.prop("disabled", true);
  9356. }
  9357.  
  9358. // 启用按钮
  9359. function enableButtons() {
  9360. fullscreenButton.prop("disabled", false);
  9361. fixToBottomButton.prop("disabled", false);
  9362. fixToRightButton.prop("disabled", false);
  9363. }
  9364.  
  9365. // 进入全屏
  9366. function enterFullscreen() {
  9367. let editor = $('#OJBetter_editor');
  9368. editor.addClass('fullscreen');
  9369.  
  9370. // 取消按钮
  9371. let cancelButton = $(`
  9372. <button type="button" class="ojb_btn ojb_btn_popover top primary exit_button_bottom">
  9373. <i class="iconfont">&#xe60b;</i>
  9374. <span class="popover_content">${i18next.t('exitFullscreenButton', { ns: 'codeEditor' })}</span>
  9375. </button>
  9376. `).on('click', () => exitFullscreen(cancelButton));
  9377. $('body').append(cancelButton);
  9378.  
  9379. disableButtons();
  9380. GM_setValue("monacoEditor_position", "full");
  9381. }
  9382.  
  9383. // 退出全屏
  9384. const exitFullscreen = (cancelButton) => {
  9385. let editor = $('#OJBetter_editor');
  9386. editor.removeClass('fullscreen');
  9387. cancelButton.remove();
  9388. enableButtons();
  9389. GM_setValue("monacoEditor_position", "initial");
  9390. };
  9391.  
  9392. // 固定到底部
  9393. function fixToBottom() {
  9394. let editor = $('#OJBetter_editor');
  9395. editor.addClass('bottom');
  9396.  
  9397. let halfHeight = $(window).height() * 0.5;
  9398. let blankSpace = $('<div>', {
  9399. 'class': 'blank-space',
  9400. 'style': 'height: ' + (halfHeight + 30) + 'px;'
  9401. });
  9402. $('body').append(blankSpace);
  9403.  
  9404. let cancelButton = $(`
  9405. <button type="button" class="ojb_btn ojb_btn_popover top enabled exit_button_bottom">
  9406. <i class="iconfont">&#xe625;</i>
  9407. <span class="popover_content">${i18next.t('cancelFixButton', { ns: 'codeEditor' })}</span>
  9408. </button>
  9409. `).on('click', () => cancelFixingToBottom(cancelButton, blankSpace));
  9410. $('body').append(cancelButton);
  9411.  
  9412. disableButtons();
  9413. GM_setValue("monacoEditor_position", "bottom");
  9414. }
  9415.  
  9416. // 取消固定到底部
  9417. const cancelFixingToBottom = (cancelButton, blankSpace) => {
  9418. let editor = $('#OJBetter_editor');
  9419. editor.removeClass('bottom');
  9420. cancelButton.remove();
  9421. blankSpace.remove();
  9422. enableButtons();
  9423. GM_setValue("monacoEditor_position", "initial");
  9424. };
  9425.  
  9426. // 固定到右侧边栏
  9427. function fixToRight() {
  9428. const sidebar = $('#sidebar').hide();
  9429.  
  9430. // 添加样式
  9431. const styleElement = GM_addStyle(`
  9432. #body {
  9433. min-width: 50vw;
  9434. max-width: 50vw;
  9435. max-height: 100vh;
  9436. overflow-x: hidden;
  9437. overflow-y: auto;
  9438. padding: 1rem;
  9439. box-sizing: border-box;
  9440. }
  9441. body {
  9442. margin: 0px;
  9443. }
  9444. .content-with-sidebar {
  9445. margin-right: 0px !important;
  9446. }
  9447. .menu-list li {
  9448. margin-right: 0.5em;
  9449. }
  9450. .menu-list li a {
  9451. font-size: 1.4rem;
  9452. }
  9453. #OJBetter_editor{
  9454. height: 100vh;
  9455. width: 50vw;
  9456. }
  9457. `);
  9458.  
  9459. // 包装一层div
  9460. $('#body').wrap('<div id="right-side-wrapper" style="display:flex; max-width: 100vw; overflow: hidden;"></div>');
  9461. const blankSpace = $('<div>').appendTo('#right-side-wrapper');
  9462.  
  9463. // 移动编辑器
  9464. const editor = $('#OJBetter_editor').prependTo(blankSpace).addClass('right-side');
  9465.  
  9466. // 取消按钮
  9467. const cancelButton = $(`
  9468. <button type="button" class="ojb_btn ojb_btn_popover top enabled exit_button_bottom">
  9469. <i class="iconfont">&#xe625;</i>
  9470. <span class="popover_content">${i18next.t('cancelFixButton', { ns: 'codeEditor' })}</span>
  9471. </button>
  9472. `).on('click', () => cancelFixingToRight(sidebar, styleElement, editor, cancelButton)).appendTo('body');
  9473.  
  9474. disableButtons();
  9475. GM_setValue("monacoEditor_position", "right");
  9476.  
  9477. // 补丁:修复固定到右侧导致的样例元素.sample-test相关代码重复执行的问题(具体原因未查)
  9478. $('.sample-test').find('.title').each((i, e) => {
  9479. if ($(e).find('.input-output-copier').length > 1) {
  9480. $(e).find('.input-output-copier').first().remove();
  9481. }
  9482. });
  9483. darkModeStyleAdjustment();
  9484. }
  9485.  
  9486. const cancelFixingToRight = (sidebar, styleElement, editor, cancelButton) => {
  9487. sidebar.show();
  9488. // 移回来
  9489. editor.insertAfter('#sourceCodeTextarea').removeClass('right-side');
  9490.  
  9491. // 移除包装
  9492. $('#body').unwrap();
  9493. cancelButton.remove();
  9494. styleElement.remove(); // 移除添加的样式
  9495.  
  9496. enableButtons();
  9497. GM_setValue("monacoEditor_position", "initial");
  9498. }
  9499.  
  9500. // 代码同步与保存
  9501. var nowUrl = window.location.href;
  9502. nowUrl = nowUrl.replace(/#/, ""); // 当页面存在更改时url会多出一个#,去掉
  9503. const code = await getCode(nowUrl);
  9504. if (code) {
  9505. OJBetter.monaco.editor.setValue(code); // 恢复代码
  9506. $('#sourceCodeTextarea').val(code);
  9507. }
  9508. OJBetter.monaco.editor.onDidChangeModelContent(async () => {
  9509. // 将monaco editor的内容同步到sourceCodeTextarea
  9510. const code = OJBetter.monaco.editor.getValue();
  9511. $('#sourceCodeTextarea').val(code);
  9512. await saveCode(nowUrl, code);
  9513. });
  9514. })();
  9515.  
  9516. /**
  9517. * 注册(不可用)本地自动补全
  9518. */
  9519. (OJBetter_monaco.RegisterLocalComplet = async () => {
  9520. // 补全器注册(不可用)函数
  9521. function registMyCompletionItemProvider(language, genre, rule) {
  9522. if (genre == "monaco") {
  9523. monaco.languages.registerCompletionItemProvider(language, {
  9524. provideCompletionItems: function (model, position) {
  9525. return parseMonacoCompleter(rule, OJBetter_monaco.CollectRangeByPosition(position));
  9526. }
  9527. })
  9528. } else if (genre == "ace") {
  9529. monaco.languages.registerCompletionItemProvider(language, {
  9530. provideCompletionItems: function (model, position) {
  9531. return parseAceCompleter(rule, OJBetter_monaco.CollectRangeByPosition(position));
  9532. }
  9533. })
  9534. }
  9535. }
  9536.  
  9537. // 注册(不可用)acwing cpp 模板
  9538. if (language == "cpp" && OJBetter.monaco.complet.cppCodeTemplate) {
  9539. var acwing_cpp_code_completer = JSON.parse(GM_getResourceText("acwing_cpp_code_completer"));
  9540. registMyCompletionItemProvider('cpp', 'ace', acwing_cpp_code_completer);
  9541. }
  9542.  
  9543. // 注册(不可用)自定义的补全
  9544. let complet_length = OJBetter.monaco.complet.customConfig.configurations.length;
  9545. if (complet_length > 0) {
  9546. for (let i = 0; i < complet_length; i++) {
  9547. let item = OJBetter.monaco.complet.customConfig.configurations[i];
  9548. if (item.isChoose && item.language == language) {
  9549. registMyCompletionItemProvider(item.language, item.genre, await OJB_getExternalJSON(item.jsonUrl));
  9550. }
  9551. }
  9552. }
  9553. })();
  9554.  
  9555. if (!support || !OJBetter.monaco.lsp.enabled) { return; } // 如果不支持lsp,则到此为止
  9556.  
  9557. /**
  9558. * LSP连接状态指示
  9559. */
  9560. const lspStateButton = $(`
  9561. <div id="lspStateDiv" class="ojb_btn ojb_btn_popover top loading">
  9562. <i class="iconfont">&#xe658;</i>
  9563. <span class="popover_content">${i18next.t('lsp.connect', { ns: 'codeEditor' })}</span>
  9564. </div>
  9565. `).on('click', () => {
  9566. OJB_showModal(LSPLogDiv);
  9567. LSPLogDiv.show();
  9568. });
  9569. form.topRightDiv.prepend(lspStateButton);
  9570.  
  9571. const LSPLogDiv = $(`
  9572. <dialog id="LSPLog" style="display: none;">
  9573. <button class="ojb_btn">${i18next.t('close', { ns: 'common' })}</button>
  9574. <div id="LSPLogList" style="overflow: auto;"></div>
  9575. <dialog>`);
  9576. $('body').append(LSPLogDiv);
  9577.  
  9578. const LSPLogList = $('<ul></ul>');
  9579. $('#LSPLogList').append(LSPLogList);
  9580.  
  9581. const closeButton = LSPLogDiv.find('button');
  9582. closeButton.on('click', function () {
  9583. OJB_closeModal(LSPLogDiv);
  9584. });
  9585.  
  9586. /**
  9587. * 推送新的消息到LSP日志中
  9588. * @param {'error' | 'warn' | 'info'} status
  9589. * @param {string} msg
  9590. * @param {boolean} data
  9591. */
  9592. function pushLSPLogMessage(status, msg, data) {
  9593. var li = $('<li>').text('[' + new Date().toLocaleString() + '] ' + msg);
  9594. if (status === 'error') {
  9595. li.attr('style', 'color: #f44336;');
  9596. } else if (status === 'warn') {
  9597. li.attr('style', 'color: #ff9800;');
  9598. } else if (status === 'info') {
  9599. li.attr('style', 'color: #616161;');
  9600. }
  9601. if (data) {
  9602. var jsonText = JSON.stringify(data, null, 2);
  9603. var details = $('<details>');
  9604. var summary = $('<summary>').text('Data');
  9605. var pre = $('<pre>').text(jsonText);
  9606. details.append(summary, pre);
  9607. li.append(details);
  9608. }
  9609. LSPLogList.append(li);
  9610. }
  9611.  
  9612. /**
  9613. * 添加状态底栏
  9614. */
  9615. var statusBar = $('<div id="OJBetter_statusBar">');
  9616. form.editorDiv.append(statusBar);
  9617.  
  9618. /**
  9619. * languageSocket
  9620. */
  9621. var url = OJBetter.monaco.lsp.socketUrl;
  9622. var languageSocket = new WebSocket(url + language);
  9623. OJBetter.monaco.lsp.socket.push(languageSocket);
  9624. var languageSocketState = false;
  9625. var responseHandlers = {}; // 映射表,需要等待返回数据的请求 -> 对应的事件触发函数
  9626. languageSocket.onopen = () => {
  9627. languageSocketState = true;
  9628. lspStateButton.setButtonPopover(i18next.t('lsp.waitingAnswer', { ns: 'codeEditor' }));
  9629. pushLSPLogMessage("info", `languageSocket ${i18next.t('lsp.socket.open', { ns: 'logMessage' })}`);
  9630. };
  9631. languageSocket.onmessage = (event) => {
  9632. const message = JSON.parse(event.data);
  9633. if (message.id === 0 && message.result) {
  9634. // 初始化完成
  9635. lspStateButton.setButtonState('success', i18next.t('lsp.connected', { ns: 'codeEditor' }));
  9636. pushLSPLogMessage("info", `Initialization ${i18next.t('lsp.state.finished', { ns: 'logMessage' })}`);
  9637. serverInfo = message.result; // 存下服务器支持信息
  9638. OJBetter_monaco.openDocRequest(); // 打开文档
  9639. if (!OJBetter.monaco.setting.language.includes(language)) {
  9640. OJBetter.monaco.setting.language.push(language);
  9641. OJBetter_monaco.RegistrationAfterInit(); // 注册(不可用)语言及功能
  9642. } else {
  9643. location.reload(); // 这里有问题,先贴个补丁
  9644. }
  9645. OJBetter_monaco.PassiveReceiveHandler(); // 注册(不可用)被动接收函数
  9646. } else if (message.id === 0 && message.error) {
  9647. pushLSPLogMessage("warn", `Initialization ${i18next.t('lsp.state.error', { ns: 'logMessage' })}`);
  9648. } else if (message.id !== undefined && responseHandlers[message.id]) {
  9649. // 如果收到带有id字段的消息,则回传给对应的事件触发函数
  9650. responseHandlers[message.id](message);
  9651. delete responseHandlers[message.id]; // 删除已处理的事件触发函数
  9652. } else if (message.method == "textDocument/publishDiagnostics") {
  9653. // 接收代码诊断推送
  9654. OJBetter_monaco.updateMarkers(message);
  9655. } else if (message.method == "workspace/applyEdit") {
  9656. // 应用服务器推送的更改
  9657. OJBetter_monaco.applyEdit(message);
  9658. }
  9659. };
  9660. languageSocket.onerror = (error) => {
  9661. pushLSPLogMessage("error", `languageSocket ${i18next.t('lsp.state.error', { ns: 'logMessage' })}`, error);
  9662. console.warn(`Error connecting to languageSocket: ${error}`)
  9663. };
  9664. languageSocket.onclose = (event) => {
  9665. languageSocketState = false;
  9666. lspStateButton.setButtonState('error', i18next.t('lsp.error', { ns: 'codeEditor' }));
  9667. pushLSPLogMessage("warn", `languageSocket ${i18next.t('lsp.socket.close', { ns: 'logMessage' })}`);
  9668. };
  9669.  
  9670. /**
  9671. * 等待LanguageSocketState
  9672. */
  9673. async function waitForLanguageSocketState() {
  9674. return new Promise((resolve) => {
  9675. const checkInitialized = () => {
  9676. if (languageSocketState) {
  9677. resolve();
  9678. } else {
  9679. setTimeout(checkInitialized, 100); // 每100毫秒检查一次initialized的值
  9680. }
  9681. };
  9682. checkInitialized();
  9683. });
  9684. }
  9685.  
  9686. // 等待lsp响应初始化结果
  9687. async function waitForInitialized() {
  9688. return new Promise((resolve) => {
  9689. const checkInitialized = () => {
  9690. if (initialized) {
  9691. resolve();
  9692. } else {
  9693. setTimeout(checkInitialized, 100); // 每100毫秒检查一次initialized的值
  9694. }
  9695. };
  9696. checkInitialized();
  9697. });
  9698. }
  9699.  
  9700. /**
  9701. * 与languageSocket通信的包装方法
  9702. */
  9703. async function sendMessage(data, requiresResponse, callback) {
  9704. if (!initialized) {
  9705. await waitForInitialized(); // 等待initialized为真
  9706. }
  9707. if (requiresResponse) {
  9708. responseHandlers[data.id] = callback; // 将事件触发函数与id关联起来
  9709. }
  9710. if (!languageSocketState) await waitForLanguageSocketState();
  9711. languageSocket.send(JSON.stringify(data));
  9712. }
  9713. // 发送消息并等待返回结果
  9714. function fetchData(params, callback) {
  9715. sendMessage(params, true, callback);
  9716. }
  9717. // 发送消息,不需要等待返回结果
  9718. function sendData(data) {
  9719. sendMessage(data, false);
  9720. }
  9721.  
  9722. /**
  9723. * 代码文件更新fileWebSocket
  9724. */
  9725. var fileWebSocket = new WebSocket(url + "file");
  9726. var fileWebSocketState = false;
  9727. OJBetter.monaco.lsp.socket.push(fileWebSocket);
  9728. fileWebSocket.onopen = () => {
  9729. fileWebSocketState = true;
  9730. pushLSPLogMessage("info", `fileWebSocket ${i18next.t('lsp.socket.open', { ns: 'logMessage' })}`);
  9731. };
  9732. fileWebSocket.onclose = (ev) => {
  9733. fileWebSocketState = false;
  9734. pushLSPLogMessage("warn", `fileWebSocket ${i18next.t('lsp.socket.close', { ns: 'logMessage' })}`, ev);
  9735. };
  9736. fileWebSocket.onmessage = (ev) => {
  9737. let message = JSON.parse(ev.data);
  9738. if (message.result !== "ok")
  9739. pushLSPLogMessage("error", `update file failed: ${ev}`);
  9740. };
  9741. fileWebSocket.onerror = (error) => {
  9742. console.warn(`Error connecting to fileWebSocket: ${error}`);
  9743. };
  9744. async function updateFile(workspace, filename, fileExtension, code) {
  9745. async function waitForfileWebSocketState() {
  9746. return new Promise((resolve) => {
  9747. const checkInitialized = () => {
  9748. if (fileWebSocketState) {
  9749. resolve();
  9750. } else {
  9751. setTimeout(checkInitialized, 100); // 每100毫秒检查一次initialized的值
  9752. }
  9753. };
  9754. checkInitialized();
  9755. });
  9756. }
  9757. if (!fileWebSocketState) await waitForfileWebSocketState();
  9758. fileWebSocket.send(
  9759. JSON.stringify({
  9760. type: "update",
  9761. workspace,
  9762. filename,
  9763. fileExtension,
  9764. code,
  9765. })
  9766. );
  9767. }
  9768.  
  9769. /**
  9770. * 发送初始化请求
  9771. */
  9772. OJBetter_monaco.Initialize = () => {
  9773. //初始化initialize
  9774. const capabilities = {
  9775. workspace: {
  9776. applyEdit: true,
  9777. },
  9778. textDocument: {
  9779. publishDiagnostics: {
  9780. relatedInformation: true,
  9781. versionSupport: false,
  9782. tagSupport: {
  9783. valueSet: [1, 2],
  9784. },
  9785. codeDescriptionSupport: true,
  9786. },
  9787. completion: {
  9788. contextSupport: true,
  9789. completionItem: {
  9790. snippetSupport: true,
  9791. commitCharactersSupport: true,
  9792. documentationFormat: ["markdown", "plaintext"],
  9793. deprecatedSupport: true,
  9794. preselectSupport: true,
  9795. tagSupport: {
  9796. valueSet: [1],
  9797. },
  9798. insertReplaceSupport: true,
  9799. resolveSupport: {
  9800. properties: [
  9801. "documentation",
  9802. "detail",
  9803. "additionalTextEdits",
  9804. ],
  9805. },
  9806. insertTextModeSupport: {
  9807. valueSet: [1, 2],
  9808. },
  9809. },
  9810. },
  9811. hover: {
  9812. dynamicRegistration: true,
  9813. contentFormat: ["markdown", "plaintext"],
  9814. },
  9815. signatureHelp: {
  9816. signatureInformation: {
  9817. documentationFormat: ["markdown", "plaintext"],
  9818. parameterInformation: {
  9819. labelOffsetSupport: true,
  9820. },
  9821. activeParameterSupport: true,
  9822. },
  9823. contextSupport: true,
  9824. },
  9825. definition: {
  9826. dynamicRegistration: true,
  9827. linkSupport: true,
  9828. },
  9829. references: {
  9830. dynamicRegistration: true,
  9831. },
  9832. documentHighlight: {
  9833. dynamicRegistration: true,
  9834. },
  9835. codeAction: {
  9836. codeActionLiteralSupport: {
  9837. codeActionKind: {
  9838. valueSet:
  9839. language == "java"
  9840. ? []
  9841. : [
  9842. "",
  9843. "quickfix",
  9844. "refactor",
  9845. "refactor.extract",
  9846. "refactor.inline",
  9847. "refactor.rewrite",
  9848. "source",
  9849. "source.organizeImports",
  9850. ],
  9851. },
  9852. },
  9853. },
  9854. rename: {
  9855. dynamicRegistration: true,
  9856. prepareSupport: true,
  9857. prepareSupportDefaultBehavior: 1,
  9858. honorsChangeAnnotations: true,
  9859. },
  9860. documentLink: {
  9861. tooltipSupport: true,
  9862. },
  9863. typeDefinition: {
  9864. dynamicRegistration: true,
  9865. linkSupport: true,
  9866. },
  9867. implementation: {
  9868. dynamicRegistration: true,
  9869. linkSupport: true,
  9870. },
  9871. colorProvider: {
  9872. dynamicRegistration: true,
  9873. },
  9874. foldingRange: {
  9875. dynamicRegistration: true,
  9876. rangeLimit: 5000,
  9877. lineFoldingOnly: true,
  9878. },
  9879. declaration: {
  9880. dynamicRegistration: true,
  9881. linkSupport: true,
  9882. },
  9883. semanticTokens: {
  9884. dynamicRegistration: true,
  9885. tokenTypes: [
  9886. "namespace",
  9887. "type",
  9888. "class",
  9889. "enum",
  9890. "interface",
  9891. "struct",
  9892. "typeParameter",
  9893. "parameter",
  9894. "variable",
  9895. "property",
  9896. "enumMember",
  9897. "event",
  9898. "function",
  9899. "method",
  9900. "macro",
  9901. "keyword",
  9902. "modifier",
  9903. "comment",
  9904. "string",
  9905. "number",
  9906. "regexp",
  9907. "operator",
  9908. ],
  9909. tokenModifiers: [
  9910. "declaration",
  9911. "definition",
  9912. "readonly",
  9913. "static",
  9914. "deprecated",
  9915. "abstract",
  9916. "async",
  9917. "modification",
  9918. "documentation",
  9919. "defaultLibrary",
  9920. ],
  9921. formats: ["relative"],
  9922. requests: {
  9923. range: true,
  9924. full: {
  9925. delta: true,
  9926. },
  9927. },
  9928. multilineTokenSupport: false,
  9929. overlappingTokenSupport: false,
  9930. },
  9931. callHierarchy: {
  9932. dynamicRegistration: true,
  9933. },
  9934. },
  9935. window: {
  9936. showMessage: {
  9937. messageActionItem: {
  9938. additionalPropertiesSupport: true,
  9939. },
  9940. },
  9941. showDocument: {
  9942. support: true,
  9943. },
  9944. workDoneProgress: true,
  9945. },
  9946. general: {
  9947. regularExpressions: {
  9948. engine: "ECMAScript",
  9949. version: "ES2020",
  9950. },
  9951. markdown: {
  9952. parser: "marked",
  9953. version: "1.1.0",
  9954. },
  9955. },
  9956. };
  9957.  
  9958. const initializeRequest = {
  9959. id: id++,
  9960. jsonrpc: "2.0",
  9961. method: "initialize",
  9962. params: {
  9963. processId: null,
  9964. clientInfo: {
  9965. name: "CFMonaco" + InstanceID,
  9966. },
  9967. locale: "zh-CN",
  9968. rootPath: null,
  9969. rootUri: null,
  9970. capabilities: capabilities,
  9971. trace: "off",
  9972. workspaceFolders: [
  9973. {
  9974. uri:
  9975. "file:///" + OJBetter.monaco.lsp.workUri + workspace,
  9976. name:
  9977. "file:///" + OJBetter.monaco.lsp.workUri + workspace,
  9978. },
  9979. ],
  9980. },
  9981. };
  9982. languageSocket.send(JSON.stringify(initializeRequest));
  9983.  
  9984. // 打开文档函数
  9985. OJBetter_monaco.openDocRequest = function () {
  9986. const initializ = {
  9987. jsonrpc: "2.0",
  9988. method: "initialized",
  9989. params: {},
  9990. };
  9991. languageSocket.send(JSON.stringify(initializ));
  9992. const openDocRequest = {
  9993. jsonrpc: "2.0",
  9994. method: "textDocument/didOpen",
  9995. params: {
  9996. textDocument: {
  9997. uri: model.uri.toString(),
  9998. languageId: language,
  9999. version: model.getVersionId(),
  10000. text: model.getValue(),
  10001. },
  10002. },
  10003. };
  10004. languageSocket.send(JSON.stringify(openDocRequest));
  10005. initialized = true; // 初始化完成,这里确认逻辑待完善
  10006. };
  10007.  
  10008. // 初始化更新文件
  10009. updateFile(workspace, filename, fileExtension, model.getValue());
  10010. }
  10011.  
  10012. /**
  10013. * 注册(不可用)语言及功能
  10014. */
  10015. OJBetter_monaco.RegistrationAfterInit = () => {
  10016. // 注册(不可用)语言
  10017. monaco.languages.register({ id: language });
  10018.  
  10019. // 注册(不可用)"Command"
  10020. (function registerCommand() {
  10021. serverInfo.capabilities.executeCommandProvider.commands.forEach(
  10022. (item) => {
  10023. pushLSPLogMessage("info", `${i18next.t('lsp.server.regist', { ns: 'logMessage' })}`, item);
  10024. monaco.editor.registerCommand(item, (accessor, ...args) => {
  10025. sendData({
  10026. jsonrpc: "2.0",
  10027. id: id++,
  10028. method: "workspace/executeCommand",
  10029. params: {
  10030. command: item,
  10031. arguments: args,
  10032. },
  10033. });
  10034. });
  10035. }
  10036. );
  10037. })();
  10038.  
  10039. // 注册(不可用)"增量更新"
  10040. model.onDidChangeContent((event) => {
  10041. updateFile(workspace, filename, fileExtension, model.getValue()); // 更新文件
  10042. const changeDocRequest = {
  10043. jsonrpc: "2.0",
  10044. method: "textDocument/didChange",
  10045. params: {
  10046. textDocument: {
  10047. uri: model.uri.toString(),
  10048. version: model.getVersionId(),
  10049. },
  10050. contentChanges: event.changes.map((change) => ({
  10051. range: OJBetter_monaco.MonacoRangeTolspRange(change.range),
  10052. rangeLength: change.rangeLength,
  10053. text: change.text,
  10054. })),
  10055. },
  10056. };
  10057. sendData(changeDocRequest);
  10058. });
  10059.  
  10060. //注册(不可用)"自动补全"
  10061. monaco.languages.registerCompletionItemProvider(language, {
  10062. provideCompletionItems: (model, position, context) => {
  10063. const request = {
  10064. jsonrpc: "2.0",
  10065. id: id++,
  10066. method: "textDocument/completion",
  10067. params: {
  10068. textDocument: {
  10069. uri: model.uri.toString(),
  10070. },
  10071. position: OJBetter_monaco.MonacoPositionTolspPosition(position),
  10072. context: {
  10073. triggerKind: context.triggerKind + 1, // 这里要+1,两边的定义不一样。。。
  10074. triggerCharacter: context.triggerCharacter,
  10075. },
  10076. },
  10077. };
  10078. return new Promise((resolve, reject) => {
  10079. fetchData(request, (response) => {
  10080. const result = response.result;
  10081. pushLSPLogMessage("info", `completion ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10082. if (!result) return resolve(null);
  10083. const CompletionItems = {
  10084. suggestions: result.items.map(
  10085. ({
  10086. label,
  10087. kind,
  10088. filterText,
  10089. insertText,
  10090. insertTextFormat,
  10091. sortText,
  10092. textEdit,
  10093. documentation,
  10094. additionalTextEdits,
  10095. }) => ({
  10096. additionalTextEdits: additionalTextEdits
  10097. ? additionalTextEdits.map(({ newText, range }) => ({
  10098. text: newText,
  10099. range: OJBetter_monaco.lspRangeToMonacoRange(range),
  10100. }))
  10101. : [],
  10102. documentation: documentation ? documentation.value : "",
  10103. filterText,
  10104. insertText: insertText ? insertText : textEdit.newText,
  10105. insertTextRules:
  10106. insertTextFormat === 2
  10107. ? monaco.languages.CompletionItemInsertTextRule
  10108. .InsertAsSnippet
  10109. : monaco.languages.CompletionItemInsertTextRule
  10110. .KeepWhitespace,
  10111. kind,
  10112. label,
  10113. sortText,
  10114. range: textEdit
  10115. ? textEdit.range
  10116. ? OJBetter_monaco.lspRangeToMonacoRange(textEdit.range)
  10117. : OJBetter_monaco.lspRangeToMonacoRange(textEdit.insert)
  10118. : null,
  10119. })
  10120. ),
  10121. };
  10122. pushLSPLogMessage("info", `completion ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, CompletionItems);
  10123. resolve(CompletionItems);
  10124. });
  10125. });
  10126. },
  10127. });
  10128.  
  10129. // 注册(不可用)"代码修复"
  10130. monaco.languages.registerCodeActionProvider(language, {
  10131. provideCodeActions: (model, range, context) => {
  10132. const request = {
  10133. id: id++,
  10134. jsonrpc: "2.0",
  10135. method: "textDocument/codeAction",
  10136. params: {
  10137. textDocument: {
  10138. uri: model.uri.toString(),
  10139. },
  10140. range: OJBetter_monaco.MonacoRangeTolspRange(range),
  10141. context: {
  10142. diagnostics: context.markers.map((item) => ({
  10143. range: OJBetter_monaco.MonacoRangeTolspRange({
  10144. startLineNumber: item.startLineNumber,
  10145. startColumn: item.startColumn,
  10146. endLineNumber: item.endLineNumber,
  10147. endColumn: item.endColumn,
  10148. }),
  10149. severity: OJBetter_monaco.MonacoSeverityTolspSeverity(
  10150. item.severity
  10151. ),
  10152. code: item.code,
  10153. source: item.source,
  10154. message: item.message,
  10155. tags: item.tags,
  10156. relatedInformation: item.relatedInformation
  10157. ? item.relatedInformation.map((item) => ({
  10158. location: {
  10159. uri: item.resource.toString(),
  10160. range: OJBetter_monaco.MonacoRangeTolspRange({
  10161. startLineNumber: item.startLineNumber,
  10162. startColumn: item.startColumn,
  10163. endLineNumber: item.endLineNumber,
  10164. endColumn: item.endColumn,
  10165. }),
  10166. },
  10167. message: item.message,
  10168. }))
  10169. : null,
  10170. })),
  10171. only: context.only ? [context.only] : [],
  10172. triggerKind: context.trigger,
  10173. },
  10174. },
  10175. };
  10176.  
  10177. return new Promise((resolve, reject) => {
  10178. fetchData(request, (response) => {
  10179. const result = response.result;
  10180. pushLSPLogMessage("info", `codeAction ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10181. if (!result) return resolve(null);
  10182. const codeAction = {
  10183. actions: result.map((item) => ({
  10184. title: item.title,
  10185. kind: item.kind ? item.kind : "quickfix",
  10186. command: item.command
  10187. ? item.command.command
  10188. ? {
  10189. id: item.command.command,
  10190. arguments: item.command.arguments,
  10191. title: item.command.title,
  10192. }
  10193. : null
  10194. : null,
  10195. diagnostics: item.diagnostics
  10196. ? item.diagnostics.map((item) => ({
  10197. code: item.code,
  10198. message: item.message,
  10199. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  10200. severity: OJBetter_monaco.lspSeverityToMonacoSeverity(
  10201. item.severity
  10202. ),
  10203. source: item.source,
  10204. }))
  10205. : null,
  10206. edit: item.edit
  10207. ? OJBetter_monaco.lspEditToMonacoEdit(item.edit)
  10208. : item.arguments
  10209. ? {
  10210. edits: item.arguments.flatMap(
  10211. (item1) => OJBetter_monaco.lspEditToMonacoEdit(item1).edits
  10212. ),
  10213. }
  10214. : null,
  10215. })),
  10216. dispose: () => { },
  10217. };
  10218. pushLSPLogMessage("info", `codeAction ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, codeAction);
  10219.  
  10220. resolve(codeAction);
  10221. });
  10222. });
  10223. },
  10224. });
  10225.  
  10226. // 注册(不可用)"hover提示"
  10227. monaco.languages.registerHoverProvider(language, {
  10228. provideHover: (model, position) => {
  10229. const request = {
  10230. jsonrpc: "2.0",
  10231. id: id++,
  10232. method: "textDocument/hover",
  10233. params: {
  10234. textDocument: {
  10235. uri: model.uri.toString(),
  10236. },
  10237. position: OJBetter_monaco.MonacoPositionTolspPosition(position),
  10238. },
  10239. };
  10240.  
  10241. return new Promise((resolve, reject) => {
  10242. fetchData(request, (response) => {
  10243. pushLSPLogMessage("info", `Hover ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10244. const result = response.result;
  10245.  
  10246. if (!result) return resolve(null);
  10247. const Hover = {
  10248. range: result.range
  10249. ? OJBetter_monaco.lspRangeToMonacoRange(result.range)
  10250. : new monaco.Range(
  10251. position.lineNumber,
  10252. position.column,
  10253. position.lineNumber,
  10254. position.column
  10255. ),
  10256. contents: Array.isArray(result.contents)
  10257. ? result.contents.map((item) => ({
  10258. value: item.value ? item.value : item,
  10259. }))
  10260. : [
  10261. {
  10262. value: result.contents.value,
  10263. },
  10264. ],
  10265. };
  10266. pushLSPLogMessage("info", `Hover ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, Hover);
  10267. resolve(Hover);
  10268. });
  10269. });
  10270. },
  10271. });
  10272.  
  10273. // 注册(不可用)"inlay提示"
  10274. if (language == "cpp" || language == "java")
  10275. monaco.languages.registerInlayHintsProvider(language, {
  10276. provideInlayHints: (model, range, token) => {
  10277. return new Promise((resolve, reject) => {
  10278. const request = {
  10279. jsonrpc: "2.0",
  10280. id: id++,
  10281. method: "textDocument/inlayHint",
  10282. params: {
  10283. textDocument: {
  10284. uri: model.uri.toString(),
  10285. },
  10286. range: OJBetter_monaco.MonacoRangeTolspRange(range),
  10287. },
  10288. };
  10289.  
  10290. fetchData(request, (response) => {
  10291. const result = response.result;
  10292. pushLSPLogMessage("info", `Inlay Hints ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10293.  
  10294. if (!result) return resolve(null);
  10295.  
  10296. const inlayHints = {
  10297. hints: result.map((item) => {
  10298. return {
  10299. kind: item.kind,
  10300. label: item.label,
  10301. paddingLeft: item.paddingLeft,
  10302. paddingRight: item.paddingRight,
  10303. position: {
  10304. lineNumber: item.position.line + 1,
  10305. column: item.position.character + 1,
  10306. },
  10307. };
  10308. }),
  10309. };
  10310. pushLSPLogMessage("info", `Inlay Hints ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, inlayHints);
  10311.  
  10312. resolve(inlayHints);
  10313. });
  10314. });
  10315. },
  10316. });
  10317.  
  10318. // 注册(不可用)"转到定义"
  10319. monaco.languages.registerDefinitionProvider(language, {
  10320. provideDefinition: (model, position) => {
  10321. const request = {
  10322. jsonrpc: "2.0",
  10323. id: id++,
  10324. method: "textDocument/definition",
  10325. params: {
  10326. textDocument: {
  10327. uri: model.uri.toString(),
  10328. },
  10329. position: OJBetter_monaco.MonacoPositionTolspPosition(position),
  10330. },
  10331. };
  10332.  
  10333. return new Promise((resolve, reject) => {
  10334. fetchData(request, (response) => {
  10335. const result = response.result;
  10336. pushLSPLogMessage("info", `definition ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10337.  
  10338. if (result.length == 0) return resolve(null);
  10339. const definition = result.map((item) => ({
  10340. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  10341. uri: monaco.Uri.parse(item.uri), //
  10342. }));
  10343. pushLSPLogMessage("info", `definition ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, definition);
  10344.  
  10345. resolve(definition);
  10346. });
  10347. });
  10348.  
  10349. return null; // 如果没有内容,则返回null
  10350. },
  10351. });
  10352.  
  10353. // 注册(不可用)"转到引用"
  10354. monaco.languages.registerReferenceProvider(language, {
  10355. provideReferences: (model, position, context) => {
  10356. const request = {
  10357. jsonrpc: "2.0",
  10358. id: id++,
  10359. method: "textDocument/references",
  10360. params: {
  10361. context: context,
  10362. textDocument: {
  10363. uri: model.uri.toString(),
  10364. },
  10365. position: OJBetter_monaco.MonacoPositionTolspPosition(position),
  10366. },
  10367. };
  10368.  
  10369. return new Promise((resolve, reject) => {
  10370. fetchData(request, (response) => {
  10371. const result = response.result;
  10372. pushLSPLogMessage("info", `references ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10373.  
  10374. if (result.length == 0) return resolve([]);
  10375.  
  10376. const references = result.map((item) => ({
  10377. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  10378. uri: monaco.Uri.parse(item.uri), //
  10379. }));
  10380. pushLSPLogMessage("info", `references ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, references);
  10381. resolve(references);
  10382. });
  10383. });
  10384. return []; // 如果没有内容,则返回空数组
  10385. },
  10386. });
  10387.  
  10388. // 注册(不可用)"符号引用点击高亮"
  10389. monaco.languages.registerDocumentHighlightProvider(language, {
  10390. provideDocumentHighlights: (model, position) => {
  10391. const request = {
  10392. jsonrpc: "2.0",
  10393. id: id++,
  10394. method: "textDocument/documentHighlight",
  10395. params: {
  10396. textDocument: {
  10397. uri: model.uri.toString(),
  10398. },
  10399. position: OJBetter_monaco.MonacoPositionTolspPosition(position),
  10400. },
  10401. };
  10402.  
  10403. return new Promise((resolve, reject) => {
  10404. fetchData(request, (response) => {
  10405. const result = response.result;
  10406. pushLSPLogMessage("info", `documentHighlight ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10407.  
  10408. if (!result || result.length == 0) return resolve([]);
  10409. const highlights = result.map((item) => ({
  10410. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  10411. kind: item.kind,
  10412. }));
  10413. pushLSPLogMessage("info",
  10414. `documentHighlight ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`,
  10415. highlights
  10416. );
  10417.  
  10418. resolve(highlights);
  10419. });
  10420. });
  10421. return []; // 如果没有内容,则返回空数组
  10422. },
  10423. });
  10424.  
  10425. // 注册(不可用)"文件链接"
  10426. if (language == "cpp" || language == "java")
  10427. monaco.languages.registerLinkProvider(language, {
  10428. provideLinks: (model) => {
  10429. const request = {
  10430. jsonrpc: "2.0",
  10431. id: id++,
  10432. method: "textDocument/documentLink",
  10433. params: {
  10434. textDocument: {
  10435. uri: model.uri.toString(),
  10436. },
  10437. },
  10438. };
  10439.  
  10440. return new Promise((resolve, reject) => {
  10441. fetchData(request, (response) => {
  10442. const result = response.result;
  10443. pushLSPLogMessage("info", `DocumentLink ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10444.  
  10445. if (!result) return resolve(null);
  10446. const links = {
  10447. links: result.map((item) => ({
  10448. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  10449. url: item.target.toString(),
  10450. tooltip: item.tooltip ? item.tooltip : null,
  10451. })),
  10452. };
  10453. pushLSPLogMessage("info", `DocumentLink ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, links);
  10454. resolve(links);
  10455. });
  10456. });
  10457. },
  10458. });
  10459.  
  10460. // 注册(不可用)"格式化"
  10461. monaco.languages.registerDocumentFormattingEditProvider(language, {
  10462. provideDocumentFormattingEdits: (model, options, token) => {
  10463. const request = {
  10464. jsonrpc: "2.0",
  10465. id: id++,
  10466. method: "textDocument/formatting",
  10467. params: {
  10468. textDocument: {
  10469. uri: model.uri.toString(),
  10470. },
  10471. options: options,
  10472. },
  10473. };
  10474.  
  10475. return new Promise((resolve, reject) => {
  10476. fetchData(request, (response) => {
  10477. const result = response.result;
  10478. pushLSPLogMessage("info", `formatting ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10479.  
  10480. const TextEdit = result.map((edit) => ({
  10481. range: OJBetter_monaco.lspRangeToMonacoRange(edit.range),
  10482. text: edit.newText,
  10483. }));
  10484. pushLSPLogMessage("info", `formatting ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, TextEdit);
  10485. resolve(TextEdit);
  10486. });
  10487. });
  10488. },
  10489. });
  10490.  
  10491. // 注册(不可用)"部分格式化"
  10492. monaco.languages.registerDocumentRangeFormattingEditProvider(language, {
  10493. provideDocumentRangeFormattingEdits: (model, range, options) => {
  10494. const request = {
  10495. jsonrpc: "2.0",
  10496. id: id++,
  10497. method: "textDocument/rangeFormatting",
  10498. params: {
  10499. textDocument: {
  10500. uri: model.uri.toString(),
  10501. },
  10502. range: OJBetter_monaco.MonacoRangeTolspRange(range),
  10503. options,
  10504. },
  10505. };
  10506.  
  10507. return new Promise((resolve, reject) => {
  10508. fetchData(request, (response) => {
  10509. const result = response.result;
  10510. pushLSPLogMessage("info", `rangeFormatting ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10511.  
  10512. if (!result || result.length == 0) return resolve([]);
  10513. const edits = result.map((item) => ({
  10514. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  10515. text: item.newText,
  10516. }));
  10517. pushLSPLogMessage("info", `rangeFormatting ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, edits);
  10518. resolve(edits);
  10519. });
  10520. });
  10521. },
  10522. });
  10523.  
  10524. // 注册(不可用)"重命名"
  10525. monaco.languages.registerRenameProvider(language, {
  10526. provideRenameEdits: (model, position, newName, token) => {
  10527. const request = {
  10528. jsonrpc: "2.0",
  10529. id: id++,
  10530. method: "textDocument/rename",
  10531. params: {
  10532. textDocument: {
  10533. uri: model.uri.toString(),
  10534. },
  10535. position: OJBetter_monaco.MonacoPositionTolspPosition(position),
  10536. newName: newName,
  10537. },
  10538. };
  10539.  
  10540. return new Promise((resolve, reject) => {
  10541. fetchData(request, (response) => {
  10542. const result = response.result;
  10543. pushLSPLogMessage("info", `rename ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10544.  
  10545. const rename = OJBetter_monaco.lspEditToMonacoEdit(result);
  10546. pushLSPLogMessage("info", `rename ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, rename);
  10547. resolve(rename);
  10548. });
  10549. });
  10550. },
  10551. });
  10552.  
  10553. // 注册(不可用)"折叠范围分析"
  10554. monaco.languages.registerFoldingRangeProvider(language, {
  10555. provideFoldingRanges: (model) => {
  10556. const request = {
  10557. jsonrpc: "2.0",
  10558. id: id++,
  10559. method: "textDocument/foldingRange",
  10560. params: {
  10561. textDocument: {
  10562. uri: model.uri.toString(),
  10563. },
  10564. },
  10565. };
  10566.  
  10567. return new Promise((resolve, reject) => {
  10568. fetchData(request, (response) => {
  10569. const result = response.result;
  10570. pushLSPLogMessage("info", `FoldingRange ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10571.  
  10572. if (!result) return resolve([]);
  10573. const foldingRanges = result.map((item) => ({
  10574. start: item.startLine + 1,
  10575. end: item.endLine + 1,
  10576. kind: monaco.languages.FoldingRangeKind.fromValue(item.kind),
  10577. }));
  10578. pushLSPLogMessage("info", `FoldingRange ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, foldingRanges);
  10579. resolve(foldingRanges);
  10580. });
  10581. });
  10582. },
  10583. });
  10584.  
  10585. // 注册(不可用)"方法签名提示"
  10586. monaco.languages.registerSignatureHelpProvider(language, {
  10587. signatureHelpTriggerCharacters:
  10588. serverInfo.capabilities.signatureHelpProvider.triggerCharacters,
  10589. provideSignatureHelp: (model, position, token, context) => {
  10590. const request = {
  10591. jsonrpc: "2.0",
  10592. id: id++,
  10593. method: "textDocument/signatureHelp",
  10594. params: {
  10595. textDocument: {
  10596. uri: model.uri.toString(),
  10597. },
  10598. position: {
  10599. line: position.lineNumber - 1,
  10600. character: position.column - 1,
  10601. },
  10602. context: {
  10603. triggerKind: context.triggerKind,
  10604. triggerCharacter: context.triggerCharacter,
  10605. isRetrigger: context.isRetrigger,
  10606. activeSignatureHelp: context.activeSignatureHelp,
  10607. },
  10608. },
  10609. };
  10610.  
  10611. return new Promise((resolve, reject) => {
  10612. fetchData(request, (response) => {
  10613. const result = response.result;
  10614.  
  10615. pushLSPLogMessage("info", `signatureHelp ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10616.  
  10617. if (!result) return resolve(null);
  10618. const SignatureHelpResult = {
  10619. value: {
  10620. activeParameter: result.activeParameter,
  10621. activeSignature: result.activeSignature,
  10622. signatures: result.signatures,
  10623. },
  10624. dispose: () => { },
  10625. };
  10626.  
  10627. pushLSPLogMessage("info",
  10628. `signatureHelp ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`,
  10629. SignatureHelpResult
  10630. );
  10631. resolve(SignatureHelpResult);
  10632. });
  10633. });
  10634. },
  10635. });
  10636.  
  10637. // 注册(不可用)"渐进式自动格式化" 如果server有这个
  10638. if (serverInfo.capabilities.documentOnTypeFormattingProvider)
  10639. monaco.languages.registerOnTypeFormattingEditProvider(language, {
  10640. autoFormatTriggerCharacters: [
  10641. serverInfo.capabilities.documentOnTypeFormattingProvider
  10642. .firstTriggerCharacter,
  10643. ],
  10644. provideOnTypeFormattingEdits: (model, position, ch, options) => {
  10645. const request = {
  10646. jsonrpc: "2.0",
  10647. id: id++,
  10648. method: "textDocument/onTypeFormatting",
  10649. params: {
  10650. textDocument: {
  10651. uri: model.uri.toString(),
  10652. },
  10653. position: OJBetter_monaco.MonacoPositionTolspPosition(position),
  10654. ch,
  10655. options,
  10656. },
  10657. };
  10658.  
  10659. return new Promise((resolve, reject) => {
  10660. fetchData(request, (response) => {
  10661. const result = response.result;
  10662. pushLSPLogMessage("info", `onTypeFormatting ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10663.  
  10664. if (!result || result.length == 0) return resolve([]);
  10665.  
  10666. const edits = result.map((item) => ({
  10667. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  10668. text: item.newText,
  10669. }));
  10670. pushLSPLogMessage("info", `onTypeFormatting ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, edits);
  10671. resolve(edits);
  10672. });
  10673. });
  10674. },
  10675. });
  10676. };
  10677.  
  10678. /**
  10679. * 被动式接收处理
  10680. */
  10681. OJBetter_monaco.PassiveReceiveHandler = () => {
  10682.  
  10683. // "实时代码诊断"
  10684. OJBetter_monaco.updateMarkers = function (message) {
  10685. const params = message.params;
  10686. pushLSPLogMessage("info", `Markers ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, message);
  10687.  
  10688. if (!params) return;
  10689. const markers = params.diagnostics.map((item1) => ({
  10690. code: item1.code,
  10691. message: item1.message,
  10692. ...OJBetter_monaco.lspRangeToMonacoRange(item1.range),
  10693. relatedInformation: item1.relatedInformation
  10694. ? item1.relatedInformation.map((item2) => ({
  10695. ...(item2.location.range
  10696. ? OJBetter_monaco.lspRangeToMonacoRange(item2.location.range)
  10697. : OJBetter_monaco.lspRangeToMonacoRange(item2.location)),
  10698. message: item2.message,
  10699. resource: monaco.Uri.parse(item2.location.uri),
  10700. }))
  10701. : null,
  10702. severity: OJBetter_monaco.lspSeverityToMonacoSeverity(item1.severity),
  10703. source: item1.source,
  10704. }));
  10705.  
  10706. pushLSPLogMessage("info", `Markers ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, markers);
  10707. monaco.editor.setModelMarkers(model, "eslint", markers);
  10708.  
  10709. // 更新状态底栏信息
  10710. const nowMarks = monaco.editor.getModelMarkers();
  10711. warningCount = 0;
  10712. errorCount = 0;
  10713. for (const marker of nowMarks) {
  10714. if (marker.severity === monaco.MarkerSeverity.Warning) {
  10715. warningCount++;
  10716. } else if (marker.severity === monaco.MarkerSeverity.Error) {
  10717. errorCount++;
  10718. }
  10719. }
  10720. $('#OJBetter_statusBar').text(`Warnings: ${warningCount}, Errors: ${errorCount}`);
  10721. };
  10722.  
  10723. // "应用服务器推送的更改"(代码修复)
  10724. OJBetter_monaco.applyEdit = function (message) {
  10725. const params = message.params;
  10726. pushLSPLogMessage("info", `applyEdit ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, message);
  10727.  
  10728. if (!params) return;
  10729. const operations = Object.values(params.edit.changes)
  10730. .flat()
  10731. .map((item) => ({
  10732. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  10733. text: item.newText,
  10734. }));
  10735.  
  10736. pushLSPLogMessage("info", `applyEdit ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, operations);
  10737. model.pushEditOperations([], operations, () => null); // 入栈编辑操作
  10738. };
  10739. }
  10740.  
  10741. if (!languageSocketState) await waitForLanguageSocketState();
  10742. OJBetter_monaco.Initialize();
  10743. }
  10744.  
  10745. // 语言更改
  10746. function changeMonacoLanguage(form) {
  10747. let nowSelect = form.selectLang.val();
  10748. // 记忆更改
  10749. GM_setValue('compilerSelection', nowSelect);
  10750. // 销毁旧的编辑器
  10751. try {
  10752. if (OJBetter.monaco.editor) OJBetter.monaco.editor.dispose();
  10753. } catch (error) {
  10754. console.warn("Encountered an error while attempting to delete the old editor, but it should not affect your regular usage.", error)
  10755. }
  10756. // 关闭旧的socket
  10757. OJBetter.monaco.lsp.socket.forEach(socket => {
  10758. socket.close();
  10759. });
  10760. // 移除相关元素
  10761. form.topRightDiv.empty();
  10762. $('#LSPLog').remove();
  10763. $('#OJBetter_statusBar').remove();
  10764. // 创建新的编辑器
  10765. if (nowSelect in value_monacoLanguageMap) {
  10766. let language = value_monacoLanguageMap[nowSelect];
  10767. if (language == "python" || language == "cpp") {
  10768. createMonacoEditor(language, form, true);
  10769. } else {
  10770. createMonacoEditor(language, form, false);
  10771. }
  10772. } else {
  10773. createMonacoEditor(null, false);
  10774. }
  10775. // 更新在线编译器参数
  10776. changeCompilerArgs(nowSelect);
  10777. }
  10778.  
  10779. // 收集样例数据
  10780. function getTestData() {
  10781. var testData = {};
  10782.  
  10783. // 从pre中获取文本信息
  10784. function getTextFromPre(node) {
  10785. let text;
  10786. if (node.find("br").length > 0) {
  10787. text = node.html().replace(/<br>/g, "\n"); // <br>作换行符的情况
  10788. } else {
  10789. text = node.text();
  10790. }
  10791. return text;
  10792. }
  10793.  
  10794. $('.input').each(function (index) {
  10795. var inputText = '';
  10796. if ($(this).find('pre').find('div').length > 0) {
  10797. $(this).find('pre').find('div').each(function () {
  10798. inputText += getTextFromPre($(this)) + '\n';
  10799. });
  10800. } else {
  10801. inputText = getTextFromPre($(this).find('pre'));
  10802. }
  10803. var outputText = '';
  10804. if ($('.output').eq(index).find('pre').find('div').length > 0) {
  10805. $('.output').eq(index).find('pre').find('div').each(function () {
  10806. inputText += getTextFromPre($(this)) + '\n';
  10807. });
  10808. } else {
  10809. outputText = getTextFromPre($('.output').eq(index).find('pre'));
  10810. }
  10811.  
  10812. testData[index + 1] = {
  10813. input: inputText.trim(),
  10814. output: outputText.trim()
  10815. };
  10816. });
  10817. return testData;
  10818. }
  10819.  
  10820. // 初始化自定义测试数据面板
  10821. function CustomTestInit() {
  10822. const url = window.location.href;
  10823.  
  10824. restoreText();
  10825.  
  10826. // 添加
  10827. $('#addCustomTest').click(function () {
  10828. var sampleDiv = $('<div class="sampleDiv">');
  10829. var inputTextarea = $('<p style="padding: 0px 5px;">input</p><textarea class="dynamicTextarea inputTextarea"></textarea>');
  10830. var outputTextarea = $('<p style="padding: 0px 5px;">output</p><textarea class="dynamicTextarea outputTextarea"></textarea>');
  10831. var deleteCustomTest = $(`<button type="button" class="deleteCustomTest">${closeIcon}</button>`);
  10832. sampleDiv.append(deleteCustomTest);
  10833. sampleDiv.append(inputTextarea);
  10834. sampleDiv.append(outputTextarea);
  10835. $('#customTests').append(sampleDiv);
  10836. });
  10837.  
  10838. // 实时保存文本内容到 IndexedDB 中
  10839. $(document).on('input', '.inputTextarea, .outputTextarea', function () {
  10840. OJBetter.common.database.transaction('rw', OJBetter.common.database.samplesData, function () {
  10841. var objectStore = OJBetter.common.database.samplesData;
  10842. var samples = {
  10843. url: url,
  10844. samples: []
  10845. };
  10846. var index = 0;
  10847. $('.sampleDiv').each(function () {
  10848. var $sampleDiv = $(this);
  10849. var inputTextarea = $sampleDiv.find('.inputTextarea');
  10850. var outputTextarea = $sampleDiv.find('.outputTextarea');
  10851. $sampleDiv.attr('data-index', index);
  10852. inputTextarea.attr('id', 'input' + index);
  10853. outputTextarea.attr('id', 'output' + index);
  10854. var sample = {
  10855. id: index,
  10856. input: inputTextarea.val(),
  10857. output: outputTextarea.val()
  10858. };
  10859. samples.samples.push(sample);
  10860. index++;
  10861. });
  10862. objectStore.put(samples);
  10863. });
  10864. });
  10865.  
  10866. // 删除
  10867. $(document).on('click', '.deleteCustomTest', function () {
  10868. var $sampleDiv = $(this).closest('.sampleDiv');
  10869. OJBetter.common.database.transaction('rw', OJBetter.common.database.samplesData, function () {
  10870. var objectStore = OJBetter.common.database.samplesData;
  10871. var index = parseInt($sampleDiv.attr('data-index'));
  10872. if (!isNaN(index)) {
  10873. objectStore.get(url).then(row => {
  10874. let samples = row.samples;
  10875. samples.splice(index, 1); // 移除第index个元素
  10876. objectStore.put({
  10877. url: url,
  10878. samples: samples
  10879. });
  10880. })
  10881. }
  10882. $sampleDiv.remove();
  10883. });
  10884. });
  10885.  
  10886. // 恢复保存的内容
  10887. function restoreText() {
  10888. OJBetter.common.database.transaction('r', OJBetter.common.database.samplesData, function () {
  10889. return OJBetter.common.database.samplesData.get(url);
  10890. }).then(function (data) {
  10891. if (data.samples && data.samples.length > 0) {
  10892. data.samples.forEach(function (item, index) {
  10893. var sampleDiv = $('<div class="sampleDiv">');
  10894. var inputTextarea = $(`<p style="padding: 0px 5px;">input</p><textarea id="input${index}" class="dynamicTextarea inputTextarea"></textarea>`);
  10895. var outputTextarea = $(`<p style="padding: 0px 5px;">output</p><textarea id="output${index}" class="dynamicTextarea outputTextarea"></textarea>`);
  10896. var deleteCustomTest = $(`<button type="button" class="deleteCustomTest">${closeIcon}</button>`);
  10897.  
  10898. inputTextarea.val(item.input);
  10899. outputTextarea.val(item.output);
  10900.  
  10901. sampleDiv.append(deleteCustomTest);
  10902. sampleDiv.append(inputTextarea);
  10903. sampleDiv.append(outputTextarea);
  10904. sampleDiv.attr('data-index', index)
  10905. $('#customTests').append(sampleDiv);
  10906. });
  10907. }
  10908. });
  10909. }
  10910. }
  10911.  
  10912. // 获取自定义测试数据
  10913. function getCustomTestData() {
  10914. const url = window.location.href;
  10915.  
  10916. return new Promise(function (resolve) {
  10917. var customTestData = {};
  10918. OJBetter.common.database.transaction('r', OJBetter.common.database.samplesData, function () {
  10919. return OJBetter.common.database.samplesData.get(url);
  10920. }).then(function (data) {
  10921. if (!data) resolve(customTestData);
  10922. if (data.samples && data.samples.length > 0) {
  10923. data.samples.forEach(function (item, index) {
  10924. customTestData[index + 1] = {
  10925. input: item.input,
  10926. output: item.output
  10927. };
  10928. });
  10929. }
  10930. resolve(customTestData);
  10931. });
  10932. });
  10933. }
  10934.  
  10935. // codeforces编译器参数列表
  10936. let officialLanguage = "";
  10937. function officialCompilerArgsChange(nowSelect) {
  10938. officialLanguage = nowSelect;
  10939. $('#CompilerArgsInput').prop("disabled", true);
  10940. }
  10941.  
  10942. // codeforces编译器通信
  10943. async function officialCompiler(code, input) {
  10944. const data = new FormData();
  10945. data.append('csrf_token', OJBetter.common.cf_csrf_token);
  10946. data.append('source', code);
  10947. data.append('tabSize', '4');
  10948. data.append('programTypeId', officialLanguage);
  10949. data.append('input', input);
  10950. data.append('output', '');
  10951. data.append('communityCode', '');
  10952. data.append('action', 'submitSourceCode');
  10953. data.append('programTypeId', officialLanguage);
  10954. data.append('sourceCode', code);
  10955.  
  10956. const requestOptions = {
  10957. method: 'POST',
  10958. url: `${OJBetter.common.hostAddress}/data/customtest`,
  10959. data: data,
  10960. headers: {
  10961. 'X-Csrf-Token': OJBetter.common.cf_csrf_token
  10962. }
  10963. };
  10964.  
  10965. const result = {
  10966. Errors: '',
  10967. Result: '',
  10968. Stats: ''
  10969. };
  10970.  
  10971. try {
  10972. const submitResponse = await OJB_GMRequest(requestOptions);
  10973. if (submitResponse.status !== 200 || !submitResponse.response) {
  10974. result.Errors = `${i18next.t('compiler.official.pushError', { ns: 'codeEditor' })}`;
  10975. return result;
  10976. }
  10977.  
  10978. const submitResult = JSON.parse(submitResponse.response);
  10979. const customTestSubmitId = submitResult.customTestSubmitId;
  10980.  
  10981. const verdictResponse = await OJB_promiseRetryWrapper(
  10982. getOfficialCompilerVerdict,
  10983. {
  10984. maxRetries: 10,
  10985. retryInterval: 500
  10986. },
  10987. customTestSubmitId
  10988. );
  10989. return verdictResponse;
  10990. } catch (error) {
  10991. result.Errors = error.message;
  10992. return result;
  10993. }
  10994. }
  10995.  
  10996. // 获取codeforces编译器的执行结果
  10997. async function getOfficialCompilerVerdict(customTestSubmitId) {
  10998. const newdata = new FormData();
  10999. newdata.append('csrf_token', OJBetter.common.cf_csrf_token);
  11000. newdata.append('action', 'getVerdict');
  11001. newdata.append('customTestSubmitId', customTestSubmitId);
  11002.  
  11003. const requestOptions = {
  11004. method: 'POST',
  11005. url: `${OJBetter.common.hostAddress}/data/customtest`,
  11006. data: newdata,
  11007. headers: {
  11008. 'X-Csrf-Token': OJBetter.common.cf_csrf_token
  11009. }
  11010. };
  11011.  
  11012. const responseDetails = await OJB_GMRequest(requestOptions);
  11013. if (responseDetails.status !== 200 || !responseDetails.response) {
  11014. throw new Error(`${i18next.t('compiler.official.getResultError', { ns: 'codeEditor' })}`);
  11015. }
  11016.  
  11017. const response = JSON.parse(responseDetails.response);
  11018. if (!response.stat) {
  11019. throw new Error('Verdict not ready, retrying...');
  11020. }
  11021.  
  11022. return {
  11023. Errors: response.verdict === "OK" ? null : response.verdict + '<br>' + response.output,
  11024. Result: response.output.replace(/\r\n/g, "\n"),
  11025. Stats: `Status: ${response.stat}`
  11026. };
  11027. }
  11028.  
  11029. // rextester编译器参数列表
  11030. let rextesterLanguage = "";
  11031. function rextesterCompilerArgsChange(nowSelect) {
  11032. let LanguageChoiceList = {
  11033. "4": "9", "6": "8", "7": "5", "9": "1", "13": "13", "19": "42", "20": "21", "28": "30", "31": "24", "32": "20",
  11034. "34": "17", "36": "4", "43": "6", "45": "7", "46": "4", "50": "7", "51": "9", "52": "27", "54": "7", "55": "23", "60": "4",
  11035. "61": "7", "65": "1", "67": "12", "70": "5", "73": "7", "74": "4", "75": "46", "77": "43", "79": "1", "80": "27", "83": "43", "87": "4"
  11036. }
  11037. let CompilerArgsList = {
  11038. "6": "-Wall -std=gnu99 -O2 -o a.out source_file.c",
  11039. "7": "-Wall -std=c++14 -O2 -o a.out source_file.cpp",
  11040. "20": "-o a.out source_file.go",
  11041. "27": "-Wall -std=c++14 -stdlib=libc++ -O2 -o a.out source_file.cpp",
  11042. "30": "source_file.d -ofa.out"
  11043. }
  11044. if (nowSelect in LanguageChoiceList) {
  11045. $('#RunTestButton').prop("disabled", false);
  11046. rextesterLanguage = LanguageChoiceList[nowSelect];
  11047. } else {
  11048. $('#RunTestButton').prop("disabled", true);
  11049. }
  11050. if (rextesterLanguage in CompilerArgsList) {
  11051. const rextesterCompilerArgs = CompilerArgsList[rextesterLanguage];
  11052. $('#CompilerArgsInput').val(rextesterCompilerArgs);
  11053. } else {
  11054. $('#CompilerArgsInput').val("");
  11055. }
  11056. }
  11057.  
  11058. // rextester编译器通信
  11059. async function rextesterCompiler(code, input) {
  11060. try {
  11061. const result = await OJB_promiseRetryWrapper(rextesterCompilerRequest, {
  11062. maxRetries: 5,
  11063. retryInterval: 500,
  11064. errorHandler: (err) => ({ Errors: err.message, Result: '', Stats: '' })
  11065. }, code, input);
  11066. return result;
  11067. } catch (error) {
  11068. return { Errors: error.message, Result: '', Stats: '' };
  11069. }
  11070. }
  11071.  
  11072. // rextester编译器请求方法
  11073. async function rextesterCompilerRequest(code, input) {
  11074. const data = new FormData();
  11075. data.append('LanguageChoiceWrapper', rextesterLanguage);
  11076. data.append('EditorChoiceWrapper', '1');
  11077. data.append('LayoutChoiceWrapper', '1');
  11078. data.append('Program', code);
  11079. data.append('CompilerArgs', $('#CompilerArgsInput').val());
  11080. data.append('Input', input);
  11081. data.append('ShowWarnings', 'false');
  11082. data.append('IsInEditMode', 'false');
  11083. data.append('IsLive', 'false');
  11084.  
  11085. const responseDetails = await OJB_GMRequest({
  11086. method: 'POST',
  11087. url: 'https://rextester.com/rundotnet/Run',
  11088. data: data
  11089. });
  11090.  
  11091. if (responseDetails.status !== 200 || !responseDetails.response) {
  11092. throw new Error(`${i18next.t('compiler.common.error', { ns: 'codeEditor' })}`);
  11093. }
  11094.  
  11095. const response = JSON.parse(responseDetails.response);
  11096. return {
  11097. Errors: response.Errors || '',
  11098. Result: response.Result || '',
  11099. Stats: response.Stats || ''
  11100. };
  11101. }
  11102.  
  11103. // wandbox编译器参数列表
  11104. var wandboxlist = JSON.parse(GM_getResourceText("wandboxlist"));
  11105. function wandboxCompilerArgsChange(nowSelect) {
  11106. let LanguageChoiceList = {
  11107. "6": "PHP", "7": "Python", "9": "C#", "12": "Haskell", "13": "Perl", "19": "OCaml",
  11108. "20": "Scala", "28": "D", "31": "Python", "32": "Go", "34": "JavaScript", "36": "Java", "40": "Python", "41": "Python",
  11109. "43": "C++", "50": "C++", "51": "Pascal", "52": "C++", "54": "C++", "60": "Java", "61": "C++", "65": "C#", "67": "Ruby",
  11110. "70": "Python", "73": "C++", "74": "Java", "75": "Rust", "79": "C#", "80": "C++", "87": "Java"
  11111. }
  11112.  
  11113. // 移除旧的
  11114. $('#CompilerChange').remove();
  11115.  
  11116. if (nowSelect in LanguageChoiceList) {
  11117. $('#RunTestButton').prop("disabled", false);
  11118. const Languagefiltered = wandboxlist.filter(obj => obj.language === LanguageChoiceList[nowSelect]);
  11119.  
  11120. // 创建编译器下拉框
  11121. let CompilerChange = $('<select id="CompilerChange" style="width: 100%;"></select>');
  11122.  
  11123. $('#CompilerSetting').show().append(CompilerChange);
  11124. for (let i = 0; i < Languagefiltered.length; i++) {
  11125. let Compiler = Languagefiltered[i];
  11126. let op = $("<option></option>")
  11127. .val(Compiler.name)
  11128. .text(Compiler["display-name"] + " " + Compiler.version);
  11129. $("#CompilerChange").append(op);
  11130. }
  11131.  
  11132. // 编译器参数刷新
  11133. function refreshCompilerArgs() {
  11134. var flags = '';
  11135. $("#CompilerBox").find("*").each(function () {
  11136. if ($(this).is("input[type='checkbox']")) {
  11137. let flag = $(this).prop("checked") ? $(this).val() : '';
  11138. flags += flag + (flag ? ' ' : '');
  11139. } else if ($(this).is("select") || $(this).is("input") || $(this).is("textarea")) {
  11140. let flag = $(this).val();
  11141. flags += flag + (flag ? ' ' : '');
  11142. }
  11143. });
  11144. $("#CompilerArgsInput").val(flags);
  11145. $("#CompilerArgsInput").prop("readonly", true); // 只读
  11146. }
  11147.  
  11148. // 编译器切换监听
  11149. CompilerChange.change(function () {
  11150. let selectedName = CompilerChange.val();
  11151. let Compiler = Languagefiltered.find(
  11152. (obj) => obj.name === selectedName
  11153. );
  11154.  
  11155. $("#CompilerArgsInput").val(); // 初始化编译器输入框
  11156.  
  11157. $("#CompilerBox").remove();
  11158. let div = $("<div id='CompilerBox'></div>");
  11159.  
  11160. let display_compile_command = $(`<input id='${Compiler.name}' value='${Compiler['display-compile-command']}' style="display:none;"}></input>`);
  11161. div.append(display_compile_command);
  11162.  
  11163. let switches = Compiler.switches;
  11164. for (let i = 0; i < switches.length; i++) {
  11165. let switche = switches[i];
  11166.  
  11167. if (switche.type == "single") {
  11168. let single = $(`
  11169. <div>
  11170. <input type='checkbox' id='${switche.name}' value='${switche['display-flags']}' ${switche.default ? 'checked' : ''}></input>
  11171. <label for='${switche.name}'>${switche['display-name']}</label>
  11172. </div>
  11173. `);
  11174. div.append(single);
  11175. single.find("input").change(function () {
  11176. refreshCompilerArgs();
  11177. });
  11178. } else if (switche.type == "select") {
  11179. let select = $(`<select id='${switche.name}'></select>`);
  11180. select.data('previousValue', switche.options[0]['display-flags']);
  11181. div.append(select);
  11182. for (let i = 0; i < switche.options.length; i++) {
  11183. let option = switche.options[i];
  11184. let op = $("<option></option>")
  11185. .val(option['display-flags'])
  11186. .text(option['display-name']);
  11187. select.append(op);
  11188. }
  11189. select.change(function () {
  11190. refreshCompilerArgs();
  11191. });
  11192. }
  11193. }
  11194.  
  11195. if (Compiler['compiler-option-raw'] == true) {
  11196. let textarea = $(`<textarea id="compiler_option_raw" placeholder="Raw compiler options" style="resize: vertical;"></textarea>`);
  11197. div.append(textarea);
  11198. textarea.on('input', function () {
  11199. refreshCompilerArgs();
  11200. });
  11201. }
  11202. if (Compiler['runtime-option-raw'] == true) {
  11203. let textarea = $(`<textarea id="runtime_option_raw" placeholder="Raw runtime options" style="resize: vertical;"></textarea>`);
  11204. div.append(textarea);
  11205. textarea.on('input', function () {
  11206. refreshCompilerArgs();
  11207. });
  11208. }
  11209. $("#CompilerSetting").append(div);
  11210.  
  11211. refreshCompilerArgs(); // 初始化
  11212. });
  11213.  
  11214. CompilerChange.trigger("change"); // 初始化
  11215. } else {
  11216. $('#RunTestButton').prop("disabled", true);
  11217. }
  11218. }
  11219.  
  11220. // wandbox编译器通信
  11221. async function wandboxCompiler(code, input) {
  11222. try {
  11223. const result = await OJB_promiseRetryWrapper(wandboxCompilerRequest, {
  11224. maxRetries: 5,
  11225. retryInterval: 500,
  11226. errorHandler: (err) => ({ Errors: err.message, Result: '', Stats: '' })
  11227. }, code, input);
  11228. return result;
  11229. } catch (error) {
  11230. return { Errors: error.message, Result: '', Stats: '' };
  11231. }
  11232. }
  11233.  
  11234. // wandbox编译器请求方法
  11235. async function wandboxCompilerRequest(code, input) {
  11236. const data = {
  11237. code: code,
  11238. codes: [],
  11239. compiler: $('#CompilerChange').val().replace($('#compiler_option_raw').val(), '').replace($('#runtime_option_raw').val(), ''),
  11240. 'compiler-option-raw': $('#compiler_option_raw').val(),
  11241. 'runtime-option-raw': $('#runtime_option_raw').val(),
  11242. options: $("#CompilerArgsInput").val(),
  11243. description: '',
  11244. stdin: input,
  11245. title: ''
  11246. };
  11247.  
  11248. const responseDetails = await OJB_GMRequest({
  11249. method: 'POST',
  11250. url: 'https://wandbox.org/api/compile.json',
  11251. data: JSON.stringify(data),
  11252. headers: {
  11253. 'Content-Type': 'application/json'
  11254. }
  11255. });
  11256.  
  11257. if (responseDetails.status !== 200 || !responseDetails.response) {
  11258. throw new Error(`${i18next.t('compiler.common.error', { ns: 'codeEditor' })}`);
  11259. }
  11260.  
  11261. const response = JSON.parse(responseDetails.response);
  11262. return {
  11263. Errors: response.compiler_error === "" ? response.signal : response.compiler_error,
  11264. Result: response.program_output || '',
  11265. Stats: response.status === "0" ? "Finish" : "Error"
  11266. };
  11267. }
  11268.  
  11269. // 更改编译器参数
  11270. function changeCompilerArgs(nowSelect) {
  11271. if (OJBetter.monaco.onlineCompilerChoice == "official") {
  11272. officialCompilerArgsChange(nowSelect);
  11273. } else if (OJBetter.monaco.onlineCompilerChoice == "rextester") {
  11274. rextesterCompilerArgsChange(nowSelect);
  11275. } else if (OJBetter.monaco.onlineCompilerChoice == "wandbox") {
  11276. wandboxCompilerArgsChange(nowSelect);
  11277. }
  11278. }
  11279.  
  11280. // 在线编译器通信
  11281. async function onlineCompilerConnect(code, input) {
  11282. if (OJBetter.monaco.onlineCompilerChoice == "official") {
  11283. return await officialCompiler(code, input);
  11284. } else if (OJBetter.monaco.onlineCompilerChoice == "rextester") {
  11285. return await rextesterCompiler(code, input);
  11286. } else if (OJBetter.monaco.onlineCompilerChoice == "wandbox") {
  11287. return await wandboxCompiler(code, input);
  11288. }
  11289. }
  11290.  
  11291. // 差异对比
  11292. function codeDiff(expectedText, actualText) {
  11293. // 将文本按行拆分
  11294. const expectedLines = expectedText ? expectedText.split('\n') : [];
  11295. const actualLines = actualText ? actualText.split('\n') : [];
  11296.  
  11297. const output = document.createElement('div');
  11298.  
  11299. const createLineElement = (lineNo, contentElement) => {
  11300. const lineDiv = document.createElement('div');
  11301. lineDiv.className = 'diffLine';
  11302.  
  11303. const lineNoDiv = document.createElement('div');
  11304. lineNoDiv.className = 'lineNo';
  11305. lineNoDiv.textContent = lineNo;
  11306.  
  11307. lineDiv.appendChild(lineNoDiv);
  11308. lineDiv.appendChild(contentElement);
  11309.  
  11310. return lineDiv;
  11311. };
  11312.  
  11313. const createContentElement = (isEquals = true, expected = null, removed = null) => {
  11314. const contentDiv = document.createElement('div');
  11315. contentDiv.className = 'lineContent';
  11316.  
  11317. if (isEquals) {
  11318. contentDiv.textContent = expected;
  11319. } else {
  11320. if (removed != null) {
  11321. const removedSpan = document.createElement('span');
  11322. removedSpan.className = 'removed';
  11323. removedSpan.textContent = removed;
  11324. contentDiv.appendChild(removedSpan);
  11325. }
  11326. if (expected != null) {
  11327. const addedSpan = document.createElement('span');
  11328. addedSpan.className = 'added';
  11329. addedSpan.textContent = expected;
  11330. contentDiv.appendChild(addedSpan);
  11331. }
  11332. }
  11333.  
  11334. return contentDiv;
  11335. };
  11336.  
  11337. let index = 1;
  11338.  
  11339. expectedLines.forEach((expectedLine, i) => {
  11340. const actualLine = actualLines[i];
  11341. if (actualLine === undefined) {
  11342. output.appendChild(createLineElement(index++, createContentElement(false, expectedLine)));
  11343. } else if (expectedLine === actualLine) {
  11344. output.appendChild(createLineElement(index++, createContentElement(true, expectedLine)));
  11345. } else {
  11346. output.appendChild(createLineElement(index++, createContentElement(false, expectedLine, actualLine)));
  11347. }
  11348. });
  11349.  
  11350. // 处理多余的 actualLines
  11351. for (let i = expectedLines.length; i < actualLines.length; i++) {
  11352. output.appendChild(createLineElement(index++, createContentElement(false, null, actualLines[i])));
  11353. }
  11354.  
  11355. return output.innerHTML;
  11356. }
  11357.  
  11358. // 内容类型常量
  11359. const TestCaseContentType = {
  11360. TERMINAL: 'terminal',
  11361. DIFF: 'diff',
  11362. NO_DIFF: 'no_diff',
  11363. SUCCESS: 'success'
  11364. };
  11365.  
  11366. // 样例测试状态类
  11367. class TestCaseStatus {
  11368. constructor(item, prefix) {
  11369. this.testCase = $(`<div class="test-case"></div>`);
  11370. this.item = item;
  11371. this.prefix = prefix;
  11372. this.titleElement = $(`<div class="test-case-title">${this.prefix} ${this.item}</div>`);
  11373. this.statusElement = $(`<div class="test-case-status"></div>`);
  11374. this.contentElement = $(`<div class="test-case-content"></div>`);
  11375. this.judgeElement = $(`<div class="test-case-judge"></div>`);
  11376. this.testCase.append(this.titleElement, this.statusElement, this.contentElement, this.judgeElement);
  11377. $('#statePanel').append(this.testCase);
  11378. this.setStatus('Queued', 'queued');
  11379. }
  11380.  
  11381. setTitle(title) {
  11382. this.titleElement.text(title);
  11383. }
  11384.  
  11385. setStatus(text, status) {
  11386. this.statusElement.text(text).removeClass('queued running success error').addClass(status);
  11387. }
  11388.  
  11389. setContent(content, type) {
  11390. // 如果内容类型为SUCCESS,隐藏内容元素并提前返回
  11391. if (type === TestCaseContentType.SUCCESS) {
  11392. this.contentElement.hide();
  11393. return;
  11394. }
  11395.  
  11396. // 根据内容类型创建内容元素
  11397. const createContentElementByType = (content, type) => {
  11398. let contentElement;
  11399. switch (type) {
  11400. case TestCaseContentType.TERMINAL:
  11401. // 为TERMINAL类型创建一个新的终端容器
  11402. contentElement = $(`<div class="terminal-container" style="overflow: auto;"></div>`);
  11403. break;
  11404. case TestCaseContentType.DIFF:
  11405. case TestCaseContentType.NO_DIFF:
  11406. // 为DIFF和NO_DIFF类型创建相应的内容元素,并添加差异说明
  11407. const className = type === TestCaseContentType.DIFF ? "output_diff" : "output_no_diff";
  11408. contentElement = $(`<pre class="${className}">${content}</pre>`);
  11409. appendDiffNote();
  11410. break;
  11411. default:
  11412. throw new Error("Unsupported content type.");
  11413. }
  11414. return contentElement;
  11415. };
  11416.  
  11417. // 初始化终端
  11418. const initializeTerminal = (content, contentElement) => {
  11419. const term = new Terminal({ rows: 10, cols: 150 });
  11420. term.setOption('theme', { background: '#2d2e2c' });
  11421. term.setOption('convertEol', true); // 将换行符\n转换为\r\n
  11422. term.write(content);
  11423. term.open(contentElement.get(0));
  11424. };
  11425.  
  11426. // 添加差异说明
  11427. const appendDiffNote = () => {
  11428. const diffNote = $(`<div class="diff_note">${i18next.t('resultBlock.diffNote', { ns: 'codeEditor' })}</div>`);
  11429. this.testCase.append(diffNote);
  11430. };
  11431.  
  11432. // 创建并追加内容元素
  11433. const contentElement = createContentElementByType(content, type);
  11434. this.contentElement.append(contentElement);
  11435.  
  11436. // 如果内容类型为TERMINAL,初始化并打开终端
  11437. if (type === TestCaseContentType.TERMINAL) {
  11438. initializeTerminal(content, contentElement);
  11439. }
  11440. }
  11441.  
  11442. setJudge(judge) {
  11443. this.judgeElement.text(judge);
  11444. }
  11445. }
  11446.  
  11447. // 样例测试函数
  11448. async function runCode(event, runButton, sourceDiv, submitDiv) {
  11449. event.preventDefault();
  11450. const statePanel = $('#statePanel').show().empty();
  11451. const testData = getTestData();
  11452. const customTestData = await getCustomTestData();
  11453. const totalTests = Object.keys(customTestData).length + Object.keys(testData).length;
  11454.  
  11455. let passedTests = 0;
  11456. let failedTests = 0;
  11457. let hasError = false;
  11458.  
  11459. // 定义一个对象队列,包括创建的样例块实例和对应的样例数据
  11460. const queue = [];
  11461.  
  11462. // 先生成各个样例的块,并显示排队中,将创建的各个对象存到队列中,以便后面更新
  11463. for (const [item, data] of Object.entries(customTestData)) {
  11464. const testCase = new TestCaseStatus(item, i18next.t('resultBlock.title.custom', { ns: 'codeEditor' }));
  11465. queue.push({ testCase, data });
  11466. }
  11467.  
  11468. if (!$('#onlyCustomTest').prop('checked')) {
  11469. for (const [item, data] of Object.entries(testData)) {
  11470. const testCase = new TestCaseStatus(item, i18next.t('resultBlock.title.sample', { ns: 'codeEditor' }));
  11471. queue.push({ testCase, data });
  11472. }
  11473. }
  11474.  
  11475. // 测试函数
  11476. const runTest = async (testCase, data, index) => {
  11477. runButton.setButtonState('running', `${index}/${totalTests}`);
  11478.  
  11479. testCase.setStatus('Running', 'running');
  11480. const result = await onlineCompilerConnect(sourceDiv.val(), data.input);
  11481.  
  11482. if (result.Errors) {
  11483. testCase.setStatus('Compilation error or Time limit', 'error');
  11484. testCase.setContent(result.Errors, TestCaseContentType.TERMINAL);
  11485. hasError = true;
  11486. } else if (result.Result.trim() === data.output.trim()) {
  11487. testCase.setStatus('Accepted', 'success');
  11488. testCase.setContent('The output is correct.', TestCaseContentType.SUCCESS);
  11489. passedTests++;
  11490. } else {
  11491. testCase.setStatus('Wrong Answer', 'error');
  11492. const diffContent = $('#DontShowDiff').prop('checked') ? result.Result.trim() : codeDiff(data.output.trim(), result.Result.trim());
  11493. const contentType = $('#DontShowDiff').prop('checked') ? TestCaseContentType.NO_DIFF : TestCaseContentType.DIFF;
  11494. testCase.setContent(diffContent, contentType);
  11495. failedTests++;
  11496. }
  11497.  
  11498. const judgeStats = `${i18next.t('resultBlock.state', { ns: 'codeEditor' })}${result.Stats}`;
  11499. testCase.setJudge(judgeStats);
  11500.  
  11501. await OJB_delay(500); // 等待500毫秒
  11502. };
  11503.  
  11504. // 对队列中的对象进行测试
  11505. for (let i = 0; i < queue.length; i++) {
  11506. const { testCase, data } = queue[i];
  11507. await runTest(testCase, data, i + 1);
  11508. }
  11509.  
  11510. // 测试完成后更新按钮状态
  11511. if (hasError) {
  11512. runButton.setButtonState('error', i18next.t('runTestButton.error', { ns: 'codeEditor' }));
  11513. } else if (failedTests > 0) {
  11514. runButton.setButtonState('error', `${passedTests}/${totalTests} ` + i18next.t('runTestButton.partial', { ns: 'codeEditor' }));
  11515. } else {
  11516. runButton.setButtonState('success', i18next.t('runTestButton.success', { ns: 'codeEditor' }));
  11517. }
  11518. }
  11519.  
  11520. /**
  11521. * 添加题目页代码编辑器
  11522. * @returns
  11523. */
  11524. async function addProblemPageCodeEditor() {
  11525. if (typeof ace === 'undefined') {
  11526. const loadingMessage = new LoadingMessage();
  11527. loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('error.codeEditor.load', { ns: 'alert' })}`, 'error');
  11528. return; // 因为Codeforces设定的是未登录(不可用)时不能访问提交页,也不会加载ace库
  11529. }
  11530.  
  11531. // 获取提交页链接
  11532. const href = window.location.href;
  11533. let submitUrl;
  11534. if (/\/problemset\//.test(href)) {
  11535. // problemset
  11536. submitUrl = OJBetter.common.hostAddress + '/problemset/submit';
  11537. } else if (/\/gym\//.test(href)) {
  11538. // gym 题目
  11539. submitUrl = OJBetter.common.hostAddress + '/gym/' + ((href) => {
  11540. const regex = /\/gym\/(?<num>[0-9a-zA-Z]*?)\/problem\//;
  11541. const match = href.match(regex);
  11542. return match && match.groups.num;
  11543. })(href) + '/submit';
  11544. } else if (OJBetter.typeOfPage.is_acmsguru) {
  11545. // acmsguru 题目
  11546. submitUrl = href.replace(/\/problemsets[A-Za-z0-9\/#]*/, "/problemsets/acmsguru/submit");
  11547. } else {
  11548. submitUrl = href.replace(/\/problem[A-Za-z0-9\/#]*/, "/submit");
  11549. }
  11550.  
  11551. // 获取提交页HTML
  11552. let cloneHTML = await getSubmitHTML(submitUrl);
  11553.  
  11554. // 创建
  11555. let form = await createCodeEditorForm(submitUrl, cloneHTML);
  11556. let selectLang = form.selectLang;
  11557. let submitButton = form.submitButton;
  11558. let runButton = form.runButton;
  11559.  
  11560. // 初始化
  11561. CustomTestInit(); // 自定义测试数据面板
  11562. selectLang.val(OJBetter.monaco.compilerSelection);
  11563. changeMonacoLanguage(form);
  11564.  
  11565. selectLang.on('change', () => changeMonacoLanguage(form)); // 编辑器语言切换监听
  11566.  
  11567. // 样例测试
  11568. runButton.on('click', (event) => runCode(event, runButton, form.sourceDiv, form.submitDiv))
  11569. .setHoverRedo();
  11570.  
  11571. // 提交
  11572. submitButton.on('click', async function (event) {
  11573. event.preventDefault();
  11574. if (OJBetter.monaco.setting.isCodeSubmitDoubleConfirm) {
  11575. const submit = await OJB_createDialog(
  11576. i18next.t('submitCode.title', { ns: 'dialog' }),
  11577. i18next.t('submitCode.content', { ns: 'dialog' }),
  11578. [
  11579. i18next.t('submitCode.buttons.0', { ns: 'dialog' }),
  11580. i18next.t('submitCode.buttons.1', { ns: 'dialog' })
  11581. ]
  11582. ); //提交确认
  11583. if (submit) {
  11584. submitButton.after(`<img class="OJBetter_loding" src="//codeforces.org/s/84141/images/ajax-loading-24x24.gif">`);
  11585. $('#OJBetter_SubmitForm').submit();
  11586. } else {
  11587. submitButton.addClass('disabled');
  11588. setTimeout(function () {
  11589. submitButton.removeClass('disabled');
  11590. }, 300);
  11591. }
  11592. } else {
  11593. $('#OJBetter_SubmitForm').submit();
  11594. }
  11595. });
  11596. }
  11597.  
  11598. /**
  11599. * 获取翻译服务目标语言的对应代码
  11600. * @param {string} serverName 服务名称
  11601. * @returns {string} 目标语言,如果没有对应代码则返回中文
  11602. */
  11603. function getTargetLanguage(serverName) {
  11604. let targetLanguage = OJBetter.supportList.translationSupport[serverName][OJBetter.translation.targetLang];
  11605. if (targetLanguage) return targetLanguage;
  11606. else return OJBetter.supportList.translationSupport[serverName]['zh'];
  11607. }
  11608.  
  11609. /**
  11610. * 将文本中Markdown格式的加粗**转换成HTML格式。
  11611. * @param {string} text 文本
  11612. * @returns {string} 替换后的字符串
  11613. */
  11614. function convertBoldMarkdownToHTML(text) {
  11615. return text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
  11616. }
  11617.  
  11618. /**
  11619. * 将文本中Markdown格式的链接文本转换成HTML格式。
  11620. * @param {string} text 文本
  11621. * @returns {string} 替换后的字符串
  11622. */
  11623. function convertLinksMarkdownToHTML(text) {
  11624. return text.replace(/(?<!!)\[(.*?)\]\(([^"]*?)("(.*?)")*\)/g, '<a href="$2" title="$4">$1</a>');
  11625. }
  11626.  
  11627. /**
  11628. * 将HTML格式的加粗文本转换回Markdown格式。
  11629. * @param {string} text 文本
  11630. * @returns {string} 替换后的字符串
  11631. */
  11632. function convertBoldHTMLToMarkdown(text) {
  11633. return text.replace(/<strong>(.*?)<\/strong>/g, '**$1**');
  11634. }
  11635.  
  11636. /**
  11637. * 将HTML格式的链接文本转换回Markdown格式。
  11638. * @param {string} html - 包含HTML链接标签<a>的字符串。
  11639. * @returns {string} 转换后的字符串,其中HTML链接标签被替换为Markdown的链接语法。
  11640. */
  11641. function convertLinksHTMLToMarkdown(html) {
  11642. return html.replace(/<a href="([^"]*)"( title="([^"]*)")*>([^<]+)<\/a>/g, '[$4]($1 "$3")');
  11643. }
  11644.  
  11645. /**
  11646. * DeepL翻译
  11647. * @param {string} raw 原文
  11648. * @returns {Promise<TranslateResult>} 翻译结果对象
  11649. */
  11650. async function translate_deepl(raw) {
  11651. const id = (Math.floor(Math.random() * 99999) + 100000) * 1000;
  11652. const data = {
  11653. jsonrpc: '2.0',
  11654. method: 'LMT_handle_texts',
  11655. id,
  11656. params: {
  11657. splitting: 'newlines',
  11658. lang: {
  11659. source_lang_user_selected: 'auto',
  11660. target_lang: getTargetLanguage('deepl'),
  11661. },
  11662. texts: [{
  11663. text: raw,
  11664. requestAlternatives: 3
  11665. }],
  11666. timestamp: getTimeStamp(raw.split('i').length - 1)
  11667. }
  11668. }
  11669. let postData = JSON.stringify(data);
  11670. if ((id + 5) % 29 === 0 || (id + 3) % 13 === 0) {
  11671. postData = postData.replace('"method":"', '"method" : "');
  11672. } else {
  11673. postData = postData.replace('"method":"', '"method": "');
  11674. }
  11675. const options = {
  11676. method: 'POST',
  11677. url: 'https://www2.deepl.com/jsonrpc',
  11678. data: postData,
  11679. headers: {
  11680. 'Content-Type': 'application/json',
  11681. 'Host': 'www2.deepl.com',
  11682. 'Origin': 'https://www.deepl.com',
  11683. 'Referer': 'https://www.deepl.com/',
  11684. },
  11685. anonymous: true,
  11686. nocache: true,
  11687. }
  11688. return await BaseTranslate(options, res => JSON.parse(res).result.texts[0].text, res => {
  11689. const resObj = {
  11690. status: true,
  11691. message: 'ok'
  11692. };
  11693. if (res.includes('"error":{"code":1042912,"message":"Too many requests"}')) {
  11694. resObj.status = false;
  11695. resObj.message = i18next.t('error.deepl429', { ns: 'translator' }); // Too many requests 提示
  11696. return resObj;
  11697. };
  11698. return resObj;
  11699. });
  11700. }
  11701.  
  11702. /**
  11703. * 使用 DeepL Free API 进行翻译
  11704. * @param {string} raw 原文
  11705. * @returns {Promise<TranslateResult>} 翻译结果对象
  11706. */
  11707. async function translate_deepl_api_free(raw) {
  11708. const data = JSON.stringify({
  11709. text: [raw],
  11710. target_lang: getTargetLanguage('deepl'),
  11711. split_sentences: '1',
  11712. ...(OJBetter.deepl.enableEmphasisProtection || OJBetter.deepl.enableLinkProtection ? { tag_handling: 'html' } : {}),
  11713. ...Object.assign({}, ...OJBetter.deepl.config.data)
  11714. });
  11715.  
  11716. const options = {
  11717. method: "POST",
  11718. url: OJBetter.deepl.config.proxy || "https://api-free.deepl.com/v2/translate",
  11719. headers: {
  11720. "Authorization": `DeepL-Auth-Key ${OJBetter.deepl.config.key}`,
  11721. "Content-Type": "application/json",
  11722. ...Object.assign({}, ...OJBetter.deepl.config.header)
  11723. },
  11724. data: data,
  11725. onload: response => response.responseText,
  11726. onerror: error => console.error(error)
  11727. };
  11728.  
  11729. return await BaseTranslate(options, res => JSON.parse(res).translations[0].text);
  11730. }
  11731.  
  11732. /**
  11733. * 使用 DeepL Pro API 进行翻译
  11734. * @param {string} raw 原文
  11735. * @returns {Promise<TranslateResult>} 翻译结果对象
  11736. */
  11737. async function translate_deepl_api_pro(raw) {
  11738. const data = JSON.stringify({
  11739. text: [raw],
  11740. target_lang: getTargetLanguage('deepl'),
  11741. split_sentences: '1',
  11742. ...(OJBetter.deepl.enableEmphasisProtection || OJBetter.deepl.enableLinkProtection ? { tag_handling: 'html' } : {}),
  11743. ...Object.assign({}, ...OJBetter.deepl.config.data)
  11744. });
  11745.  
  11746. const options = {
  11747. method: "POST",
  11748. url: OJBetter.deepl.config.proxy || "https://api.deepl.com/v2/translate",
  11749. headers: {
  11750. "Authorization": `DeepL-Auth-Key ${OJBetter.deepl.config.key}`,
  11751. "Content-Type": "application/json",
  11752. ...Object.assign({}, ...OJBetter.deepl.config.header)
  11753. },
  11754. data: data,
  11755. onload: response => response.responseText,
  11756. onerror: error => console.error(error)
  11757. };
  11758.  
  11759. return await BaseTranslate(options, res => JSON.parse(res).translations[0].text);
  11760. }
  11761.  
  11762. /**
  11763. * 使用 DeepLX 进行翻译
  11764. * @param {String} text 原文
  11765. * @returns {Promise<TranslateResult>} 翻译结果对象
  11766. */
  11767. async function translate_deeplx(text) {
  11768. const options = {
  11769. method: "POST",
  11770. url: OJBetter.deepl.config.proxy || 'https://api.deeplx.org/translate',
  11771. data: JSON.stringify({
  11772. "text": text,
  11773. "source_lang": "EN",
  11774. "target_lang": getTargetLanguage('deepl'),
  11775. }),
  11776. headers: {
  11777. 'Content-Type': 'application/json',
  11778. ...(OJBetter.deepl.config.key ? { Authorization: `Bearer ${OJBetter.deepl.config.key}` } : {})
  11779. },
  11780. responseType: "json",
  11781. };
  11782.  
  11783. return await BaseTranslate(options, res => {
  11784. const parsedResponse = JSON.parse(res);
  11785. if (parsedResponse.code === 200 && parsedResponse.data) {
  11786. return parsedResponse.data;
  11787. } else {
  11788. throw new Error('Translation failed or invalid response format.');
  11789. }
  11790. });
  11791. }
  11792.  
  11793. function getTimeStamp(iCount) {
  11794. const ts = Date.now();
  11795. if (iCount !== 0) {
  11796. iCount = iCount + 1;
  11797. return ts - (ts % iCount) + iCount;
  11798. } else {
  11799. return ts;
  11800. }
  11801. }
  11802.  
  11803. /**
  11804. * 讯飞听见翻译
  11805. * @param {String} text 要翻译的文本
  11806. * @returns {Promise<TranslateResult>} 翻译结果对象
  11807. */
  11808. async function translate_iflyrec(text) {
  11809. const options = {
  11810. method: "POST",
  11811. url: 'https://www.iflyrec.com/TranslationService/v1/textTranslation',
  11812. data: JSON.stringify({
  11813. "from": "2",
  11814. "to": getTargetLanguage('iflyrec'),
  11815. "contents": [{
  11816. "text": text,
  11817. "frontBlankLine": 0
  11818. }]
  11819. }),
  11820. anonymous: true,
  11821. headers: {
  11822. 'Content-Type': 'application/json',
  11823. 'Origin': 'https://www.iflyrec.com',
  11824. },
  11825. responseType: "json",
  11826. };
  11827. return await BaseTranslate(options, res => JSON.parse(res).biz[0].translateResult.replace(/\\n/g, "\n\n"));
  11828. }
  11829.  
  11830. /**
  11831. * 有道翻译
  11832. * @param {string} raw 原文
  11833. * @returns {Promise<TranslateResult>} 翻译结果对象
  11834. */
  11835. async function translate_youdao_mobile(raw) {
  11836. const options = {
  11837. method: "POST",
  11838. url: 'http://m.youdao.com/translate',
  11839. data: "inputtext=" + encodeURIComponent(raw) + "&type=" + getTargetLanguage('youdao'),
  11840. anonymous: true,
  11841. headers: {
  11842. "Content-Type": "application/x-www-form-urlencoded",
  11843. 'Host': 'm.youdao.com',
  11844. 'Origin': 'http://m.youdao.com',
  11845. 'Referer': 'http://m.youdao.com/translate',
  11846. }
  11847. }
  11848. return await BaseTranslate(options,
  11849. res => {
  11850. const array = /id="translateResult">\s*?<li>([\s\S]*?)<\/li>\s*?<\/ul/.exec(res);
  11851. if (array && array.length > 1) {
  11852. return array[1];
  11853. } else {
  11854. return res;
  11855. }
  11856. },
  11857. res => {
  11858. const resObj = {
  11859. status: true,
  11860. message: 'ok'
  11861. };
  11862. if (res.includes('<title>413 Request Entity Too Large</title>')) {
  11863. resObj.status = false;
  11864. resObj.message = i18next.t('error.youdao413', { ns: 'translator' }); // Request Entity Too Large 提示
  11865. return resObj;
  11866. };
  11867. return resObj;
  11868. })
  11869. }
  11870.  
  11871. /**
  11872. * 谷歌翻译
  11873. * @param {string} raw 原文
  11874. * @returns {Promise<TranslateResult>} 翻译结果对象
  11875. */
  11876. async function translate_gg(raw) {
  11877. const params = `tl=${getTargetLanguage('google')}&q=${encodeURIComponent(raw)}`;
  11878. const options = {
  11879. method: "GET",
  11880. url: `https://translate.google.com/m?${params}`,
  11881. }
  11882. return await BaseTranslate(options,
  11883. res => $(res).filter('.result-container').text() || $(res).find('.result-container').text());
  11884. }
  11885.  
  11886. /**
  11887. * 彩云翻译预处理
  11888. */
  11889. async function translate_caiyun_startup() {
  11890. const browser_id = CryptoJS.MD5(Math.random().toString()).toString();
  11891. sessionStorage.setItem('caiyun_id', browser_id);
  11892. const options = {
  11893. method: "POST",
  11894. url: 'https://api.interpreter.caiyunai.com/v1/user/jwt/generate',
  11895. headers: {
  11896. "Content-Type": "application/json",
  11897. "X-Authorization": "token:qgemv4jr1y38jyq6vhvi",
  11898. "Origin": "https://fanyi.caiyunapp.com",
  11899. },
  11900. data: JSON.stringify({ browser_id }),
  11901. }
  11902. const res = await OJB_GMRequest(options);
  11903. sessionStorage.setItem('caiyun_jwt', JSON.parse(res.responseText).jwt);
  11904. }
  11905.  
  11906. /**
  11907. * 彩云翻译
  11908. * @param {string} raw 原文
  11909. * @returns {Promise<TranslateResult>} 翻译结果对象
  11910. */
  11911. async function translate_caiyun(raw) {
  11912. const source = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm";
  11913. const dic = [..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"].reduce((dic, current, index) => { dic[current] = source[index]; return dic }, {});
  11914. // 解码
  11915. const decodeUnicode = str => {
  11916. const decoder = new TextDecoder();
  11917. const data = Uint8Array.from(atob(str), c => c.charCodeAt(0));
  11918. return decoder.decode(data);
  11919. };
  11920. const decoder = line => decodeUnicode([...line].map(i => dic[i] || i).join(""));
  11921. const options = {
  11922. method: "POST",
  11923. url: 'https://api.interpreter.caiyunai.com/v1/translator',
  11924. data: JSON.stringify({
  11925. "source": raw.split('\n'),
  11926. "trans_type": getTargetLanguage('caiyun'),
  11927. "detect": true,
  11928. "browser_id": sessionStorage.getItem('caiyun_id')
  11929. }),
  11930. headers: {
  11931. "X-Authorization": "token:qgemv4jr1y38jyq6vhvi",
  11932. "T-Authorization": sessionStorage.getItem('caiyun_jwt')
  11933. }
  11934. }
  11935. return await BaseTranslate(options, res => JSON.parse(res).target.map(decoder).join('\n'))
  11936. }
  11937.  
  11938. /**
  11939. * ChatGPT
  11940. * @param {string} raw 原文
  11941. * @returns {Promise<TranslateResult>} 翻译结果对象
  11942. */
  11943. async function translate_openai(raw) {
  11944. const modelDefault = 'gpt-3.5-turbo';
  11945. const lang = getTargetLanguage('openai');
  11946. const prompt = (OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru) ?
  11947. i18next.t('chatgpt_prompt.notLaTeX', { ns: 'translator', transTargetLang: lang, lng: OJBetter.translation.targetLang }) :
  11948. i18next.t('chatgpt_prompt.common', { ns: 'translator', transTargetLang: lang, lng: OJBetter.translation.targetLang });
  11949. const data = {
  11950. model: OJBetter.chatgpt.config.model || modelDefault,
  11951. messages: [{
  11952. role: "user",
  11953. content: prompt + raw
  11954. }],
  11955. temperature: 0.7,
  11956. ...Object.assign({}, ...OJBetter.chatgpt.config.data)
  11957. }
  11958. const options = {
  11959. method: "POST",
  11960. url: OJBetter.chatgpt.config.proxy || 'https://api.openai.com/v1/chat/completions',
  11961. data: JSON.stringify(data),
  11962. responseType: 'json',
  11963. headers: {
  11964. 'Content-Type': 'application/json',
  11965. 'Authorization': 'Bearer ' + OJBetter.chatgpt.config.key,
  11966. ...Object.assign({}, ...OJBetter.chatgpt.config.header)
  11967. }
  11968. }
  11969. return await BaseTranslate(options,
  11970. res => res,
  11971. undefined,
  11972. response => response.response.choices[0].message.content);
  11973. }
  11974.  
  11975. /**
  11976. * ChatGPT 流式传输
  11977. * @param {string} raw 原文
  11978. * @param {TranslateDiv} translateDiv 翻译结果面板
  11979. * @returns {Promise<TranslateResult>} 翻译结果对象
  11980. */
  11981. async function translate_openai_stream(raw, translateDiv) {
  11982. const result = {
  11983. done: true,
  11984. checkPassed: null,
  11985. response: null,
  11986. responseText: null,
  11987. text: "",
  11988. error: null,
  11989. message: null
  11990. };
  11991. const helpText = i18next.t('error.basic', { ns: 'translator' }); // 基本帮助提示信息
  11992. try {
  11993. for await (const delta of openai_stream(raw)) {
  11994. result.text += delta;
  11995. // 翻译结果面板更新
  11996. translateDiv.updateTranslateDiv(result.text, !(OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru), false);
  11997. }
  11998. return result;
  11999. } catch (err) {
  12000. console.warn(err);
  12001. result.error = {
  12002. message: err.message || null,
  12003. stack: err.stack ? err.stack.replace(/\n/g, '<br>').replace(/\s/g, '&nbsp;') : null,
  12004. enumerable: err,
  12005. source: 'openai_stream'
  12006. };
  12007. result.message = `${i18next.t('error.GMRequest', { ns: 'translator' })}${helpText}`;
  12008. }
  12009.  
  12010. return result;
  12011. }
  12012.  
  12013. /**
  12014. * 流式传输
  12015. * @param {string} raw 原文
  12016. * @returns {AsyncGenerator<string>} 返回 AsyncGenerator
  12017. */
  12018. async function* openai_stream(raw) {
  12019. const modelDefault = 'gpt-3.5-turbo';
  12020. const lang = getTargetLanguage('openai');
  12021. const prompt = (OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru) ?
  12022. i18next.t('chatgpt_prompt.notLaTeX', { ns: 'translator', transTargetLang: lang, lng: OJBetter.translation.targetLang }) :
  12023. i18next.t('chatgpt_prompt.common', { ns: 'translator', transTargetLang: lang, lng: OJBetter.translation.targetLang });
  12024. const data = {
  12025. model: OJBetter.chatgpt.config.model || modelDefault,
  12026. messages: [{
  12027. role: "user",
  12028. content: prompt + raw
  12029. }],
  12030. temperature: 0.7,
  12031. stream: true,
  12032. ...Object.assign({}, ...OJBetter.chatgpt.config.data)
  12033. }
  12034. const options = {
  12035. method: "POST",
  12036. url: OJBetter.chatgpt.config.proxy || 'https://api.openai.com/v1/chat/completions',
  12037. data: JSON.stringify(data),
  12038. responseType: 'stream',
  12039. headers: {
  12040. 'Content-Type': 'application/json',
  12041. 'Authorization': 'Bearer ' + OJBetter.chatgpt.config.key,
  12042. ...Object.assign({}, ...OJBetter.chatgpt.config.header)
  12043. }
  12044. }
  12045. const response = await OJB_GMRequest(options, true);
  12046. const reader = response.response.getReader();
  12047. const decoder = new TextDecoder();
  12048. let buffer = ''; // 用于累积数据片段的缓冲区
  12049.  
  12050. while (true) {
  12051. const { done, value } = await reader.read();
  12052. if (done) break;
  12053. buffer += decoder.decode(value, { stream: true }); // 将新的数据片段追加到缓冲区
  12054. let lines = buffer.split("\n\n"); // 处理累积的数据
  12055.  
  12056. // 缓冲区的最后一行可能还未完整接收,保留在缓冲区中,-1
  12057. for (let i = 0; i < lines.length - 1; i++) {
  12058. let line = lines[i];
  12059. line = line.substring(5); // 移除 'data:' 前缀
  12060. if (line.includes('[DONE]')) {
  12061. return; // End
  12062. }
  12063. try {
  12064. let data = JSON.parse(line);
  12065. let delta = data['choices'][0]['delta'];
  12066. let content = delta['content'] ? delta['content'] : "";
  12067. yield content; // 传递数据给调用者
  12068. } catch (error) {
  12069. console.warn(`Error parsing JSON: ${error}\n\nError data: ${line}`);
  12070. }
  12071. }
  12072.  
  12073. // 保留最后一行在缓冲区中
  12074. buffer = lines.slice(-1);
  12075. }
  12076.  
  12077. return buffer;
  12078. }
  12079.  
  12080. /**
  12081. * @typedef {Object} CheckResponseResult
  12082. * @property {boolean} status 检查是否通过
  12083. * @property {string} message 检查失败时的消息
  12084. */
  12085.  
  12086. /**
  12087. * @typedef {Object} ErrorResponse
  12088. * @property {Object} message 错误消息
  12089. * @property {Object} stack 错误堆栈
  12090. * @property {Object} enumerable 可枚举的错误属性
  12091. * @property {string} source 错误来源
  12092. */
  12093.  
  12094. /**
  12095. * @typedef {Object} TranslateResult
  12096. * @property {boolean} done 操作是否完成
  12097. * @property {CheckResponseResult|null} checkPassed 检查是否通过的结果
  12098. * @property {Object|null} response 响应对象
  12099. * @property {string|null} text 处理后的文本
  12100. * @property {ErrorResponse} error 错误列表
  12101. * @property {string|null} message 可能的消息
  12102. */
  12103.  
  12104. /**
  12105. * 通用翻译函数
  12106. * @param {Object} options GM_xmlhttpRequest 的参数
  12107. * @param {Function} processer 响应再处理函数,它接收响应文本,并应返回处理后的文本。
  12108. * @param {Function} checkResponse 检查文本是否符合预期的函数,它接收文本,并返回一个Object,包含状态和信息。默认为返回 { status: true, message: 'ok' }
  12109. * @param {Function} getResponseText 重写响应文本获取函数,它接收response,并返回响应文本。 默认为 response.responseText
  12110. * @returns {Promise<TranslateResult>} 返回 Promise,其解析值为翻译结果对象
  12111. */
  12112. async function BaseTranslate(options, processer, checkResponse = () => { return { status: true, message: 'ok' } }, getResponseText = (response) => response.responseText) {
  12113. const result = {
  12114. done: false,
  12115. checkPassed: null,
  12116. response: null,
  12117. responseText: null,
  12118. text: "",
  12119. error: null,
  12120. message: null
  12121. };
  12122. const helpText = i18next.t('error.basic', { ns: 'translator' }); // 基本帮助提示信息
  12123. const toDo = async () => {
  12124. try {
  12125. result.response = await OJB_GMRequest(options);
  12126. result.responseText = result.response.responseText;
  12127. result.text = getResponseText(result.response);
  12128. } catch (err) {
  12129. console.warn(err);
  12130. result.error = {
  12131. message: err.message || null,
  12132. stack: err.stack ? err.stack.replace(/\n/g, '<br>').replace(/\s/g, '&nbsp;') : null,
  12133. enumerable: err,
  12134. source: 'GMRequest'
  12135. };
  12136. result.message = `${i18next.t('error.GMRequest', { ns: 'translator' })}${helpText}`;
  12137. throw result;
  12138. }
  12139. try {
  12140. result.text = processer(result.text);
  12141. } catch (err) {
  12142. console.warn(err);
  12143. result.error = {
  12144. message: err.message || null,
  12145. stack: err.stack ? err.stack.replace(/\n/g, '<br>').replace(/\s/g, '&nbsp;') : null,
  12146. enumerable: err,
  12147. source: 'processer'
  12148. };
  12149. result.message = `${i18next.t('error.processer', { ns: 'translator' })}${helpText}`;
  12150. throw result;
  12151. }
  12152. try {
  12153. result.checkPassed = checkResponse(result.text);
  12154. if (result.checkPassed.status) result.done = true;
  12155. else result.message = result.checkPassed.message;
  12156. return result;
  12157. } catch (err) {
  12158. console.warn(err);
  12159. result.error = {
  12160. message: err.message || null,
  12161. stack: err.stack ? err.stack.replace(/\n/g, '<br>').replace(/\s/g, '&nbsp;') : null,
  12162. enumerable: err,
  12163. source: 'checkResponse'
  12164. };
  12165. result.message = `${i18next.t('error.checkResponse', { ns: 'translator' })}${helpText}`;
  12166. throw result;
  12167. }
  12168. };
  12169.  
  12170. return await OJB_promiseRetryWrapper(toDo, {
  12171. maxRetries: 3,
  12172. errorHandler: (err, maxRetries, attemptsLeft) => {
  12173. const detailedError = {
  12174. maxRetries: maxRetries,
  12175. attemptsLeft: attemptsLeft,
  12176. ...err
  12177. };
  12178. return detailedError;
  12179. }
  12180. });
  12181. }
  12182.  
  12183. /**
  12184. * 查询服务余额
  12185. * @param {Object} quotaConfig - 配额配置对象
  12186. * @returns {Promise} 返回包含余额信息的 Promise
  12187. */
  12188. async function queryServerBalance(quotaConfig) {
  12189. // 确保传入了有效的配置对象
  12190. if (!quotaConfig || !quotaConfig.url) {
  12191. return Promise.reject(new Error('Quota configuration is missing.'));
  12192. }
  12193.  
  12194. // 准备请求选项
  12195. const requestOptions = {
  12196. method: quotaConfig.method || 'GET',
  12197. url: quotaConfig.url,
  12198. headers: {
  12199. ...Object.assign({}, ...quotaConfig.header)
  12200. },
  12201. data: JSON.stringify({ ...Object.assign({}, ...quotaConfig.data) })
  12202. };
  12203.  
  12204. // 发送请求并返回 Promise
  12205. return OJB_GMRequest(requestOptions).then(response => {
  12206. try {
  12207. const responseData = JSON.parse(response.responseText);
  12208. // 从响应数据中提取余额
  12209. const surplusPath = quotaConfig.surplus;
  12210. const surplusValue = OJB_evaluatePathOrExpression(responseData, surplusPath);
  12211. return surplusValue;
  12212. } catch (error) {
  12213. return Promise.reject(new Error('Failed to parse balance response.'));
  12214. }
  12215. }).catch(error => {
  12216. console.warn('Error querying balance:', error);
  12217. return Promise.reject(error);
  12218. });
  12219. }
  12220.  
  12221. /**
  12222. * 确认 jQuery 已加载
  12223. * @param {number} retryDelay 重试延迟(毫秒)
  12224. * @returns {Promise<void>}
  12225. */
  12226. async function ensureJQueryIsLoaded(retryDelay = 50) {
  12227. while (typeof jQuery === 'undefined') {
  12228. console.warn(`JQuery is not loaded. Retry after ${retryDelay} ms.`);
  12229. await OJB_delay(retryDelay);
  12230. retryDelay = Math.min(retryDelay * 2, 2000);
  12231. }
  12232. }
  12233.  
  12234. /**
  12235. * 加载必须的函数
  12236. * @returns {Promise<LoadingMessage>} 加载提示信息
  12237. */
  12238. async function loadRequiredFunctions() {
  12239. await initVar();// 初始化全局变量
  12240. return Promise.allSettled([
  12241. initDB(), // 连接数据库
  12242. initI18next(), // i18next初始化
  12243. initButtonFunc(), // 加载按钮相关函数
  12244. checkScriptVersion(), // 更新检查
  12245. ...(OJBetter.typeOfPage.is_acmsguru ? [acmsguruReblock()] : []) // 为acmsguru题面重新划分div
  12246. ]);
  12247. }
  12248.  
  12249. /**
  12250. * DOM加载后即可执行
  12251. */
  12252. function initOnDOMReady() {
  12253. showAnnounce(); // 显示公告
  12254. showWarnMessage(); // 显示警告消息
  12255. initSettingsPanel(); // 加载设置按钮面板
  12256. localizeWebsite(); // 网站本地化替换
  12257. addDependencyStyles(); // 添加一些依赖库的样式
  12258. addI18nStyles(); // 添加包含i18n内容的样式
  12259. if (OJBetter.basic.expandFoldingblocks) ExpandFoldingblocks(); // 折叠块展开
  12260. if (OJBetter.basic.renderPerfOpt) RenderPerfOpt(); // 折叠块渲染优化
  12261. if (OJBetter.typeOfPage.is_problem) {
  12262. const problemPageLinkbar = new ProblemPageLinkbar(); // 创建题目页相关链接栏
  12263. if (OJBetter.basic.showJumpToLuogu) CF2luogu(problemPageLinkbar); // 跳转到洛谷按钮
  12264. if (OJBetter.clist.enabled.problem) showRatingByClist_problem(problemPageLinkbar); // problem页显示Rating
  12265. }
  12266. if (OJBetter.typeOfPage.is_contest) {
  12267. if (OJBetter.clist.enabled.contest) showRatingByClist_contest(); // contest页显示Rating
  12268. }
  12269. if (OJBetter.typeOfPage.is_problemset) {
  12270. if (OJBetter.clist.enabled.problemset) showRatingByClist_problemset(); // problemset页显示Rating
  12271. }
  12272. if (OJBetter.typeOfPage.is_problem && OJBetter.monaco.enableOnProblemPage) {
  12273. addProblemPageCodeEditor(); // 添加题目页代码编辑器
  12274. }
  12275. }
  12276.  
  12277. /**
  12278. * 需要在页面资源完全加载后执行的函数
  12279. */
  12280. function onResourcesReady(loadingMessage) {
  12281. if (OJBetter.preference.showLoading) loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('loadFunc', { ns: 'alert' })}`);
  12282. initializeInParallel(loadingMessage);
  12283. initializeSequentially(loadingMessage);
  12284. }
  12285.  
  12286. /**
  12287. * 可以异步并行的函数
  12288. */
  12289. function initializeInParallel(loadingMessage) {
  12290. if (OJBetter.basic.darkMode == "dark") darkModeStyleAdjustment(); // 黑暗模式额外的处理事件
  12291. if (OJBetter.basic.commentPaging) CommentPagination(); // 评论区分页
  12292. if (OJBetter.translation.comment.transMode == "2") multiChoiceTranslation(); // 选段翻译支持
  12293. }
  12294.  
  12295. /**
  12296. * 必须按序执行的函数
  12297. */
  12298. async function initializeSequentially(loadingMessage) {
  12299. await addConversionButton(); // 添加MD/复制/翻译按钮
  12300. if ((OJBetter.typeOfPage.is_problem || OJBetter.typeOfPage.is_completeProblemset) && OJBetter.translation.memory.enabled) {
  12301. await initTransResultsRecover(); // 翻译结果恢复功能初始化
  12302. }
  12303. if (OJBetter.translation.auto.enabled) {
  12304. await initTransWhenViewable(); // 自动翻译
  12305. }
  12306. if (OJBetter.basic.standingsRecolor && OJBetter.typeOfPage.is_cfStandings) {
  12307. await recolorStandings(); // cf赛制榜单重新着色
  12308. }
  12309. if (OJBetter.preference.showLoading) loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('loadSuccess', { ns: 'alert' })}`, 'success', 3000);
  12310. }
  12311.  
  12312. /**
  12313. * 脚本开始加载
  12314. */
  12315. document.addEventListener("DOMContentLoaded", async () => {
  12316. await ensureJQueryIsLoaded(); // 等待jQuery加载
  12317. const loadingMessage = new LoadingMessage();
  12318. await loadRequiredFunctions(); // 加载必须的函数
  12319. initOnDOMReady(); // DOM加载后即可执行的函数
  12320. if (OJBetter.preference.showLoading) loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('onload', { ns: 'alert' })}`);
  12321.  
  12322. // 检查页面资源是否已经完全加载
  12323. if (OJBetter.state.notWaiteLoaded) {
  12324. onResourcesReady(loadingMessage);
  12325. } else {
  12326. if (document.readyState === 'complete') {
  12327. onResourcesReady(loadingMessage);
  12328. } else {
  12329. window.addEventListener('load', () => onResourcesReady(loadingMessage));
  12330. }
  12331. }
  12332. });
  12333.  
  12334. // ------------------------------
  12335. // 配置自动迁移代码(将在10个小版本后移除-1.83)
  12336. // ------------------------------
  12337.  
  12338. {
  12339. let bottomZh_CN = GM_getValue("bottomZh_CN");
  12340. if (bottomZh_CN !== undefined) {
  12341. if (bottomZh_CN == true) {
  12342. GM_setValue("localizationLanguage", "zh");
  12343. } else {
  12344. GM_setValue("localizationLanguage", "initial");
  12345. }
  12346. GM_deleteValue("bottomZh_CN");
  12347. location.reload();
  12348. }
  12349. }
  12350. {
  12351. let config = GM_getValue("chatgpt-config");
  12352. if (config && config !== undefined) {
  12353. let index = parseInt(config.choice, 10);
  12354. if (index == -1) config.choice = "";
  12355. else config.choice = config.configurations[index].note;
  12356. config.configurations.forEach(function (item) {
  12357. item.name = item.note;
  12358. delete item.note;
  12359. });
  12360. GM_deleteValue("chatgpt-config");
  12361. GM_setValue("chatgpt_config", config);
  12362. location.reload();
  12363. }
  12364. }
  12365. {
  12366. let config = GM_getValue("Complet_config");
  12367. if (config && config.changed === undefined) {
  12368. config.changed = true; // 设置一个迁移标志
  12369. config.configurations.forEach(function (item) {
  12370. if (item.note !== undefined) {
  12371. item.name = item.note;
  12372. delete item.note;
  12373. }
  12374. });
  12375. GM_setValue("Complet_config", config);
  12376. location.reload();
  12377. }
  12378. }

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址