Atcoder Better!

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

2024-03-15 يوللانغان نەشرى. ئەڭ يېڭى نەشرىنى كۆرۈش.

  1. // ==UserScript==
  2. // @name Atcoder Better!
  3. // @namespace https://greatest.deepsurf.us/users/747162
  4. // @version 1.13.0
  5. // @description Atcoder界面汉化、题目翻译、markdown视图、一键复制题目、跳转到洛谷
  6. // @author 北极小狐
  7. // @match *://atcoder.jp/*
  8. // @run-at document-start
  9. // @connect www2.deepl.com
  10. // @connect api-free.deepl.com
  11. // @connect api.deepl.com
  12. // @connect api.deeplx.org
  13. // @connect www.iflyrec.com
  14. // @connect m.youdao.com
  15. // @connect api.interpreter.caiyunai.com
  16. // @connect translate.google.com
  17. // @connect openai.api2d.net
  18. // @connect api.openai.com
  19. // @connect www.luogu.com.cn
  20. // @connect vjudge.net
  21. // @connect clist.by
  22. // @connect greatest.deepsurf.us
  23. // @connect staticfile.net
  24. // @connect aowuucdn.oss-cn-beijing.aliyuncs.com
  25. // @connect aowuucdn.oss-accelerate.aliyuncs.com
  26. // @connect 127.0.0.1
  27. // @connect *
  28. // @grant GM_xmlhttpRequest
  29. // @grant GM_info
  30. // @grant GM_setValue
  31. // @grant GM_getValue
  32. // @grant GM_listValues
  33. // @grant GM_deleteValue
  34. // @grant GM_addStyle
  35. // @grant GM_setClipboard
  36. // @grant GM_getResourceText
  37. // @icon https://aowuucdn.oss-accelerate.aliyuncs.com/atcoder.png
  38. // @require https://cdn.staticfile.net/turndown/7.1.2/turndown.min.js
  39. // @require https://cdn.staticfile.net/markdown-it/13.0.1/markdown-it.min.js
  40. // @require https://cdn.bootcdn.net/ajax/libs/crypto-js/4.1.1/crypto-js.min.js
  41. // @require https://cdn.staticfile.net/chroma-js/2.4.2/chroma.min.js
  42. // @require https://cdn.staticfile.net/xterm/3.9.2/xterm.min.js
  43. // @require https://cdn.staticfile.net/dexie/3.2.4/dexie.min.js
  44. // @require https://cdn.staticfile.net/i18next/23.5.1/i18next.min.js
  45. // @require https://cdn.staticfile.net/i18next-http-backend/2.2.2/i18nextHttpBackend.min.js
  46. // @require https://cdn.staticfile.net/jquery-i18next/1.2.1/jquery-i18next.min.js
  47. // @require https://cdn.staticfile.net/highlight.js/11.3.1/highlight.min.js
  48. // @require https://update.greatest.deepsurf.us/scripts/484742/1311040/i18nextChainedBackendjs.js
  49. // @require https://update.greatest.deepsurf.us/scripts/484743/1311041/i18next-localstorage-backendjs.js
  50. // @resource acwing_cpp_code_completer https://aowuucdn.oss-accelerate.aliyuncs.com/acwing_cpp_code_completer-0.0.11.json
  51. // @resource wandboxlist https://wandbox.org/api/list.json
  52. // @resource xtermcss https://cdn.staticfile.net/xterm/3.9.2/xterm.min.css
  53. // @license GPL3
  54. // @compatible Chrome
  55. // @compatible Firefox
  56. // @compatible Edge
  57. // @incompatible safari
  58. // @supportURL https://github.com/beijixiaohu/OJBetter/issues
  59. // @name:zh-TW Atcoder Better!
  60. // @name:en Atcoder Better!
  61. // @name:de Atcoder Better!
  62. // @name:fr Atcoder Better!
  63. // @name:ko Atcoder Better!
  64. // @name:pt Atcoder Better!
  65. // @name:ja Atcoder Better!
  66. // @name:es Atcoder Better!
  67. // @name:it Atcoder Better!
  68. // @name:hi Atcoder Better!
  69. // @description 一个适用于 AtCoder 的 Tampermonkey 脚本,增强功能与界面。
  70. // @description:zh-TW 一個適用於 AtCoder 的 Tampermonkey 腳本,增強功能與界面。
  71. // @description:en A Tampermonkey script for AtCoder that enhances functionality and interface.
  72. // @description:de Ein Tampermonkey-Skript für AtCoder, das Funktionalität und Benutzeroberfläche verbessert.
  73. // @description:fr Un script Tampermonkey pour AtCoder qui améliore les fonctionnalités et l'interface.
  74. // @description:ko AtCoder를 위한 Tampermonkey 스크립트로 기능과 인터페이스를 개선합니다.
  75. // @description:pt Um script Tampermonkey para AtCoder que aprimora a funcionalidade e a interface.
  76. // @description:ja AtCoder用のTampermonkeyスクリプトで機能とインターフェースを強化します。
  77. // @description:es Un script Tampermonkey para AtCoder que mejora la funcionalidad y la interfaz.
  78. // @description:it Uno script Tampermonkey per AtCoder che migliora la funzionalità e l'interfaccia.
  79. // @description:hi AtCoder के लिए एक Tampermonkey स्क्रिप्ट जो कार्यक्षमता और इंटरफ़ेस को बेहतर बनाता है।
  80. // ==/UserScript==
  81.  
  82. /**
  83. * @namespace OJBetter
  84. * @desc 主命名空间
  85. */
  86. const OJBetter = {};
  87.  
  88. /**
  89. * @namespace state
  90. * @desc 描述脚本的当前状态。
  91. * @memberof OJBetter
  92. */
  93. OJBetter.state = {
  94. /** @type {string} 脚本名*/
  95. name: GM_info.script.name,
  96. /** @type {string} 格式化后的脚本名*/
  97. formatName: undefined,
  98. /** @type {string} 版本号*/
  99. version: GM_info.script.version,
  100. /** @type {boolean?} 是否跳过页面加载等待 */
  101. notWaiteLoaded: undefined,
  102. /** @type {string} 最后公告版本,用于标识版本更新完成提示 */
  103. lastAnnounceVer: undefined,
  104. /** @type {string} 最后读取的有效公告版本 */
  105. lastReadAnnounceVer: undefined,
  106. /** @type {number} 当前已打开的模态对话框数量*/
  107. openDialogCount: 0
  108. };
  109.  
  110. /**
  111. * @namespace common
  112. * @desc 通用设置和属性。
  113. * @memberof OJBetter
  114. */
  115. OJBetter.common = {
  116. /** @type {string} 网站的主机地址 */
  117. hostAddress: location.origin,
  118. /** @type {string?} Atcoder的CSRF令牌 */
  119. at_csrf_token: undefined,
  120. /** @type {Array?} 任务队列 */
  121. taskQueue: undefined,
  122. /** @type {object} OJBetter数据库连接实例*/
  123. database: undefined
  124. };
  125.  
  126. /**
  127. * @namespace basic
  128. * @desc 基本的用户界面设置。
  129. * @memberof OJBetter
  130. */
  131. OJBetter.basic = {
  132. /** @type {string} 黑暗模式设置 */
  133. darkMode: undefined,
  134. /** @type {boolean?} 是否展开折叠块 */
  135. expandFoldingblocks: undefined,
  136. /** @type {boolean?} 是否开启折叠块渲染性能优化 */
  137. renderPerfOpt: undefined,
  138. /** @type {boolean?} 评论区分页 */
  139. commentPaging: undefined,
  140. /** @type {boolean?} 显示跳转到Luogu按钮 */
  141. showJumpToLuogu: undefined,
  142. /** @type {boolean?} 显示跳转到Virtual Judge按钮 */
  143. showCF2vjudge: undefined,
  144. /** @type {boolean?} 比赛排行榜重新着色 */
  145. standingsRecolor: undefined
  146. };
  147.  
  148. /**
  149. * @namespace typeOfPage
  150. * @desc 页面类型判断。
  151. * @memberof OJBetter
  152. */
  153. OJBetter.typeOfPage = {
  154. /** @type {boolean?} 是否是轻量站 */
  155. is_mSite: false,
  156. /** @type {boolean?} 是否是acmsguru页面 */
  157. is_acmsguru: false,
  158. /** @type {boolean?} 是否是旧版LaTeX页面 */
  159. is_oldLatex: false,
  160. /** @type {boolean?} 是否是题目集页面 */
  161. is_contest: undefined,
  162. /** @type {boolean?} 是否是题目页面 */
  163. is_problem: undefined,
  164. /** @type {boolean?} 是否是完整的问题集页面 */
  165. is_completeProblemset: false,
  166. /** @type {boolean?} 是否是问题集中的问题页面 */
  167. is_problemset_problem: false,
  168. /** @type {boolean?} 是否是问题集页面 */
  169. is_problemset: false,
  170. /** @type {boolean?} 是否是Codeforces排名页面 */
  171. is_cfStandings: false,
  172. /** @type {boolean?} 是否是提交页面 */
  173. is_submitPage: false,
  174. /** @type {boolean?} 是否是主页 */
  175. is_homepage: undefined,
  176. /** @type {boolean?} 是否选择的是英语页面 */
  177. isEnglishLanguage: undefined,
  178. };
  179.  
  180. /**
  181. * @namespace localization
  182. * @desc 本地化设置。
  183. * @memberof OJBetter
  184. */
  185. OJBetter.localization = {
  186. /** @type {string?} 网站语言 */
  187. websiteLang: undefined,
  188. /** @type {string?} 脚本语言 */
  189. scriptLang: undefined
  190. };
  191.  
  192. /**
  193. * @namespace translation
  194. * @desc 翻译设置。
  195. * @memberof OJBetter
  196. */
  197. OJBetter.translation = {
  198. /** @type {string?} 翻译服务选择 */
  199. choice: undefined,
  200. /** @type {string?} 目标语言 */
  201. targetLang: undefined,
  202. comment: {
  203. /** @type {string?} 评论翻译服务选择 */
  204. choice: undefined,
  205. /** @type {string?} 评论翻译模式 */
  206. transMode: undefined
  207. },
  208. auto: {
  209. /** @type {boolean?} 自动翻译开关 */
  210. enabled: undefined,
  211. /** @type {number?} 短文本长度限制 */
  212. shortTextLength: undefined,
  213. mixTrans: {
  214. /** @type {boolean?} 混合翻译开关 */
  215. enabled: undefined,
  216. /** @type {Array?} 混合翻译服务列表 */
  217. servers: undefined
  218. }
  219. },
  220. memory: {
  221. /** @type {boolean?} 翻译记忆开关 */
  222. enabled: undefined,
  223. /** @type {Object?} 翻译记忆树 */
  224. ttTree: undefined
  225. },
  226. /** @type {string?} 重翻译时的行为 */
  227. retransAction: undefined,
  228. /** @type {number?} 等待时间 */
  229. waitTime: undefined,
  230. /** @type {boolean?} 替换符 */
  231. replaceSymbol: undefined,
  232. /** @type {boolean?} 过滤文本中的*号 */
  233. filterTextWithoutEmphasis: undefined
  234. };
  235.  
  236. /**
  237. * @namespace clist
  238. * @desc Clist相关设置。
  239. * @memberof OJBetter
  240. */
  241. OJBetter.clist = {
  242. enabled: {
  243. /** @type {boolean?} 比赛页面开关 */
  244. contest: undefined,
  245. /** @type {boolean?} 问题页面开关 */
  246. problem: undefined,
  247. /** @type {boolean?} 问题集页面开关 */
  248. problemset: undefined
  249. },
  250. /** @type {boolean?} Rating数据防剧透 */
  251. ratingHidden: undefined,
  252. /** @type {string?} Clist key */
  253. authorization: undefined
  254. };
  255.  
  256. /**
  257. * @namespace monaco
  258. * @desc Monaco编辑器配置。
  259. * @memberof OJBetter
  260. */
  261. OJBetter.monaco = {
  262. /** @type {boolean?} 在问题页面上启用Monaco编辑器 */
  263. enableOnProblemPage: undefined,
  264. /** @type {boolean?} 美化pre代码块 */
  265. beautifyPreBlocks: undefined,
  266. /** @type {boolean} Monaco编辑器加载完成标志 */
  267. loaderOnload: false,
  268. lsp: {
  269. /** @type {Array?} LSP套接字数组 */
  270. socket: [],
  271. /** @type {boolean?} 是否启用LSP */
  272. enabled: undefined,
  273. /** @type {string?} 工作路径 */
  274. workUri: undefined,
  275. /** @type {string?} 套接字URL */
  276. socketUrl: undefined
  277. },
  278. complet: {
  279. /** @type {boolean?} 是否启用C++代码补全模板 */
  280. cppCodeTemplate: undefined,
  281. /** @type {Object?} 自定义配置 */
  282. customConfig: undefined
  283. },
  284. /** @type {Object?} Monaco编辑器实例 */
  285. editor: null,
  286. /** @type {string?} 在线编译器选择 */
  287. onlineCompilerChoice: undefined,
  288. /** @type {string?} 编译器选择 */
  289. compilerSelection: undefined,
  290. setting: {
  291. /** @type {Array?} 语言设置数组 */
  292. language: [],
  293. /** @type {string?} 位置 */
  294. position: undefined,
  295. /** @type {boolean} 位置初始化标志 */
  296. position_initialized: false,
  297. /** @type {number?} 字体大小 */
  298. fontsize: undefined,
  299. /** @type {boolean?} 鼠标滚动锁定 */
  300. alwaysConsumeMouseWheel: undefined,
  301. /** @type {boolean?} 提交代码二次确认 */
  302. isCodeSubmitDoubleConfirm: undefined,
  303. /** @type {string?} 提交按钮位置 */
  304. submitButtonPosition: undefined
  305. }
  306. };
  307.  
  308. /**
  309. * @namespace deepl
  310. * @desc DeepL翻译服务配置。
  311. * @memberof OJBetter
  312. */
  313. OJBetter.deepl = {
  314. /** @type {Object?} DeepL配置对象 */
  315. configs: undefined,
  316. config: {
  317. /** @type {string?} 类型 */
  318. type: undefined,
  319. /** @type {string?} 名称 */
  320. name: undefined,
  321. /** @type {string?} API类型 */
  322. apiGenre: undefined,
  323. /** @type {string?} API密钥 */
  324. key: undefined,
  325. /** @type {string?} 代理 */
  326. proxy: undefined,
  327. /** @type {Object?} 额外请求头 */
  328. header: undefined,
  329. /** @type {Object?} 额外请求数据 */
  330. data: undefined,
  331. quota: {
  332. /** @type {string?} 余额URL */
  333. url: undefined,
  334. /** @type {string?} 余额请求方法 */
  335. method: undefined,
  336. /** @type {Object?} 余额请求头 */
  337. header: undefined,
  338. /** @type {Object?} 余额请求数据 */
  339. data: undefined,
  340. /** @type {number?} 剩余配额 */
  341. surplus: undefined
  342. }
  343. },
  344. /** @type {boolean?} 启用重点保护 */
  345. enableEmphasisProtection: undefined,
  346. /** @type {boolean?} 启用链接保护 */
  347. enableLinkProtection: undefined
  348. };
  349.  
  350. /**
  351. * @namespace chatgpt
  352. * @desc ChatGPT服务配置。
  353. * @memberof OJBetter
  354. */
  355. OJBetter.chatgpt = {
  356. /** @type {Object?} ChatGPT配置对象 */
  357. configs: undefined,
  358. config: {
  359. /** @type {string?} 名称 */
  360. name: undefined,
  361. /** @type {string?} 模型 */
  362. model: undefined,
  363. /** @type {string?} API密钥 */
  364. key: undefined,
  365. /** @type {string?} 代理 */
  366. proxy: undefined,
  367. /** @type {Object?} 额外请求头 */
  368. header: undefined,
  369. /** @type {Object?} 额外请求数据 */
  370. data: undefined,
  371. quota: {
  372. /** @type {string?} 余额URL */
  373. url: undefined,
  374. /** @type {string?} 余额请求方法 */
  375. method: undefined,
  376. /** @type {Object?} 余额请求头 */
  377. header: undefined,
  378. /** @type {Object?} 余额请求数据 */
  379. data: undefined,
  380. /** @type {number?} 剩余配额 */
  381. surplus: undefined
  382. }
  383. },
  384. /** @type {boolean?} 是否为流式传输 */
  385. isStream: undefined
  386. };
  387.  
  388. /**
  389. * @namespace preference
  390. * @desc 偏好设置
  391. * @memberof OJBetter
  392. */
  393. OJBetter.preference = {
  394. /** @type {boolean?} 是否显示加载动画 */
  395. showLoading: undefined,
  396. /** @type {boolean?} 是否显示悬停目标区域 */
  397. hoverTargetAreaDisplay: undefined,
  398. /** @type {string?} 按钮图标大小 */
  399. iconButtonSize: undefined,
  400. };
  401.  
  402. /**
  403. * @namespace about
  404. * @desc 关于页信息
  405. * @memberof OJBetter
  406. */
  407. OJBetter.about = {
  408. /** @type {string?} 更新通道 */
  409. updateChannel: undefined,
  410. /** @type {string?} 更新源 */
  411. updateSource: undefined
  412. };
  413.  
  414. /**
  415. * @namespace supportList
  416. * @desc 支持列表
  417. * @memberof OJBetter
  418. */
  419. OJBetter.supportList = {
  420. /** @type {object} 翻译支持列表和对应语言代码*/
  421. translationSupport: {
  422. 'deepl': { 'zh': 'ZH', 'de': 'DE', 'fr': 'FR', 'ko': 'KO', 'pt': 'PT', 'ja': 'JA', 'es': 'ES', 'it': 'IT' },
  423. 'iflyrec': { 'zh': '1' },
  424. 'youdao': { 'zh': 'AUTO' },
  425. 'google': { 'zh': 'zh-CN', 'zh-Hant': 'zh-TW', 'de': 'de', 'fr': 'fr', 'ko': 'ko', 'pt': 'pt', 'ja': 'ja', 'es': 'es', 'it': 'it', 'hi': 'hi' },
  426. 'caiyun': { 'zh': 'auto2zh', 'ja': 'auto2ja', 'ko': 'auto2ko', 'es': 'auto2es', 'fr': 'auto2fr' },
  427. 'openai': { 'zh': 'Chinese', 'zh-Hant': 'Traditional Chinese', 'de': 'German', 'fr': 'French', 'ko': 'Korean', 'pt': 'Portuguese', 'ja': 'Japanese', 'es': 'Spanish', 'it': 'Italian', 'hi': 'Hindi' }
  428. },
  429. /** @type {object} 更新源支持列表*/
  430. updateSourceSupportList: {
  431. 'greasyfork': {
  432. 'release': true,
  433. 'dev': false
  434. },
  435. 'github': {
  436. 'release': true,
  437. 'dev': true
  438. },
  439. 'aliyunoss': {
  440. 'release': true,
  441. 'dev': true
  442. }
  443. }
  444. }
  445.  
  446. // ------------------------------
  447. // 一些工具函数
  448. // ------------------------------
  449.  
  450. /**
  451. * 安全地创建jQuery元素
  452. * @description 通过jQuery创建HTML字符串时,如果字符串以空格开头,在某些Jquery版本中会发生错误,过滤空格以安全的创建元素。
  453. * @param {string} htmlString - HTML字符串。
  454. * @returns jQuery对象
  455. */
  456. const OJB_safeCreateJQElement = function (htmlString) {
  457. return $(htmlString.replace(/^\s+/, ""));
  458. }
  459.  
  460.  
  461. /**
  462. * 将数字或者字符串解析为数字。
  463. * @memberof OJBetter.common
  464. * @param {string} val 要解析的字符串
  465. * @param {boolean} [strict=false] 是否进行严格类型检查
  466. * @returns {number} 解析结果
  467. * @throws {Error} 如果解析失败,则抛出错误
  468. */
  469. const OJB_parseNumber = (val, strict = false) => {
  470. const num = Number(val);
  471. if (isNaN(num) || (strict && val.toString() !== num.toString())) {
  472. throw new Error('Invalid number');
  473. }
  474. return num;
  475. };
  476.  
  477. /**
  478. * 将字符串解析为布尔值
  479. * @param {string} val - 要解析的字符串
  480. * @param {boolean} strict - 是否进行严格类型检查
  481. * @returns {boolean} - 解析结果
  482. * @throws {Error} - 如果解析失败,则抛出错误
  483. */
  484. const OJB_parseBoolean = (val, strict) => {
  485. if (strict) {
  486. if (val === true || val === false) return val;
  487. throw new Error('Invalid boolean');
  488. }
  489. return val === 'true' ? true : val === 'false' ? false : val;
  490. };
  491.  
  492. /**
  493. * 将字符串解析为对象
  494. * @param {string} val - 要解析的字符串
  495. * @returns {Object} - 解析结果
  496. * @throws {Error} - 如果解析失败,则抛出错误
  497. */
  498. const OJB_parseObject = val => {
  499. try {
  500. return JSON.parse(val);
  501. } catch {
  502. throw new Error('Invalid JSON');
  503. }
  504. };
  505.  
  506. /**
  507. * 将字符串解析为键值对数组
  508. * @param {string} val - 要解析的字符串
  509. * @returns {Object[]} - 解析结果
  510. * @throws {Error} - 如果解析失败,则抛出错误
  511. */
  512. const OJB_parseLinePairArray = val => {
  513. if (typeof val !== 'string' || val.trim() === '') return [];
  514. return val.split("\n").filter(line => line.trim() !== '').map(line => {
  515. const indexOfFirstColon = line.indexOf(":");
  516. if (indexOfFirstColon === -1) throw new Error('Invalid LinePairArray format: ":" is missing');
  517. const key = line.substring(0, indexOfFirstColon).trim();
  518. const value = line.substring(indexOfFirstColon + 1).trim();
  519. return { [key]: value };
  520. });
  521. };
  522.  
  523. /**
  524. * 移除文本中的HTML标签
  525. * @param {string} text - 包含HTML标签的文本
  526. * @returns {string} - 移除HTML标签后的文本
  527. */
  528. const OJB_removeHTMLTags = function (text) {
  529. return text.replace(/<\/?[a-zA-Z]+("[^"]*"|'[^']*'|[^'">])*>/g, '');
  530. }
  531.  
  532. /**
  533. * 获取对象中指定路径表达式的值
  534. * @param {Object} obj - 要计算的对象
  535. * @param {string} pathOrExpression - 要计算的路径表达式
  536. * @returns {any} - 计算结果
  537. * @example
  538. * const obj = {
  539. * "a": {
  540. * "b": 1
  541. * },
  542. * "c": 2
  543. * };
  544. * evaluatePathOrExpression(obj, "a.b"); // 1
  545. * evaluatePathOrExpression(obj, "a.b + c"); // 3
  546. * evaluatePathOrExpression(obj, "a.b + a.c"); // 1
  547. */
  548. function OJB_evaluatePathOrExpression(obj, pathOrExpression) {
  549. const hasOperator = /[\+\-\*\/]/.test(pathOrExpression);
  550. const getPathValue = (obj, path) => {
  551. return path.split('.').reduce((acc, part) => {
  552. return acc !== undefined && acc !== null && acc.hasOwnProperty(part) ? acc[part] : undefined;
  553. }, obj);
  554. };
  555. const evaluateExpression = (obj, expression) => {
  556. const tokens = expression.split(/([\+\-\*\/])/).map(token => token.trim());
  557. const values = tokens.map(token => {
  558. if (/[\+\-\*\/]/.test(token)) {
  559. return token;
  560. } else {
  561. const value = getPathValue(obj, token);
  562. return value !== undefined ? value : 0;
  563. }
  564. });
  565. const evaluatedExpression = values.join(' ');
  566. try {
  567. return Function(`'use strict'; return (${evaluatedExpression});`)();
  568. } catch (e) {
  569. console.error('Expression evaluation error:', e);
  570. return undefined;
  571. }
  572. };
  573. return hasOperator ? evaluateExpression(obj, pathOrExpression) : getPathValue(obj, pathOrExpression);
  574. }
  575.  
  576. /**
  577. * 获取 GM 存储的值并根据类型进行处理
  578. * @param {string} key - 要检索的值的键。
  579. * @param {any} defaultValue - 如果值未找到,则返回的默认值。
  580. * @param {Object} [options={}] - 配置选项对象。
  581. * @param {string} [options.type='string'] - 期望的值的类型。可选值:'string', 'number', 'boolean', 'object', 'array', 'linePairArray'。
  582. * @param {boolean} [options.strict=false] - 用于数字和布尔类型,表示是否进行严格类型检查。
  583. * @param {string} [options.pathOrExpression=''] - 用于对象或数组类型,表示路径表达式或获取元素的索引。
  584. * @returns {any} - 检索到的值。
  585. */
  586. const OJB_getGMValue = (key, defaultValue, { type = 'string', strict = false, pathOrExpression = '' } = {}) => {
  587. let value = GM_getValue(key);
  588. if (value === undefined || value === null || value === "") {
  589. GM_setValue?.(key, defaultValue);
  590. return defaultValue;
  591. }
  592.  
  593. const parsers = {
  594. string: val => val,
  595. number: (val) => OJB_parseNumber(val, strict),
  596. boolean: (val) => OJB_parseBoolean(val, strict),
  597. object: OJB_parseObject,
  598. array: OJB_parseObject,
  599. linePairArray: OJB_parseLinePairArray
  600. };
  601.  
  602. if (!(type in parsers)) {
  603. console.error(`Unsupported type: ${type}`);
  604. return defaultValue;
  605. }
  606.  
  607. try {
  608. value = parsers[type](value);
  609. } catch (e) {
  610. console.error('Error:', e.message);
  611. return defaultValue;
  612. }
  613.  
  614. // The pathOrExpression processing is not applicable to linePairArray type
  615. if ((type === 'object' || type === 'array') && pathOrExpression) {
  616. const evaluated = OJB_evaluatePathOrExpression(value, pathOrExpression);
  617. if (evaluated === undefined) {
  618. console.error('Path or expression evaluation returned undefined');
  619. return defaultValue;
  620. }
  621. value = evaluated;
  622. }
  623.  
  624. return value;
  625. };
  626.  
  627. /**
  628. * 版本号比较方法
  629. * @param {string} version1 版本号1
  630. * @param {string} version2 版本号2
  631. * @returns {number} -1: version1 < version2, 0: version1 = version2, 1: version1 > version2
  632. */
  633. const OJB_compareVersions = function (version1 = "0", version2 = "0") {
  634. const v1Array = version1.split(".").map(Number);
  635. const v2Array = version2.split(".").map(Number);
  636. const length = Math.max(v1Array.length, v2Array.length);
  637. for (let i = 0; i < length; i++) {
  638. const diff = (v1Array[i] || 0) - (v2Array[i] || 0);
  639. if (diff) return Math.sign(diff);
  640. }
  641. return 0;
  642. }
  643.  
  644. /**
  645. * 获取上一个主版本号
  646. * @param {string} currentVersion 当前版本号
  647. * @returns {string} 上一个主版本号
  648. */
  649. const OJB_getPreviousVersion = function (currentVersion) {
  650. const versionArray = currentVersion.split(".").map(Number);
  651. let lastNonZeroIndex = versionArray.length - 1;
  652. while (lastNonZeroIndex >= 0 && versionArray[lastNonZeroIndex] === 0) {
  653. lastNonZeroIndex--;
  654. }
  655. if (lastNonZeroIndex >= 0) {
  656. versionArray[lastNonZeroIndex]--;
  657. for (let i = lastNonZeroIndex + 1; i < versionArray.length; i++) {
  658. versionArray[i] = 0;
  659. }
  660. }
  661. return versionArray.join(".");
  662. };
  663.  
  664. /**
  665. * 在指定根节点下观察指定选择器的元素,当元素存在时,执行回调函数
  666. * @param {Object} options - 配置对象
  667. * @param {string} options.selector - CSS选择器文本
  668. * @param {Function} options.callback - 回调函数,接收变动的节点作为参数
  669. * @param {Boolean} [options.triggerOnExist=true] - 如果为true,元素已存在时立即触发一次回调
  670. * @param {Element} [options.root=document.body] - 在哪个根节点下监听变化
  671. * @param {Boolean} [options.subtree=false] - 是否监听子树变化(即非直接子元素)
  672. */
  673. function OJB_observeElement({
  674. selector,
  675. callback,
  676. triggerOnExist = true,
  677. root = document.body,
  678. subtree = false
  679. }) {
  680. // 尝试获取选择器指定的元素
  681. const targetNode = root.querySelector(selector);
  682.  
  683. if (targetNode) {
  684. // 如果元素已存在,直接开始观察
  685. observeAndReport(targetNode, callback);
  686. // 如果triggerOnExist为true,则立即触发一次回调
  687. if (triggerOnExist) {
  688. callback(targetNode);
  689. }
  690. } else {
  691. // 如果元素不存在,监听DOM变化直到该元素被添加
  692. const observer = new MutationObserver((mutations) => {
  693. mutations.forEach((mutation) => {
  694. mutation.addedNodes.forEach((node) => {
  695. if (node.nodeType === Node.ELEMENT_NODE && node.matches(selector)) {
  696. observeAndReport(node, callback);
  697. if (triggerOnExist) {
  698. callback(node);
  699. }
  700. observer.disconnect(); // 停止监听
  701. }
  702. });
  703. });
  704. });
  705.  
  706. observer.observe(root, { childList: true, subtree, attributes: false });
  707. }
  708.  
  709. function observeAndReport(node, callback) {
  710. const childObserver = new MutationObserver((mutations) => {
  711. mutations.forEach((mutation) => {
  712. if (childList) {
  713. mutation.addedNodes.forEach((addedNode) => {
  714. if (addedNode.nodeType === Node.ELEMENT_NODE) {
  715. callback(addedNode); // 执行回调函数
  716. }
  717. });
  718. }
  719. if (attributes && mutation.type === 'attributes') {
  720. callback(mutation.target); // 执行回调函数
  721. }
  722. });
  723. });
  724.  
  725. childObserver.observe(node, { childList: true, subtree: true, attributes: false });
  726. }
  727. }
  728.  
  729. /**
  730. * 初始化全局变量
  731. */
  732. async function initVar() {
  733. const { hostname, href } = window.location;
  734. OJBetter.state.formatName = (() => OJBetter.state.name
  735. .toLowerCase()
  736. .replace(/\s+/g, '-')
  737. .replace(/[^a-z0-9-]/g, ''))();
  738. OJBetter.state.lastAnnounceVer = OJB_getGMValue("lastAnnounceVer", "0");
  739. OJBetter.state.lastReadAnnounceVer = OJB_getGMValue("lastReadAnnounceVer", "0");
  740. OJBetter.typeOfPage.is_contest = /\/contests\/[^\/]+\/tasks\/?$/.test(href);
  741. OJBetter.typeOfPage.is_problem = href.includes('/tasks/');
  742. OJBetter.typeOfPage.is_homepage = (href === 'https://atcoder.jp/' || href === 'https://atcoder.jp/?lang=ja');
  743. OJBetter.localization.websiteLang = OJB_getGMValue("localizationLanguage", "zh");
  744. OJBetter.localization.scriptLang = OJB_getGMValue("scriptL10nLanguage", "zh");
  745. OJBetter.basic.renderPerfOpt = OJB_getGMValue("renderPerfOpt", false);
  746. OJBetter.basic.commentPaging = OJB_getGMValue("commentPaging", true);
  747. OJBetter.basic.showJumpToLuogu = OJB_getGMValue("showJumpToLuogu", true);
  748. OJBetter.basic.showCF2vjudge = OJB_getGMValue("showCF2vjudge", true);
  749. OJBetter.basic.standingsRecolor = OJB_getGMValue("standingsRecolor", true);
  750. OJBetter.state.notWaiteLoaded = OJB_getGMValue("notWaiteLoaded", false);
  751. OJBetter.translation.targetLang = OJB_getGMValue("transTargetLang", "zh");
  752. OJBetter.translation.choice = OJB_getGMValue("translation", "deepl");
  753. OJBetter.translation.comment.transMode = OJB_getGMValue("commentTranslationMode", "0");
  754. OJBetter.translation.comment.choice = OJB_getGMValue("commentTranslationChoice", "0");
  755. OJBetter.translation.memory.enabled = OJB_getGMValue("memoryTranslateHistory", true);
  756. OJBetter.translation.auto.enabled = OJB_getGMValue("autoTranslation", false);
  757. OJBetter.translation.auto.shortTextLength = OJB_getGMValue("shortTextLength", "2000");
  758. OJBetter.translation.retransAction = OJB_getGMValue("retransAction", "0");
  759. OJBetter.translation.waitTime = OJB_getGMValue("transWaitTime", "200");
  760. OJBetter.translation.auto.mixTrans.enabled = OJB_getGMValue("allowMixTrans", true);
  761. OJBetter.translation.auto.mixTrans.servers = OJB_getGMValue("mixedTranslation", ['deepl', 'iflyrec', 'youdao', 'caiyun']);
  762. OJBetter.common.taskQueue = new TaskQueue();
  763. OJBetter.translation.replaceSymbol = OJB_getGMValue("replaceSymbol", "2");
  764. OJBetter.translation.filterTextWithoutEmphasis = OJB_getGMValue("filterTextWithoutEmphasis", false);
  765. OJBetter.clist.enabled.contest = OJB_getGMValue("showClistRating_contest", false);
  766. OJBetter.clist.enabled.problem = OJB_getGMValue("showClistRating_problem", false);
  767. OJBetter.clist.enabled.problemset = OJB_getGMValue("showClistRating_problemset", false);
  768. OJBetter.clist.ratingHidden = OJB_getGMValue("RatingHidden", false);
  769. OJBetter.clist.authorization = OJB_getGMValue("clist_Authorization", "");
  770. //deepl
  771. OJBetter.deepl.config.type = OJB_getGMValue("deepl_type", "free");
  772. OJBetter.deepl.configs = OJB_getGMValue("deepl_config", {
  773. "choice": "",
  774. "configurations": []
  775. });
  776. if (OJBetter.deepl.configs.choice !== "" && OJBetter.deepl.configs.configurations.length !== 0) {
  777. const choice = OJBetter.deepl.configs.choice;
  778. const configuration = OJBetter.deepl.configs.configurations.find(obj => obj.name === choice);;
  779. if (configuration == undefined) {
  780. let existingConfig = GM_getValue('deepl_config');
  781. existingConfig.choice = "";
  782. GM_setValue('deepl_config', existingConfig);
  783. location.reload();
  784. }
  785. OJBetter.deepl.config.name = configuration.name;
  786. OJBetter.deepl.config.apiGenre = configuration.apiGenre;
  787. OJBetter.deepl.config.key = configuration.key;
  788. OJBetter.deepl.config.proxy = configuration.proxy;
  789. OJBetter.deepl.config.header = OJB_parseLinePairArray(configuration._header);
  790. OJBetter.deepl.config.data = OJB_parseLinePairArray(configuration._data);
  791. OJBetter.deepl.config.quota.url = configuration.quota_url;
  792. OJBetter.deepl.config.quota.method = configuration.quota_method;
  793. OJBetter.deepl.config.quota.header = OJB_parseLinePairArray(configuration.quota_header);
  794. OJBetter.deepl.config.quota.data = OJB_parseLinePairArray(configuration.quota_data);
  795. OJBetter.deepl.config.quota.surplus = configuration.quota_surplus;
  796. }
  797. OJBetter.deepl.enableEmphasisProtection = OJB_getGMValue("enableEmphasisProtection", true);
  798. OJBetter.deepl.enableLinkProtection = OJB_getGMValue("enableLinkProtection", true);
  799. //openai
  800. OJBetter.chatgpt.isStream = OJB_getGMValue("openai_isStream", true);
  801. OJBetter.chatgpt.configs = OJB_getGMValue("chatgpt_config", {
  802. "choice": "",
  803. "configurations": []
  804. });
  805. if (OJBetter.chatgpt.configs.choice !== "" && OJBetter.chatgpt.configs.configurations.length !== 0) {
  806. const choice = OJBetter.chatgpt.configs.choice;
  807. const configuration = OJBetter.chatgpt.configs.configurations.find(obj => obj.name === choice);;
  808. if (configuration == undefined) {
  809. let existingConfig = GM_getValue('chatgpt_config');
  810. existingConfig.choice = "";
  811. GM_setValue('chatgpt_config', existingConfig);
  812. location.reload();
  813. }
  814. OJBetter.chatgpt.config.name = configuration.name;
  815. OJBetter.chatgpt.config.model = configuration.model;
  816. OJBetter.chatgpt.config.key = configuration.key;
  817. OJBetter.chatgpt.config.proxy = configuration.proxy;
  818. OJBetter.chatgpt.config.header = OJB_parseLinePairArray(configuration._header);
  819. OJBetter.chatgpt.config.data = OJB_parseLinePairArray(configuration._data);
  820. OJBetter.chatgpt.config.quota.url = configuration.quota_url;
  821. OJBetter.chatgpt.config.quota.method = configuration.quota_method;
  822. OJBetter.chatgpt.config.quota.header = OJB_parseLinePairArray(configuration.quota_header);
  823. OJBetter.chatgpt.config.quota.data = OJB_parseLinePairArray(configuration.quota_data);
  824. OJBetter.chatgpt.config.quota.surplus = configuration.quota_surplus;
  825. }
  826. // 编辑器
  827. // if (!OJBetter.typeOfPage.is_mSite) OJBetter.common.cf_csrf_token = Codeforces.getCsrfToken();
  828. // else OJBetter.common.cf_csrf_token = "";
  829. OJBetter.common.at_csrf_token = csrfToken;
  830. OJBetter.monaco.compilerSelection = OJB_getGMValue("compilerSelection", "61");
  831. OJBetter.monaco.setting.fontsize = OJB_getGMValue("editorFontSize", "15");
  832. OJBetter.monaco.enableOnProblemPage = OJB_getGMValue("problemPageCodeEditor", true);
  833. OJBetter.monaco.beautifyPreBlocks = OJB_getGMValue("beautifyPreBlocks", true);
  834. OJBetter.monaco.complet.cppCodeTemplate = OJB_getGMValue("cppCodeTemplateComplete", true);
  835. OJBetter.monaco.onlineCompilerChoice = OJB_getGMValue("onlineCompilerChoice", "official");
  836. OJBetter.monaco.setting.isCodeSubmitDoubleConfirm = OJB_getGMValue("isCodeSubmitConfirm", true);
  837. OJBetter.monaco.setting.alwaysConsumeMouseWheel = OJB_getGMValue("alwaysConsumeMouseWheel", true);
  838. OJBetter.monaco.setting.submitButtonPosition = OJB_getGMValue("submitButtonPosition", "bottom");
  839. //自定义补全
  840. OJBetter.monaco.complet.customConfig = OJB_getGMValue("Complet_config", {
  841. "choice": -1,
  842. "configurations": []
  843. });
  844. /**
  845. * 加载monaco编辑器资源
  846. */
  847. OJBetter.monaco.lsp.enabled = OJB_getGMValue("useLSP", false);
  848. OJBetter.monaco.setting.position = OJB_getGMValue("monacoEditor_position", "initial");
  849. OJBetter.monaco.lsp.workUri = OJB_getGMValue("OJBetter_Bridge_WorkUri", "C:/OJBetter_Bridge");
  850. OJBetter.monaco.lsp.socketUrl = OJB_getGMValue("OJBetter_Bridge_SocketUrl", "ws://127.0.0.1:2323/");
  851. if (OJBetter.monaco.enableOnProblemPage || OJBetter.monaco.beautifyPreBlocks) {
  852. let monacoLoader = document.createElement("script");
  853. monacoLoader.src = "https://cdn.staticfile.net/monaco-editor/0.44.0/min/vs/loader.min.js";
  854. document.head.prepend(monacoLoader);
  855. monacoLoader.onload = () => {
  856. require.config({
  857. paths: { vs: "https://cdn.staticfile.net/monaco-editor/0.44.0/min/vs" },
  858. "vs/nls": { availableLanguages: { "*": "zh-cn" } },
  859. });
  860. require(["vs/editor/editor.main"], () => {
  861. OJBetter.monaco.loaderOnload = true;
  862. });
  863. }
  864. }
  865. OJBetter.preference.showLoading = OJB_getGMValue("showLoading", true);
  866. OJBetter.preference.hoverTargetAreaDisplay = OJB_getGMValue("hoverTargetAreaDisplay", false);
  867. OJBetter.basic.expandFoldingblocks = OJB_getGMValue("expandFoldingblocks", true);
  868. OJBetter.preference.iconButtonSize = OJB_getGMValue("iconButtonSize", "16");
  869. OJBetter.about.updateChannel = OJB_getGMValue("updateChannel", "release");
  870. OJBetter.about.updateSource = OJB_getGMValue("updateSource", "greasyfork");
  871. }
  872.  
  873. /**
  874. * 显示警告消息
  875. */
  876. function showWarnMessage() {
  877. if (OJBetter.typeOfPage.is_oldLatex) {
  878. const loadingMessage = new LoadingMessage();
  879. loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('warning.is_oldLatex', { ns: 'alert' })}`, 'warning');
  880. }
  881. if (OJBetter.typeOfPage.is_acmsguru) {
  882. const loadingMessage = new LoadingMessage();
  883. loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('warning.is_acmsguru', { ns: 'alert' })}`, 'warning');
  884. }
  885. if (OJBetter.translation.comment.transMode == "1") {
  886. const loadingMessage = new LoadingMessage();
  887. loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('warning.trans_segment', { ns: 'alert' })}`, 'warning');
  888. }
  889. if (OJBetter.translation.comment.transMode == "2") {
  890. const loadingMessage = new LoadingMessage();
  891. loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('warning.trans_select', { ns: 'alert' })}`, 'warning');
  892. }
  893. if (OJBetter.typeOfPage.is_submitPage && OJBetter.monaco.enableOnProblemPage) {
  894. const loadingMessage = new LoadingMessage();
  895. loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('warning.is_submitPage', { ns: 'alert' })}`, 'warning');
  896. }
  897. }
  898.  
  899. // 常量
  900. 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>';
  901. 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>`;
  902. 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
  903. 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>`;
  904. 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" />
  905. <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" />
  906. <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>`;
  907.  
  908. /**
  909. * 连接数据库
  910. */
  911. async function initDB() {
  912. OJBetter.common.database = new Dexie('OJBetterDB');
  913. OJBetter.common.database.version(3).stores({
  914. samplesData: '&url',
  915. editorCode: '&url',
  916. translateData: '&url',
  917. localizeSubsData: '&lang'
  918. });
  919.  
  920. // 等待数据库打开
  921. await OJBetter.common.database.open();
  922. }
  923.  
  924. /**
  925. * 清空数据库
  926. */
  927. async function clearDatabase() {
  928. const isConfirmed = await OJB_createDialog(
  929. i18next.t('isClearDatabase.title', { ns: 'dialog' }),
  930. i18next.t('isClearDatabase.content', { ns: 'dialog' }),
  931. [
  932. i18next.t('isClearDatabase.buttons.0', { ns: 'dialog' }),
  933. i18next.t('isClearDatabase.buttons.1', { ns: 'dialog' })
  934. ]
  935. );
  936. if (!isConfirmed) {
  937. try {
  938. // 开启一个读写事务,包含数据库中的所有表
  939. await OJBetter.common.database.transaction('rw', OJBetter.common.database.tables, async () => {
  940. // 遍历所有表
  941. for (const table of OJBetter.common.database.tables) {
  942. // 清空当前表
  943. await table.clear();
  944. }
  945. });
  946. console.log("All tables in the database have been cleared.");
  947. alert("All tables in the database have been cleared.");
  948. } catch (error) {
  949. console.error("Error clearing the database:", error);
  950. }
  951. }
  952. }
  953.  
  954. /**
  955. * 导出数据库
  956. * @returns {Promise<string>} 数据库的JSON字符串
  957. */
  958. async function exportDatabase() {
  959. try {
  960. // 创建一个存储数据的对象
  961. const exportData = {};
  962. // 获取数据库中所有表的名称
  963. const tableNames = OJBetter.common.database.tables.map(table => table.name);
  964.  
  965. // 遍历每一个表,获取数据
  966. for (const tableName of tableNames) {
  967. const tableData = await OJBetter.common.database.table(tableName).toArray();
  968. exportData[tableName] = tableData;
  969. }
  970.  
  971. // 将数据对象转换为JSON字符串
  972. const jsonData = JSON.stringify(exportData, null, 4);
  973. return jsonData;
  974. } catch (error) {
  975. console.error("Error exporting database:", error);
  976. }
  977. }
  978.  
  979. /**
  980. * 导入数据库
  981. * @param {string} jsonData 数据库的JSON字符串
  982. */
  983. async function importDatabase(jsonData) {
  984. const isConfirmed = await OJB_createDialog(
  985. i18next.t('isImportDatabase.title', { ns: 'dialog' }),
  986. i18next.t('isImportDatabase.content', { ns: 'dialog' }),
  987. [
  988. i18next.t('isImportDatabase.buttons.0', { ns: 'dialog' }),
  989. i18next.t('isImportDatabase.buttons.1', { ns: 'dialog' })
  990. ]
  991. );
  992. if (!isConfirmed) {
  993. try {
  994. // 将JSON字符串解析为对象
  995. const importData = JSON.parse(jsonData);
  996.  
  997. // 开启一个事务,并清空现有数据
  998. await OJBetter.common.database.transaction('rw', OJBetter.common.database.tables, async () => {
  999. // 清空所有表的数据
  1000. for (const tableName of OJBetter.common.database.tables.map(table => table.name)) {
  1001. await OJBetter.common.database.table(tableName).clear();
  1002. }
  1003.  
  1004. // 插入新数据
  1005. for (const [tableName, rows] of Object.entries(importData)) {
  1006. await OJBetter.common.database.table(tableName).bulkAdd(rows);
  1007. }
  1008. });
  1009. alert("Data imported successfully");
  1010. } catch (error) {
  1011. console.error("Error importing database:", error);
  1012. }
  1013. }
  1014. }
  1015.  
  1016. /**
  1017. * 将数据下载为文件
  1018. * @param {string} data 数据
  1019. * @param {string} filename 文件名,默认为'export.json'
  1020. * @param {string} fileType 文件MIME类型,默认为'application/json'
  1021. * @returns {void}
  1022. */
  1023. function downloadDataAsFile(data, filename = 'export.json', fileType = 'application/json') {
  1024. // 创建一个blob对象,指定文件类型
  1025. const blob = new Blob([data], { type: fileType });
  1026. const url = URL.createObjectURL(blob);
  1027.  
  1028. // 创建一个隐藏的a标签,模拟点击进行下载
  1029. const a = document.createElement('a');
  1030. a.href = url;
  1031. a.download = filename;
  1032. document.body.appendChild(a);
  1033. a.click();
  1034.  
  1035. // 清理
  1036. document.body.removeChild(a);
  1037. URL.revokeObjectURL(url);
  1038. }
  1039.  
  1040.  
  1041. /**
  1042. * 从文件中读取数据
  1043. * @param {Function} callback 回调函数
  1044. * @returns {void}
  1045. */
  1046. function readFileInput(callback) {
  1047. const fileInput = document.createElement('input');
  1048. fileInput.type = 'file';
  1049. fileInput.accept = '.json';
  1050. fileInput.style.display = 'none'; // 隐藏input元素
  1051.  
  1052. fileInput.onchange = (e) => {
  1053. const file = e.target.files[0];
  1054. if (file) {
  1055. const reader = new FileReader();
  1056. reader.onload = (e) => {
  1057. const fileContent = e.target.result;
  1058. if (callback && typeof callback === 'function') {
  1059. callback(fileContent); // 调用回调函数,传入文件内容
  1060. }
  1061. };
  1062. reader.readAsText(file);
  1063. }
  1064. };
  1065.  
  1066. document.body.appendChild(fileInput);
  1067. fileInput.click();
  1068. document.body.removeChild(fileInput);
  1069. }
  1070.  
  1071. /**
  1072. * 删除所有设置
  1073. */
  1074. async function deleteAllConfigSettings() {
  1075. const isConfirmed = await OJB_createDialog(
  1076. i18next.t('isDeleteAllConfigSettings.title', { ns: 'dialog' }),
  1077. i18next.t('isDeleteAllConfigSettings.content', { ns: 'dialog' }),
  1078. [
  1079. i18next.t('isDeleteAllConfigSettings.buttons.0', { ns: 'dialog' }),
  1080. i18next.t('isDeleteAllConfigSettings.buttons.1', { ns: 'dialog' })
  1081. ]
  1082. );
  1083. if (!isConfirmed) {
  1084. const keys = GM_listValues();
  1085.  
  1086. keys.forEach(key => {
  1087. GM_deleteValue(key);
  1088. });
  1089.  
  1090. alert('All settings have been deleted.');
  1091. window.location.reload();
  1092. }
  1093. }
  1094.  
  1095. /**
  1096. * 导出设置到JSON
  1097. * @returns {string} JSON字符串
  1098. */
  1099. function exportSettingsToJSON() {
  1100. const keys = GM_listValues();
  1101. let settings = {};
  1102.  
  1103. keys.forEach(key => {
  1104. settings[key] = GM_getValue(key);
  1105. });
  1106.  
  1107. return JSON.stringify(settings, null, 4);
  1108. }
  1109.  
  1110. /**
  1111. * 从JSON导入设置
  1112. * @param {string} jsonData JSON字符串
  1113. * @returns {void}
  1114. */
  1115. async function importSettingsFromJSON(jsonData) {
  1116. const isConfirmed = await OJB_createDialog(
  1117. i18next.t('isImportSettings.title', { ns: 'dialog' }),
  1118. i18next.t('isImportSettings.content', { ns: 'dialog' }),
  1119. [
  1120. i18next.t('isImportSettings.buttons.0', { ns: 'dialog' }),
  1121. i18next.t('isImportSettings.buttons.1', { ns: 'dialog' })
  1122. ]
  1123. );
  1124. if (!isConfirmed) {
  1125. let settings;
  1126. try {
  1127. settings = JSON.parse(jsonData);
  1128. } catch (e) {
  1129. console.error('JSON parsing error:', e);
  1130. return;
  1131. }
  1132.  
  1133. Object.keys(settings).forEach(key => {
  1134. GM_setValue(key, settings[key]);
  1135. });
  1136.  
  1137. alert('Settings imported successfully!');
  1138. window.location.reload();
  1139. }
  1140. }
  1141.  
  1142. /**
  1143. * 加载元素本地化语言数据
  1144. * @param {JQuery} element jQuery元素
  1145. * @param {number} [retries=10] 重试次数
  1146. * @param {number} [interval=50] 重试间隔
  1147. */
  1148. function elementLocalize(element, retries = 10, interval = 50) {
  1149. if ($.isFunction(element.localize)) {
  1150. element.localize();
  1151. } else if (retries > 0) {
  1152. setTimeout(elementLocalize, interval, element, retries - 1, interval);
  1153. } else {
  1154. console.error('Unable to localize', element);
  1155. }
  1156. }
  1157.  
  1158. // 切换系统黑暗监听
  1159. const mediaQueryList = window.matchMedia('(prefers-color-scheme: dark)');
  1160. const changeEventListeners = [];
  1161. function handleColorSchemeChange(event) {
  1162. event.matches ? $('html').attr('data-theme', 'dark') : $('html').attr('data-theme', 'light');
  1163. if (!event.matches) {
  1164. var originalColor = $(this).data("original-color");
  1165. $(this).css("background-color", originalColor);
  1166. if (OJBetter.monaco.editor) {
  1167. monaco.editor.setTheme('vs');
  1168. }
  1169. } else {
  1170. if (OJBetter.monaco.editor) {
  1171. monaco.editor.setTheme('vs-dark');
  1172. }
  1173. }
  1174. }
  1175.  
  1176. // 黑暗模式
  1177. (function setDark() {
  1178. // 初始化
  1179. function setDarkTheme() {
  1180. const htmlElement = document.querySelector('html');
  1181. if (htmlElement) {
  1182. htmlElement.setAttribute('data-theme', 'dark');
  1183. } else {
  1184. setTimeout(setDarkTheme, 100);
  1185. }
  1186. }
  1187. OJBetter.basic.darkMode = OJB_getGMValue("darkMode", "follow")
  1188. if (OJBetter.basic.darkMode == "dark") {
  1189. setDarkTheme();
  1190. } else if (OJBetter.basic.darkMode == "follow") {
  1191. // 添加事件监听器
  1192. changeEventListeners.push(handleColorSchemeChange);
  1193. mediaQueryList.addEventListener('change', handleColorSchemeChange);
  1194.  
  1195. if (window.matchMedia('(prefers-color-scheme: dark)').matches) setDarkTheme();
  1196. }
  1197.  
  1198. // 定义全局变量
  1199. GM_addStyle(`
  1200. /* 黑暗支持 */
  1201. html[data-theme=dark]:root {
  1202. color-scheme: light dark;
  1203. }
  1204. /* 颜色 */
  1205. :root {
  1206. /* 文字颜色 */
  1207. --ojb-color-text-primary: #a0adb9; /* 主要文字颜色 */
  1208. --ojb-color-text-secondary: #9AA4B1; /* 次要文字颜色 */
  1209. --ojb-color-text-tertiary: #9BA5B2; /* 第三级文字颜色 */
  1210. --ojb-color-text-success: #43A047; /* 成功状态文字颜色 */
  1211. --ojb-color-text-highlight: #cbd6e2; /* 高亮文字颜色 */
  1212. --ojb-color-text-disabled: #506778; /* 禁用状态文字颜色 */
  1213. --ojb-color-text-icon-success: #2e7d32; /* 成功状态图标颜色 */
  1214. --ojb-color-text-link: #4b8eda; /* 链接颜色 */
  1215.  
  1216. /* 背景颜色 */
  1217. --ojb-color-bg-primary: #22272e; /* 主背景颜色 */
  1218. --ojb-color-bg-secondary: #2d333b; /* 次级背景颜色 */
  1219. --ojb-color-bg-disabled: #24292e; /* 禁用元素背景颜色 */
  1220.  
  1221. /* 边框颜色 */
  1222. --ojb-color-border-primary: #48535F; /* 主要边框颜色 */
  1223. --ojb-color-border-disabled: #404950; /* 禁用状态边框颜色 */
  1224. --ojb-color-border-dashed-hover: #03A9F4; /* 虚线边框悬浮颜色 */
  1225. --ojb-color-border-radio-checked: #326154; /* 选中的单选框边框颜色 */
  1226.  
  1227. /* 阴影颜色 */
  1228. --ojb-shadow-standard: 0px 0px 0.5px 0.5px #3A4048; /* 标准阴影 */
  1229. --ojb-shadow-menu-modal: 0px 0px 0px 4px #2d333b; /* 菜单和模态框阴影 */
  1230.  
  1231. /* 区域遮罩颜色 */
  1232. --ojb-overlay-background: repeating-linear-gradient(135deg, #49525f6e, #49525f6e 30px, #49525f29 0px, #49525f29 55px); /* 区域遮罩背景 */
  1233.  
  1234. /* 文字阴影 */
  1235. --ojb-text-shadow-icon: 1px 1px 0px #2d333b, 1px -1px 0px #2d333b, -1px -1px 0px #2d333b, -1px 1px 0px #2d333b; /* 图标文字阴影 */
  1236. }
  1237. /* 边框样式 */
  1238. :root {
  1239. /* 边框样式 */
  1240. --ojb-border-width: 1px; /* 边框宽度 */
  1241. --ojb-border-style-solid: solid; /* 实线样式 */
  1242. --ojb-border-style-dashed: dashed; /* 虚线样式 */
  1243. --ojb-border-radius-small: 4px; /* 小圆角 */
  1244. --ojb-border-radius-medium: 8px; /* 中圆角 */
  1245. --ojb-border-radius-large: 12px; /* 大圆角 */
  1246. /* 组合边框样式 */
  1247. --ojb-border-solid-primary: var(--ojb-border-width) var(--ojb-border-style-solid) var(--ojb-color-border-primary); /* 主要实线边框 */
  1248. --ojb-border-dashed: var(--ojb-border-width) var(--ojb-border-style-dashed) var(--ojb-color-border-primary); /* 主要虚线边框 */
  1249. --ojb-border-dashed-hover: var(--ojb-border-width) var(--ojb-border-style-dashed) var(--ojb-color-border-dashed-hover); /* 悬浮虚线边框 */
  1250. --ojb-border-solid-disabled: var(--ojb-border-width) var(--ojb-border-style-solid) var(--ojb-color-border-disabled); /* 禁用状态实线边框 */
  1251. }
  1252. `);
  1253.  
  1254. // OJBetter界面样式
  1255. GM_addStyle(`
  1256. /* 主要文字颜色 */
  1257. html[data-theme=dark] .alert-success, html[data-theme=dark] .alert-info, html[data-theme=dark] .alert-error,
  1258. html[data-theme=dark] .alert-warning, html[data-theme=dark] .markItUpEditor,
  1259. html[data-theme=dark] .translate-problem-statement, html[data-theme=dark] .OJBetter_setting_menu,
  1260. html[data-theme=dark] .help_tip .tip_text,
  1261. html[data-theme=dark] .OJBetter_setting_menu input, html[data-theme=dark] .OJBetter_setting_menu textarea,
  1262. html[data-theme=dark] #OJBetter_SubmitForm input, html[data-theme=dark] #OJBetter_SubmitForm textarea, html[data-theme=dark] #OJBetter_SubmitForm select,
  1263. html[data-theme=dark] #items-per-page, html[data-theme=dark] #pagBar,
  1264. html[data-theme=dark] .OJBetter_setting_sidebar li a:link,
  1265. html[data-theme=dark] .popup .content{
  1266. color: var(--ojb-color-text-primary);
  1267. }
  1268. /* 次要文字颜色 */
  1269. html[data-theme=dark] .ojb_btn:hover, html[data-theme=dark] .OJBetter_modal button, html[data-theme=dark] #OJBetter_statusBar,
  1270. html[data-theme=dark] #RunTestButton, html[data-theme=dark] #programTypeId, html[data-theme=dark] #addCustomTest,
  1271. html[data-theme=dark] #customTestBlock, html[data-theme=dark] .OJBetter_setting_list.alert_info{
  1272. color: var(--ojb-color-text-secondary);
  1273. }
  1274. /* 文字颜色3 */
  1275. html[data-theme=dark] .ojb_btn{
  1276. color: var(--ojb-color-text-tertiary);
  1277. }
  1278. /* 文字颜色 浅绿 */
  1279. html[data-theme=dark] #SubmitButton{
  1280. color: var(--ojb-color-text-success);
  1281. }
  1282. /* 禁止文字颜色 */
  1283. html[data-theme=dark] .ojb_btn[disabled]{
  1284. color: var(--ojb-color-text-disabled);
  1285. }
  1286. /* 主要背景层次 */
  1287. html[data-theme=dark] .OJBetter_setting_menu, html[data-theme=dark] .help_tip .tip_text, html[data-theme=dark] li#add_button:hover,
  1288. html[data-theme=dark] .ojb_btn:hover,
  1289. html[data-theme=dark] .OJBetter_setting_menu input, html[data-theme=dark] .OJBetter_setting_menu textarea,
  1290. html[data-theme=dark] #OJBetter_SubmitForm input,
  1291. html[data-theme=dark] .OJBetter_setting_menu input[type="checkbox"], html[data-theme=dark] .OJBetter_setting_menu input[type="checkbox"]:checked,
  1292. html[data-theme=dark] #OJBetter_SubmitForm textarea, html[data-theme=dark] #OJBetter_SubmitForm select,
  1293. html[data-theme=dark] .OJBetter_setting_sidebar li a.active, html[data-theme=dark] .OJBetter_setting_sidebar li,
  1294. html[data-theme=dark] .OJBetter_setting_menu::-webkit-scrollbar-track, html[data-theme=dark] .OJBetter_setting_content::-webkit-scrollbar-track,
  1295. html[data-theme=dark] .OJBetter_modal, html[data-theme=dark] .OJBetter_modal button:hover,
  1296. html[data-theme=dark] .popup .content,
  1297. html[data-theme=dark] .config_bar_list, html[data-theme=dark] #LSPLog, html[data-theme=dark] #OJBetter_SubmitForm,
  1298. html[data-theme=dark] .OJBetter_setting_menu .OJBetter_checkboxs,
  1299. html[data-theme=dark] .OJBetter_setting_menu .OJBetter_checkboxs input[type="checkbox"]::before,
  1300. html[data-theme=dark] .OJBetter_setting_menu a, html[data-theme=dark] .OJBetter_setting_menu .OJBetter_setting_list button:hover,
  1301. html[data-theme=dark] .OJBetter_setting_menu select{
  1302. background-color: var(--ojb-color-bg-primary);
  1303. background-image: none;
  1304. }
  1305. /* 次要背景层次 */
  1306. html[data-theme=dark] .ojb_btn,
  1307. html[data-theme=dark] .alert-success, html[data-theme=dark] .alert-info, html[data-theme=dark] .alert-error,
  1308. html[data-theme=dark] .alert-warning, html[data-theme=dark] .SumoSelect>.optWrapper>.options li.opt:hover,
  1309. html[data-theme=dark] .translate-problem-statement-panel,
  1310. html[data-theme=dark] .translate-problem-statement,
  1311. html[data-theme=dark] .OJBetter_setting_list,
  1312. html[data-theme=dark] .OJBetter_setting_menu hr,
  1313. html[data-theme=dark] .OJBetter_setting_sidebar li a,
  1314. html[data-theme=dark] .OJBetter_setting_menu::-webkit-scrollbar-thumb, html[data-theme=dark] .OJBetter_setting_content::-webkit-scrollbar-thumb,
  1315. html[data-theme=dark] .OJBetter_modal button, html[data-theme=dark] .test-for-popup pre,
  1316. html[data-theme=dark] .popup .content pre, html[data-theme=dark] .popup .content pre code,
  1317. html[data-theme=dark] ul.config_bar_ul::-webkit-scrollbar-thumb, html[data-theme=dark] #OJBetter_statusBar,
  1318. html[data-theme=dark] #RunTestButton, html[data-theme=dark] #programTypeId, html[data-theme=dark] .sampleDiv,
  1319. html[data-theme=dark] #addCustomTest, html[data-theme=dark] #LSPLog li:nth-child(odd),
  1320. html[data-theme=dark] .OJBetter_setting_menu .OJBetter_checkboxs input[type="checkbox"]:checked::before,
  1321. html[data-theme=dark] .config::before, html[data-theme=dark] .config li.tempConfig_add_button:hover,
  1322. html[data-theme=dark] .OJBetter_setting_menu details, html[data-theme=dark] #config_bar_menu,
  1323. html[data-theme=dark] .OJBetter_setting_menu .OJBetter_setting_list button,
  1324. html[data-theme=dark] .OJBetter_setting_menu .badge, html[data-theme=dark] #OJBetter_SubmitForm #SubmitButton{
  1325. background-color: var(--ojb-color-bg-secondary);
  1326. }
  1327. /* 禁止背景层次 */
  1328. html[data-theme=dark] .ojb_btn[disabled]{
  1329. background-color: var(--ojb-color-bg-disabled);
  1330. }
  1331. /* 实线边框颜色-圆角 */
  1332. html[data-theme=dark] .alert-success, html[data-theme=dark] .alert-info, html[data-theme=dark] .alert-error,
  1333. html[data-theme=dark] .alert-warning, html[data-theme=dark] .translate-problem-statement{
  1334. border: var(--ojb-border-solid-primary);
  1335. border-radius: 2px;
  1336. }
  1337. /* 实线边框颜色-无圆角 */
  1338. html[data-theme=dark] .ojb_btn,
  1339. html[data-theme=dark] .OJBetter_setting_list, html[data-theme=dark] .config_bar_list,
  1340. html[data-theme=dark] label.config_bar_ul_li_text,
  1341. html[data-theme=dark] .OJBetter_setting_sidebar li, html[data-theme=dark] .OJBetter_setting_menu select,
  1342. html[data-theme=dark] .translate-problem-statement-panel, html[data-theme=dark] .OJBetter_modal button, html[data-theme=dark] #OJBetter_SubmitForm select,
  1343. html[data-theme=dark] #OJBetter_editor, html[data-theme=dark] #OJBetter_statusBar,
  1344. html[data-theme=dark] #OJBetter_SubmitForm #RunTestButton, html[data-theme=dark] #programTypeId, html[data-theme=dark] #customTestBlock,
  1345. html[data-theme=dark] #OJBetter_SubmitForm #addCustomTest, html[data-theme=dark] #OJBetter_SubmitForm #SubmitButton,
  1346. html[data-theme=dark] .OJBetter_setting_menu input,
  1347. html[data-theme=dark] .OJBetter_setting_menu input[type="checkbox"], html[data-theme=dark] .OJBetter_setting_menu input[type="checkbox"]:checked,
  1348. html[data-theme=dark] .OJBetter_setting_menu textarea,
  1349. html[data-theme=dark] #OJBetter_SubmitForm input, html[data-theme=dark] #OJBetter_SubmitForm textarea,
  1350. html[data-theme=dark] #CompilerSetting select, html[data-theme=dark] #CompilerSetting textarea, html[data-theme=dark] #CompilerBox,
  1351. html[data-theme=dark] .OJBetter_setting_menu .OJBetter_checkboxs,
  1352. html[data-theme=dark] .help_tip .tip_text, html[data-theme=dark] .config::before,
  1353. html[data-theme=dark] #statePanel, html[data-theme=dark] .test-case, html[data-theme=dark] .OJBetter_setting_menu .badge{
  1354. border: var(--ojb-border-solid-primary);
  1355. }
  1356. html[data-theme=dark] #customTestBlock #customTests{
  1357. border-top: var(--ojb-border-solid-primary);
  1358. }
  1359. html[data-theme=dark] .OJBetter_setting_sidebar {
  1360. border-right: var(--ojb-border-solid-primary);
  1361. }
  1362. /* 实线边框-禁止 */
  1363. html[data-theme=dark] .ojb_btn[disabled]{
  1364. border: var(--ojb-border-solid-disabled);
  1365. }
  1366. /* 虚线边框 */
  1367. html[data-theme=dark] li#add_button,
  1368. html[data-theme=dark] .OJBetter_setting_menu_label_text{
  1369. border: var(--ojb-border-dashed);
  1370. }
  1371. /* 虚线边框-悬浮 */
  1372. html[data-theme=dark] li#add_button:hover{
  1373. border: var(--ojb-border-dashed-hover);
  1374. background-color: var(--ojb-color-bg-secondary);
  1375. color: var(--ojb-color-border-dashed-hover);
  1376. }
  1377. /* 无边框 */
  1378. html[data-theme=dark] .translate-problem-statement-panel .ojb_btn{
  1379. border: none;
  1380. }
  1381. /* 区域遮罩 */
  1382. html[data-theme=dark] .overlay::before {
  1383. background: var(--ojb-overlay-background);
  1384. color: var(--ojb-color-text-secondary);
  1385. text-shadow: 0px 0px 2px #000000;
  1386. }
  1387. /* 阴影 */
  1388. html[data-theme=dark] .translate-problem-statement-panel, html[data-theme=dark] .translate-problem-statement{
  1389. box-shadow: var(--ojb-shadow-standard);
  1390. }
  1391. /* 图标按钮状态样式 */
  1392. html[data-theme=dark] .ojb_btn_popover.success i:before, html[data-theme=dark] .ojb_btn_popover.success i {
  1393. color: var(--ojb-color-text-icon-success);
  1394. }
  1395. html[data-theme=dark] .ojb_btn_popover i:before {
  1396. text-shadow: var(--ojb-text-shadow-icon);
  1397. }
  1398. /* 其他样式 */
  1399. html[data-theme=dark] .OJBetter_setting_menu, html[data-theme=dark] .OJBetter_modal{
  1400. box-shadow: var(--ojb-shadow-menu-modal);
  1401. border: 1px solid var(--ojb-color-bg-secondary);
  1402. }
  1403. html[data-theme=dark] input[type="radio"]:checked+.OJBetter_setting_menu_label_text {
  1404. color: var(--ojb-color-text-primary);
  1405. border: 1px solid var(--ojb-color-border-radio-checked);
  1406. }
  1407. html[data-theme=dark] .alert{
  1408. text-shadow: none;
  1409. }
  1410. `);
  1411.  
  1412. // 网站界面样式
  1413. GM_addStyle(`
  1414. /* 文字颜色1 */
  1415. html[data-theme=dark] body, html[data-theme=dark] .float-container>#main-container,
  1416. html[data-theme=dark] .panel-default>.panel-heading, html[data-theme=dark] #header a,
  1417. html[data-theme=dark] .pagination>li>a, html[data-theme=dark] .pagination>li>span, html[data-theme=dark] .dropdown-menu,
  1418. html[data-theme=dark] .select2-container--bootstrap .select2-selection--single .select2-selection__rendered,
  1419. html[data-theme=dark] .ace-tm .ace_gutter, html[data-theme=dark] .translate-problem-statement-panel,
  1420. html[data-theme=dark] .select2-container--bootstrap .select2-results__option--highlighted[aria-selected],
  1421. html[data-theme=dark] .nav-pills>li.active>a, html[data-theme=dark] .user-unrated, html[data-theme=dark] #header .header-page li.is-active a,
  1422. html[data-theme=dark] .m-box_inner, html[data-theme=dark] .m-list-job_item, html[data-theme=dark] .a-btn_arrow,
  1423. html[data-theme=dark] #header, html[data-theme=dark] #header .header-sub_page li a,
  1424. html[data-theme=dark] .select2-container--default .select2-selection--single .select2-selection__rendered, html[data-theme=dark] .select2-results{
  1425. color: var(--ojb-color-text-primary) !important;
  1426. }
  1427. /* 文字颜色2 */
  1428. html[data-theme=dark] pre, html[data-theme=dark] .html2mdButton, html[data-theme=dark] .btn-default, html[data-theme=dark] .btn-pre,
  1429. html[data-theme=dark] small.contest-duration, html[data-theme=dark] .select2-container--bootstrap .select2-results__option,
  1430. html[data-theme=dark] #ace_settingsmenu, #kbshortcutmenu, html[data-theme=dark] code{
  1431. color: var(--ojb-color-text-secondary) !important;
  1432. }
  1433. /* 文字颜色3 */
  1434. html[data-theme=dark] input, html[data-theme=dark] #header .header-page li a:hover{
  1435. color: var(--ojb-color-text-secondary);
  1436. }
  1437. /* 文字颜色4 */
  1438. html[data-theme=dark] .katex{
  1439. color: var(--ojb-color-text-highlight) !important;
  1440. }
  1441. /* 链接颜色 */
  1442. html[data-theme=dark] a:link {
  1443. color: var(--ojb-color-text-link);
  1444. }
  1445. html[data-theme=dark] a:visited {
  1446. color: var(--ojb-color-text-secondary);
  1447. }
  1448. /* 按钮 */
  1449. html[data-theme=dark] input:hover, html[data-theme=dark] .btn-default:hover{
  1450. background-color: var(--ojb-color-bg-primary) !important;
  1451. }
  1452. /* 背景层次1 */
  1453. html[data-theme=dark] body, html[data-theme=dark] #main-div.float-container, html[data-theme=dark] pre,
  1454. html[data-theme=dark] .html2mdButton:hover, html[data-theme=dark] .pagination>.active>a, html[data-theme=dark] .ace-tm,
  1455. html[data-theme=dark] .dropdown-menu>li>a:hover, html[data-theme=dark] .dropdown-menu>li>a:focus,
  1456. html[data-theme=dark] .dropdown-menu .divider, html[data-theme=dark] .select2-container--bootstrap .select2-selection,
  1457. html[data-theme=dark] .ace-tm .ace_gutter-active-line, html[data-theme=dark] .select2-dropdown,
  1458. html[data-theme=dark] input, html[data-theme=dark] button, html[data-theme=dark] select, html[data-theme=dark] textarea,
  1459. html[data-theme=dark] code, html[data-theme=dark] #keyvisual .keyvisual-inner:before, html[data-theme=dark] .m-box_inner,
  1460. html[data-theme=dark] .m-list-job_item, html[data-theme=dark] .select2-container--default .select2-selection--single,
  1461. html[data-theme=dark] ol.linenums, html[data-theme=dark] li.L0, html[data-theme=dark] li.L1, html[data-theme=dark] li.L2,
  1462. html[data-theme=dark] li.L3, html[data-theme=dark] li.L4, html[data-theme=dark] li.L5, html[data-theme=dark] li.L6,
  1463. html[data-theme=dark] li.L7, html[data-theme=dark] li.L8, html[data-theme=dark] li.L9{
  1464. background-color: var(--ojb-color-bg-primary) !important;
  1465. }
  1466. /* 背景层次2 */
  1467. html[data-theme=dark] .float-container>#main-container, html[data-theme=dark] #contest-nav-tabs,
  1468. html[data-theme=dark] .btn-default, html[data-theme=dark] .html2mdButton,
  1469. html[data-theme=dark] .nav-tabs>li.active>a, html[data-theme=dark] .nav-tabs>li.active>a:hover, html[data-theme=dark] .nav-tabs>li.active>a:focus,
  1470. html[data-theme=dark] .nav>li>a:hover, html[data-theme=dark] .nav>li>a:focus, html[data-theme=dark] .panel,
  1471. html[data-theme=dark] .table-striped>tbody>tr:nth-of-type(odd), html[data-theme=dark] .insert-participant-box,
  1472. html[data-theme=dark] .btn-pre, html[data-theme=dark] .alert-success, html[data-theme=dark] .alert-info, html[data-theme=dark] .alert-danger,
  1473. html[data-theme=dark] .alert-warning, html[data-theme=dark] .panel-default>.panel-heading,
  1474. html[data-theme=dark] .pagination>li>a, html[data-theme=dark] .pagination>li>span, html[data-theme=dark] .dropdown-menu,
  1475. html[data-theme=dark] .ace-tm .ace_gutter, html[data-theme=dark] .select2-container--bootstrap .select2-results__option[aria-selected=true],
  1476. html[data-theme=dark] #ace_settingsmenu, #kbshortcutmenu, html[data-theme=dark] #header .header-inner,
  1477. html[data-theme=dark] ul#config_bar_ul::-webkit-scrollbar-thumb, html[data-theme=dark] .panel-info>.panel-heading,
  1478. html[data-theme=dark] .post-footer, html[data-theme=dark] .a-btn_arrow:before,
  1479. html[data-theme=dark] .table-hover>tbody>tr:hover,
  1480. html[data-theme=dark] li.L1, html[data-theme=dark] li.L3, html[data-theme=dark] li.L5, html[data-theme=dark] li.L7,
  1481. html[data-theme=dark] li.L9{
  1482. background-color: var(--ojb-color-bg-secondary) !important;
  1483. }
  1484. /* 实线边框颜色-圆角 */
  1485. html[data-theme=dark] input{
  1486. border: var(--ojb-border-solid-primary) !important;
  1487. border-radius: 2px;
  1488. }
  1489. /* 实线边框颜色-无圆角 */
  1490. html[data-theme=dark] .btn-default, html[data-theme=dark] .html2mdButton, html[data-theme=dark] .nav-tabs>li>a:hover,
  1491. html[data-theme=dark] .nav-tabs>li.active>a, html[data-theme=dark] .nav-tabs>li.active>a:hover,
  1492. html[data-theme=dark] .nav-tabs>li.active>a:focus, html[data-theme=dark] .btn-pre, html[data-theme=dark] .btn-pre:hover,
  1493. html[data-theme=dark] pre, html[data-theme=dark] .pagination>li>a, html[data-theme=dark] .pagination>li>span,
  1494. html[data-theme=dark] .table-bordered>thead>tr>th, html[data-theme=dark] .table-bordered>tbody>tr>th, html[data-theme=dark] .table-bordered>tfoot>tr>th,
  1495. html[data-theme=dark] .table-bordered>thead>tr>td, html[data-theme=dark] .table-bordered>tbody>tr>td, html[data-theme=dark] .table-bordered>tfoot>tr>td,
  1496. html[data-theme=dark] .panel, html[data-theme=dark] #editor, html[data-theme=dark] div#config_bar_list, html[data-theme=dark] label.config_bar_ul_li_text,
  1497. html[data-theme=dark] .select2-container--bootstrap .select2-selection, html[data-theme=dark] .select2-container--default .select2-selection--single{
  1498. border: var(--ojb-border-solid-primary) !important;
  1499. }
  1500. html[data-theme=dark] hr, html[data-theme=dark] .panel-footer,
  1501. html[data-theme=dark] .table>thead>tr>th, html[data-theme=dark] .table>tbody>tr>th, html[data-theme=dark] .table>tfoot>tr>th,
  1502. html[data-theme=dark] .table>thead>tr>td, html[data-theme=dark] .table>tbody>tr>td, html[data-theme=dark] .table>tfoot>tr>td{
  1503. border-top: var(--ojb-border-solid-primary) !important;
  1504. }
  1505. html[data-theme=dark] .nav-tabs, html[data-theme=dark] .panel-info>.panel-heading, html[data-theme=dark] .panel-default>.panel-heading,
  1506. html[data-theme=dark] .a-btn_arrow{
  1507. border-bottom: var(--ojb-border-solid-primary) !important;
  1508. }
  1509. html[data-theme=dark] .table>thead>tr>th{
  1510. border-bottom: 2px solid var(--ojb-color-border-primary) !important;
  1511. }
  1512. /* 双实线边框 */
  1513. html[data-theme=dark] #header .header-inner{
  1514. border-bottom: 5px double var(--ojb-color-border-primary) !important;
  1515. }
  1516. /* 阴影 */
  1517. html[data-theme=dark] .float-container>#main-container{
  1518. box-shadow: 0px 0px 10px 5px #fff0;
  1519. }
  1520. /* 图片-亮度 */
  1521. html[data-theme=dark] img{
  1522. opacity: .75;
  1523. }
  1524. /* 反转 */
  1525. html[data-theme=dark] .ace_content, html[data-theme=dark] #header .header-logo img, html[data-theme=dark] pre code{
  1526. filter: invert(1) hue-rotate(.5turn);
  1527. }
  1528. /* 区域遮罩 */
  1529. html[data-theme=dark] .overlay {
  1530. background: repeating-linear-gradient(135deg, #49525f6e, #49525f6e 30px, #49525f29 0px, #49525f29 55px);
  1531. color: #9099a3;
  1532. text-shadow: 0px 0px 2px #000000;
  1533. }
  1534. /* 其他样式 */
  1535. html[data-theme=dark] .nav-tabs>li.active>a, html[data-theme=dark] .nav-tabs>li.active>a:hover, html[data-theme=dark] .nav-tabs>li.active>a:focus{
  1536. border-bottom-color: transparent !important;
  1537. }
  1538. html[data-theme=dark] .collapsible-topic.collapsed .content .collapsible-topic-options:before{
  1539. background-image: linear-gradient(#22272e00, #22272e);
  1540. }
  1541. html[data-theme=dark] .alert{
  1542. text-shadow: none;
  1543. }
  1544. html[data-theme=dark] .m-box-news_post:before{
  1545. background: linear-gradient(0deg, #22272e 50%, rgba(255,255,255,0) 100%);
  1546. }
  1547. html[data-theme=dark] #header .header-sub_page li a:before, html[data-theme=dark] #header .header-page li a:before{
  1548. background-color: #9e9e9e !important;
  1549. }
  1550. html[data-theme=dark] .standings-score{
  1551. color: #2196f3;
  1552. }
  1553. html[data-theme=dark] pre code{
  1554. background-color: transparent !important;
  1555. }
  1556. html[data-theme=dark] #fixed-server-timer {
  1557. color: #000;
  1558. }
  1559. `);
  1560. })()
  1561.  
  1562. /**
  1563. * 黑暗模式额外的处理事件
  1564. */
  1565. function darkModeStyleAdjustment() {
  1566.  
  1567. }
  1568.  
  1569. /**
  1570. * 美化Pre代码块
  1571. */
  1572. async function beautifyPreBlocksWithMonaco() {
  1573. // 用于替换 <pre> 标签为 Monaco 编辑器的函数
  1574. function replacePreWithMonaco(preElement) {
  1575. const pre = $(preElement);
  1576. if (pre.hasClass('source-code-for-copy')) return; // 跳过复制块
  1577. const code = OJB_getCodeFromPre(pre.get(0));
  1578. if (!code) return;
  1579. const language = OJB_codeLangDetect(code);
  1580.  
  1581. // 创建一个用于 Monaco 编辑器的容器
  1582. const container = $('<div></div>');
  1583. const lineCount = code.split('\n').length; // 代码的行数
  1584.  
  1585. // 计算容器的高度
  1586. const calculateContainerHeight = (lineCount) => {
  1587. const lineHeight = 20; // 每行代码的高度
  1588. const minHeight = 100; // 最小高度
  1589. const maxHeight = 1000; // 最大高度
  1590. const dynamicHeight = lineCount * lineHeight;
  1591. return Math.min(Math.max(dynamicHeight, minHeight), maxHeight) + 'px';
  1592. };
  1593.  
  1594. // 应用样式
  1595. container.css({
  1596. height: calculateContainerHeight(lineCount),
  1597. width: '100%'
  1598. });
  1599. pre.replaceWith(container);
  1600.  
  1601. // 初始化 Monaco 编辑器
  1602. monaco.editor.create(container[0], {
  1603. value: code,
  1604. language: language,
  1605. readOnly: true,
  1606. tabSize: 4,
  1607. theme: OJBetter.basic.darkMode == "dark" ? "vs-dark" : "vs",
  1608. scrollbar: {
  1609. verticalScrollbarSize: 10,
  1610. horizontalScrollbarSize: 10,
  1611. alwaysConsumeMouseWheel: false
  1612. },
  1613. automaticLayout: true,
  1614. scrollBeyondLastLine: false
  1615. });
  1616. }
  1617. // 全局替换页面上所有的 <pre> 元素
  1618. $('pre').each(function () {
  1619. replacePreWithMonaco(this);
  1620. });
  1621. // 监听页面上的提交状态页面窗口的 <pre> 元素
  1622. if (OJBetter.typeOfPage.is_statePage) {
  1623. OJB_observeElement({
  1624. selector: '#facebox',
  1625. callback: (node) => {
  1626. // 如果 facebox 中存在 pre 元素,则替换它们
  1627. const preElements = $(node).find('pre');
  1628. preElements.each(function () {
  1629. replacePreWithMonaco(this);
  1630. });
  1631. }
  1632. });
  1633. }
  1634. }
  1635.  
  1636. // 样式
  1637. GM_addStyle(`
  1638. /*动画*/
  1639. @keyframes shake {
  1640. 0% { transform: translateX(-5px); }
  1641. 100% { transform: translateX(5px); }
  1642. }
  1643. @keyframes rotate {
  1644. from {
  1645. transform: rotate(0deg);
  1646. }
  1647.  
  1648. to {
  1649. transform: rotate(360deg);
  1650. }
  1651. }
  1652. @keyframes rippleout {
  1653. 0% {
  1654. box-shadow: 0 0 0 0 rgba(96, 98, 102, 0.2);
  1655. }
  1656.  
  1657. 100% {
  1658. box-shadow: 0 0 0 6px rgba(0, 0, 0, 0);
  1659. }
  1660. }
  1661. @keyframes bounce-in {
  1662. 20%,40%,60%,80%,from,to {
  1663. animation-timing-function: cubic-bezier(.215,.61,.355,1);
  1664. }
  1665.  
  1666. 0% {
  1667. opacity: 0;
  1668. transform: scale3d(.995,.995,.995);
  1669. }
  1670.  
  1671. 20% {
  1672. opacity: 1;
  1673. transform: scale3d(1.005,1.005,1.005);
  1674. }
  1675.  
  1676. 40% {
  1677. transform: scale3d(.998,.998,.998);
  1678. }
  1679.  
  1680. 60% {
  1681. transform: scale3d(1.002,1.002,1.002);
  1682. }
  1683.  
  1684. 80% {
  1685. transform: scale3d(.995,.995,.995);
  1686. }
  1687.  
  1688. to {
  1689. opacity: 1;
  1690. transform: scale3d(1,1,1);
  1691. }
  1692. }
  1693. /*iconfont图标*/
  1694. .iconfont {
  1695. font-family: "iconfont" !important;
  1696. font-size: 16px;
  1697. font-style: normal !important;
  1698. -webkit-font-smoothing: antialiased;
  1699. -moz-osx-font-smoothing: grayscale;
  1700. }
  1701. @font-face {
  1702. font-family: 'iconfont'; /* Project id 4284341 */
  1703. src: url('//aowuucdn.oss-accelerate.aliyuncs.com/iconfont/iconfont.woff2') format('woff2'),
  1704. url('//aowuucdn.oss-accelerate.aliyuncs.com/iconfont/iconfont.woff2.ttf') format('truetype');
  1705. }
  1706. html {
  1707. scroll-behavior: smooth;
  1708. }
  1709. :root {
  1710. --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";
  1711. }
  1712. span.mdViewContent {
  1713. white-space: pre-wrap;
  1714. }
  1715.  
  1716. /* dialog */
  1717. dialog {
  1718. margin: 0px;
  1719. }
  1720. dialog::backdrop {
  1721. background-color: rgba(0, 0, 0, 0.4);
  1722. }
  1723.  
  1724. /*题目页链接栏样式*/
  1725. #problemToolbar {
  1726. display: flex;
  1727. flex-wrap: wrap;
  1728. justify-content: flex-end;
  1729. overflow: auto;
  1730. height: 100%;
  1731. margin: 0.5em;
  1732. }
  1733.  
  1734. /*html2md面板*/
  1735. .html2md-panel {
  1736. display: flex;
  1737. justify-content: flex-end;
  1738. align-items: center;
  1739. }
  1740. .html2md-panel a {
  1741. text-decoration: none;
  1742. }
  1743. .html2md-panel > button {
  1744. margin: 5px;
  1745. }
  1746. .html2md-panel.is_simple {
  1747. position: absolute;
  1748. right: 2%;
  1749. }
  1750.  
  1751. /*通用按钮*/
  1752. .ojb_btn {
  1753. display: flex;
  1754. align-items: center;
  1755. justify-content: center;
  1756. cursor: pointer;
  1757. background-color: #ffffff;
  1758. color: #606266;
  1759. width: auto;
  1760. font-size: 13px;
  1761. border-radius: 0.3rem;
  1762. padding: 2px 5px;
  1763. margin: 0px 5px;
  1764. border: 1px solid #dcdfe6;
  1765. }
  1766. .ojb_btn[disabled] {
  1767. cursor: not-allowed !important;
  1768. color: rgb(168, 171, 178) !important;
  1769. border: 1px solid #e4e7ed;
  1770. background-color: #ffffff;
  1771. }
  1772. .ojb_btn:hover {
  1773. color: #409eff;
  1774. border-color: #409eff;
  1775. background-color: #f1f8ff;
  1776. z-index: 150;
  1777. }
  1778. .ojb_btn.primary {
  1779. color: #ffffff;
  1780. border: 1px solid #409eff;
  1781. background-color: #409eff;
  1782. }
  1783. .ojb_btn.primary:hover {
  1784. color: #ffffff;
  1785. border: 1px solid #79bbff;
  1786. background-color: #79bbff;
  1787. }
  1788. .ojb_btn.success {
  1789. color: #4caf50;
  1790. border: 1px solid #C8E6C9;
  1791. background-color: #f0f9eb;
  1792. }
  1793. .ojb_btn.warning {
  1794. color: #e6a23c;
  1795. border: 1px solid #f3d19e;
  1796. background-color: #fdf6ec;
  1797. }
  1798. .ojb_btn.error {
  1799. color: #f56c6c;
  1800. border: 1px solid #fab6b6;
  1801. background-color: #fef0f0;
  1802. }
  1803. .ojb_btn.enabled {
  1804. color: #42A5F5;
  1805. border: 1px solid #90CAF9;
  1806. background-color: #fafbff;
  1807. }
  1808. .ojb_btn.active {
  1809. animation: rippleout 0.5s ease-in-out;
  1810. }
  1811. a.ojb_btn {
  1812. text-decoration: none;
  1813. }
  1814. a.ojb_btn:link {
  1815. color: #606266;
  1816. }
  1817. a.ojb_btn span {
  1818. margin-left: 2px;
  1819. }
  1820. /*按钮图标和popover*/
  1821. .ojb_btn_popover {
  1822. display: flex;
  1823. justify-content: center;
  1824. position: relative;
  1825. outline: none;
  1826. appearance: none;
  1827. }
  1828. .ojb_btn_popover:hover span {
  1829. opacity: 1;
  1830. visibility: visible;
  1831. }
  1832. .ojb_btn_popover i:before {
  1833. position: absolute;
  1834. text-shadow: 1px 1px 0px #ffffff, 1px -1px 0px #ffffff, -1px -1px 0px #ffffff, -1px 1px 0px #ffffff;
  1835. }
  1836. .ojb_btn_popover span {
  1837. cursor: initial;
  1838. position: absolute;
  1839. left: 50%;
  1840. opacity: 0;
  1841. visibility: hidden;
  1842. padding: 4px 8px;
  1843. background-color: rgba(33, 33, 33, 0.8);
  1844. color: rgba(255, 255, 255, 0.9019607843);
  1845. font-size: 12px;
  1846. border-radius: 6px;
  1847. line-height: 1.6;
  1848. text-align: left;
  1849. white-space: nowrap;
  1850. transition: all 0.15s ease-in-out;
  1851. z-index: 999;
  1852. }
  1853. .ojb_btn_popover span:hover {
  1854. opacity: 0;
  1855. visibility: hidden;
  1856. }
  1857. .ojb_btn_popover.top:hover span {
  1858. transform: translate(-50%, 0);
  1859. }
  1860. .ojb_btn_popover.top span {
  1861. bottom: 100%;
  1862. transform: translate(-50%, -20%);
  1863. margin-bottom: 4px;
  1864. }
  1865. .ojb_btn_popover.top span:hover {
  1866. transform: translate(-50%, -20%);
  1867. }
  1868. .ojb_btn_popover.bottom:hover span {
  1869. transform: translate(-50%, 105%);
  1870. }
  1871. .ojb_btn_popover.bottom span {
  1872. bottom: -2%;
  1873. transform: translate(-50%, 100%);
  1874. margin-top: 4px;
  1875. }
  1876. .ojb_btn_popover.bottom span:hover {
  1877. transform: translate(-50%, 50%);
  1878. }
  1879. .ojb_btn_popover.loading i {
  1880. color: rgba(33, 33, 33, 0.1);
  1881. }
  1882. .ojb_btn_popover.loading i:before {
  1883. content: "\\e640";
  1884. color: rgb(168, 171, 178);
  1885. animation: rotate 2s cubic-bezier(0.65, 0.05, 0.36, 1) infinite;
  1886. }
  1887. .ojb_btn_popover.running i {
  1888. color: rgba(33, 33, 33, 0.1);
  1889. }
  1890. .ojb_btn_popover.running i:before {
  1891. content: "\\e600";
  1892. color: rgb(168, 171, 178);
  1893. animation: rotate 1s linear infinite;
  1894. }
  1895. .ojb_btn_popover.warning i {
  1896. color: rgba(230, 162, 61, 0.8);
  1897. }
  1898. .ojb_btn_popover.warning i:before {
  1899. content: "\\e68b";
  1900. font-size: 15px;
  1901. left: 10px;
  1902. bottom: 0%;
  1903. color: #ff9800;
  1904. }
  1905. .ojb_btn_popover.error i {
  1906. color: rgba(245, 108, 108, 0.8);
  1907. }
  1908. .ojb_btn_popover.error i:before {
  1909. content: "\\e651";
  1910. font-size: 15px;
  1911. left: 10px;
  1912. bottom: 0%;
  1913. color: #F44336;
  1914. }
  1915. .ojb_btn_popover.success i {
  1916. color: rgba(76, 175, 80, 0.9);
  1917. }
  1918. .ojb_btn_popover.success i:before {
  1919. content: "\\e61e";
  1920. font-size: 15px;
  1921. left: 10px;
  1922. bottom: 0%;
  1923. color: #4caf50;
  1924. }
  1925. .ojb_btn_popover.enabled i {
  1926. color: rgba(33, 150, 243, 0.6);
  1927. }
  1928. .ojb_btn_popover.enabled i:before {
  1929. content: "\\e6f4";
  1930. font-size: 15px;
  1931. left: 10px;
  1932. bottom: 0%;
  1933. color: #2196F3;
  1934. }
  1935. .ojb_btn_popover.redo i {
  1936. color: rgba(33, 33, 33, 0.1);
  1937. }
  1938. .ojb_btn_popover.redo i:before {
  1939. content: "\\e831";
  1940. color: #616161;
  1941. }
  1942. .ojb_btn_popover.reverse i {
  1943. transform: rotate(180deg);
  1944. }
  1945.  
  1946. /*translateDiv样式*/
  1947. .translateDiv .topText {
  1948. display: flex;
  1949. margin-left: 5px;
  1950. color: #9e9e9e;
  1951. font-size: 13px;
  1952. align-items: center;
  1953. }
  1954. .translateDiv .borderlessButton{
  1955. display: flex;
  1956. align-items: center;
  1957. margin: 2.5px 7px;
  1958. fill: #9E9E9E;
  1959. }
  1960. .translateDiv .borderlessButton:hover{
  1961. cursor: pointer;
  1962. fill: #059669;
  1963. }
  1964. .translateDiv.bounce-in {
  1965. animation: bounce-in 1s forwards;
  1966. }
  1967. html:not([data-theme='dark']) .translateDiv {
  1968. box-shadow: 0px 0px 0.5px 0.5px #defdf378;
  1969. }
  1970. .translate-problem-statement {
  1971. justify-items: start;
  1972. letter-spacing: 1.8px;
  1973. color: #059669;
  1974. background-color: #f9f9fa;
  1975. border: 1px solid #c5ebdf;
  1976. border-radius: 0rem 0rem 0.3rem 0.3rem;
  1977. padding: 5px;
  1978. margin: -5px 0px 6px 0px;
  1979. width: 100%;
  1980. box-sizing: border-box;
  1981. font-size: 13px;
  1982. }
  1983. .translate-problem-statement h3 {
  1984. font-size: 1.3em;
  1985. font-weight: 700;
  1986. }
  1987. .translate-problem-statement-panel{
  1988. display: flex;
  1989. justify-content: space-between;
  1990. background-color: #f9f9fa;
  1991. border: 1px solid #c5ebdf;
  1992. border-radius: 0.3rem;
  1993. margin: 4px 0px;
  1994. }
  1995. .translate-problem-statement-panel .ojb_btn {
  1996. background: none;
  1997. border: none;
  1998. color: #9e9e9e;
  1999. }
  2000. .translate-problem-statement-panel.error, .translate-problem-statement.error {
  2001. color: red;
  2002. border-color: red;
  2003. }
  2004. .translate-problem-statement a, .translate-problem-statement a:link {
  2005. color: #10b981;
  2006. font-weight: 600;
  2007. background: 0 0;
  2008. text-decoration: none;
  2009. }
  2010. .translate-problem-statement ol, .translate-problem-statement ul {
  2011. display: grid;
  2012. margin-inline-start: 0.8em;
  2013. margin-block-start: 0em;
  2014. margin: 0.5em 0 0 3em;
  2015. padding-inline-start: 0px;
  2016. }
  2017. .translate-problem-statement li {
  2018. display: list-item;
  2019. height: auto;
  2020. word-wrap: break-word;
  2021. }
  2022. .translate-problem-statement ol li {
  2023. list-style-type: auto;
  2024. }
  2025. .translate-problem-statement ul li {
  2026. list-style-type: disc;
  2027. }
  2028. .translate-problem-statement img {
  2029. max-width: 100.0%;
  2030. max-height: 100.0%;
  2031. }
  2032. #task-statement .translate-problem-statement .MathJax {
  2033. color: #059669!important;
  2034. }
  2035. .translate-problem-statement span.math {
  2036. margin: 0px 2.5px !important;
  2037. }
  2038. .translate-problem-statement a:hover {
  2039. background-color: #800;
  2040. color: #fff;
  2041. text-decoration: none;
  2042. }
  2043. .translate-problem-statement table {
  2044. border: 1px #ccc solid !important;
  2045. margin: 1.5em 0 !important;
  2046. color: #059669 !important;
  2047. }
  2048. .translate-problem-statement table thead th {
  2049. border: 1px #ccc solid !important;
  2050. color: #059669 !important;
  2051. }
  2052. .translate-problem-statement table td {
  2053. border-right: 1px solid #ccc;
  2054. border-top: 1px solid #ccc;
  2055. padding: 0.7143em 0.5em;
  2056. }
  2057. .translate-problem-statement table th {
  2058. padding: 0.7143em 0.5em;
  2059. }
  2060. .translate-problem-statement p:not(:first-child) {
  2061. margin: 1.5em 0 0;
  2062. }
  2063. .translate-problem-statement p {
  2064. line-height: 20px !important;
  2065. word-wrap: break-word;
  2066. font-size: 13px !important
  2067. }
  2068. .problem-statement p:last-child {
  2069. margin-bottom: 0px !important;
  2070. }
  2071.  
  2072. /*设置按钮*/
  2073. header .enter-or-register-box, header .languages {
  2074. position: absolute;
  2075. right: 170px;
  2076. }
  2077. .ojb_btn.OJBetter_setting {
  2078. float: right;
  2079. height: 30px;
  2080. background: #60a5fa;
  2081. color: white;
  2082. margin: 10px;
  2083. border: 1px solid #60a5fa;
  2084. }
  2085. .ojb_btn.OJBetter_setting.open {
  2086. background-color: #e6e6e6;
  2087. color: #727378;
  2088. cursor: not-allowed;
  2089. }
  2090.  
  2091. /*设置面板*/
  2092. .OJBetter_setting_menu {
  2093. box-shadow: 0px 0px 0px 4px #ffffff;
  2094. position: fixed;
  2095. top: 50%;
  2096. left: 50%;
  2097. width: 600px;
  2098. min-height: 600px;
  2099. transform: translate(-50%, -50%);
  2100. border-radius: 6px;
  2101. background-color: #f0f4f9;
  2102. border-collapse: collapse;
  2103. border: 1px solid #ffffff;
  2104. color: #697e91;
  2105. font-family: var(--vp-font-family-base);
  2106. padding: 10px 20px 20px 10px;
  2107. box-sizing: content-box;
  2108. }
  2109. .OJBetter_setting_menu h3 {
  2110. margin-top: 10px;
  2111. font-size: 1.4em;
  2112. font-weight: 700;
  2113. }
  2114. .OJBetter_setting_menu h4 {
  2115. margin: 15px 0px 10px 0px;
  2116. }
  2117. .OJBetter_setting_menu h4,.OJBetter_setting_menu h5 {
  2118. font-weight: 600;
  2119. }
  2120. .OJBetter_setting_menu hr {
  2121. border: none;
  2122. height: 1px;
  2123. background-color: #ccc;
  2124. margin: 10px 0;
  2125. }
  2126. .OJBetter_setting_menu details {
  2127. padding: 10px;
  2128. margin-bottom: 5px;
  2129. background-color: #ffffff;
  2130. border-bottom: 1px solid #c9c6c696;
  2131. border-radius: 8px;
  2132. }
  2133. .OJBetter_setting_menu .badge {
  2134. border-radius: 4px;
  2135. border: 1px solid #009688;
  2136. color: #009688;
  2137. background-color: #fff;
  2138. padding: 0.5px 4px;
  2139. margin-left: 5px;
  2140. margin-right: auto;
  2141. line-height: initial;
  2142. font-weight: initial;
  2143. }
  2144. .OJBetter_setting_menu .missing {
  2145. box-shadow: inset 0px 0px 1px 1px red;
  2146. }
  2147. /* 页面切换 */
  2148. .OJBetter_setting_menu .settings-page {
  2149. display: none;
  2150. }
  2151. .OJBetter_setting_menu .settings-page.active {
  2152. display: block;
  2153. }
  2154. .OJBetter_setting_container {
  2155. display: flex;
  2156. }
  2157. .OJBetter_setting_sidebar {
  2158. flex: 0 0 auto;
  2159. min-width: 110px;
  2160. padding: 6px 10px 6px 6px;
  2161. margin: 20px 0px;
  2162. border-right: 1px solid #d4d8e9;
  2163. }
  2164. .OJBetter_setting_content {
  2165. flex-grow: 1;
  2166. margin: 20px 0px 0px 12px;
  2167. padding-right: 10px;
  2168. max-height: 580px;
  2169. overflow-y: auto;
  2170. box-sizing: border-box;
  2171. }
  2172. .OJBetter_setting_sidebar h3 {
  2173. margin-top: 0;
  2174. }
  2175. .OJBetter_setting_sidebar hr {
  2176. margin-top: 10px;
  2177. margin-bottom: 10px;
  2178. border: none;
  2179. border-top: 1px solid #DADCE0;
  2180. }
  2181. .OJBetter_setting_sidebar ul {
  2182. list-style-type: none;
  2183. margin: 0;
  2184. padding: 0;
  2185. }
  2186. .OJBetter_setting_sidebar li {
  2187. margin: 5px 0px;
  2188. background-color: #ffffff;
  2189. border: 1px solid #d4d8e9;
  2190. border-radius: 4px;
  2191. font-size: 16px;
  2192. }
  2193. .OJBetter_setting_sidebar li a {
  2194. text-decoration: none;
  2195. display: flex;
  2196. width: 100%;
  2197. font-size: 16px;
  2198. color: gray;
  2199. background-color: #ffffff;
  2200. border: none;
  2201. letter-spacing: 2px;
  2202. padding: 7px;
  2203. margin: 0px;
  2204. border-radius: 4px;
  2205. align-items: center;
  2206. -webkit-box-sizing: border-box;
  2207. -moz-box-sizing: border-box;
  2208. box-sizing: border-box;
  2209. }
  2210. .OJBetter_setting_sidebar li a.active {
  2211. background-color: #eceff1c7;
  2212. }
  2213. /* 链接样式 */
  2214. .OJBetter_setting_menu a {
  2215. font-size: 13px;
  2216. color: #009688;
  2217. background-color: #E0F2F1;
  2218. border: 1px solid #009688;
  2219. border-radius: 4px;
  2220. padding: 0px 5px;
  2221. margin: 0px 5px;
  2222. text-decoration: none;
  2223. }
  2224. /* 下拉选择框 */
  2225. .OJBetter_setting_menu select {
  2226. appearance: none;
  2227. padding: 5px 10px;
  2228. margin: -5px 0px;
  2229. border-radius: 6px;
  2230. border-style: solid;
  2231. border: 1px solid #ced4da;
  2232. color: #009688;
  2233. background: #ffffff;
  2234. font-size: 15px;
  2235. }
  2236. .OJBetter_setting_menu select:focus-visible {
  2237. outline: none;
  2238. }
  2239. .OJBetter_setting_menu select option:disabled {
  2240. color: #EEEEEE;
  2241. }
  2242. /* 数值输入框 */
  2243. .OJBetter_setting_menu input[type="number"] {
  2244. width: 40px;
  2245. color: #009688;
  2246. font-size: 15px;
  2247. appearance: none;
  2248. padding: 5px 10px;
  2249. margin: -5px 3px;
  2250. border-radius: 6px;
  2251. border-style: solid;
  2252. border: 1px solid #ced4da;
  2253. }
  2254. .OJBetter_setting_menu input[type="number"]:focus-visible {
  2255. outline: none;
  2256. }
  2257. .OJBetter_setting_menu input[type="number"]::-webkit-inner-spin-button,
  2258. .OJBetter_setting_menu input[type="number"]::-webkit-outer-spin-button {
  2259. -webkit-appearance: none;
  2260. margin: 0;
  2261. }
  2262. /*设置面板-滚动条*/
  2263. .OJBetter_setting_menu::-webkit-scrollbar, .OJBetter_setting_content::-webkit-scrollbar,
  2264. .OJBetter_modal .content::-webkit-scrollbar {
  2265. width: 5px;
  2266. height: 7px;
  2267. background-color: #aaa;
  2268. }
  2269. .OJBetter_setting_menu::-webkit-scrollbar-thumb, .OJBetter_setting_content::-webkit-scrollbar-thumb,
  2270. .OJBetter_modal .content::-webkit-scrollbar-thumb {
  2271. background-clip: padding-box;
  2272. background-color: #d7d9e4;
  2273. }
  2274. .OJBetter_setting_menu::-webkit-scrollbar-track, .OJBetter_setting_content::-webkit-scrollbar-track,
  2275. .OJBetter_modal .content::-webkit-scrollbar-track {
  2276. background-color: #f1f1f1;
  2277. }
  2278. /*设置面板-关闭按钮*/
  2279. .OJBetter_setting_menu .tool-box {
  2280. position: absolute;
  2281. width: 20px;
  2282. height: 20px;
  2283. top: 3px;
  2284. right: 3px;
  2285. }
  2286. .OJBetter_setting_menu .btn-close {
  2287. width: 20px;
  2288. height: 20px;
  2289. border-radius: 50%;
  2290. border: none;
  2291. margin: 0px;
  2292. padding: 0px;
  2293. background-color: #ff000080;
  2294. transition: .15s ease all;
  2295. box-sizing: border-box;
  2296. text-align: center;
  2297. color: transparent;
  2298. }
  2299. .OJBetter_setting_menu .iconfont {
  2300. font-size: 10px;
  2301. font-weight: bolder;
  2302. }
  2303. .OJBetter_setting_menu .btn-close:hover {
  2304. color: #ffffff;
  2305. background-color: #ff0000cc;
  2306. box-shadow: 0 5px 5px 0 #00000026;
  2307. }
  2308. .OJBetter_setting_menu .btn-close:active {
  2309. color: #ffffffde;
  2310. background-color: #ff000080;
  2311. }
  2312. /*设置面板-checkbox*/
  2313. .OJBetter_setting_menu input[type=checkbox]:focus {
  2314. outline: 0px;
  2315. }
  2316. .OJBetter_setting_menu .OJBetter_setting_list input[type="checkbox"] {
  2317. margin: 0px;
  2318. appearance: none;
  2319. -webkit-appearance: none;
  2320. width: 40px;
  2321. height: 20px;
  2322. border: 1.5px solid #D7CCC8;
  2323. padding: 0px !important;
  2324. border-radius: 20px;
  2325. background: #efebe978;
  2326. position: relative;
  2327. box-sizing: border-box;
  2328. }
  2329. .OJBetter_setting_menu .OJBetter_setting_list input[type="checkbox"]::before {
  2330. content: "";
  2331. width: 17px;
  2332. height: 17px;
  2333. background: #D7CCC8;
  2334. border: 1.5px solid #BCAAA4;
  2335. border-radius: 50%;
  2336. position: absolute;
  2337. top: 0;
  2338. left: 0;
  2339. transform: translate(2%, 2%);
  2340. transition: all 0.3s ease-in-out;
  2341. box-sizing: border-box;
  2342. }
  2343. .OJBetter_setting_menu .OJBetter_setting_list input[type="checkbox"]::after {
  2344. 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");
  2345. position: absolute;
  2346. top: 0;
  2347. left: 24px;
  2348. }
  2349. .OJBetter_setting_menu .OJBetter_setting_list input[type="checkbox"]:checked {
  2350. border: 1.5px solid #C5CAE9;
  2351. background: #E8EAF6;
  2352. }
  2353. .OJBetter_setting_menu .OJBetter_setting_list input[type="checkbox"]:checked::before {
  2354. background: #C5CAE9;
  2355. border: 1.5px solid #7986CB;
  2356. transform: translate(122%, 2%);
  2357. transition: all 0.3s ease-in-out;
  2358. }
  2359. .OJBetter_setting_menu .OJBetter_setting_list input[type="checkbox"]:checked::after {
  2360. 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");
  2361. position: absolute;
  2362. top: 1.5px;
  2363. left: 4.5px;
  2364. }
  2365. .OJBetter_setting_menu .OJBetter_setting_list button {
  2366. cursor: pointer;
  2367. color: #7986cb;
  2368. background-color: #e8eaf6;
  2369. border: 1px solid #7986cb;
  2370. border-radius: 6px;
  2371. width: 100px;
  2372. margin: -5px 2px;
  2373. padding: 5px 10px;
  2374. }
  2375. .OJBetter_setting_menu .OJBetter_setting_list button:hover {
  2376. color: #e8eaf6;
  2377. background-color: #7986cb;
  2378. border: 1px solid #7986cb;
  2379. }
  2380. .OJBetter_setting_menu label, #darkMode_span, #loaded_span {
  2381. font-size: 16px;
  2382. }
  2383. .OJBetter_setting_list {
  2384. display: flex;
  2385. flex-wrap: wrap;
  2386. align-items: center;
  2387. padding: 10px;
  2388. margin: 5px 0px;
  2389. background-color: #ffffff;
  2390. border: 1px solid #c9c6c642;
  2391. border-bottom-color: #c9c6c696;
  2392. border-radius: 8px;
  2393. justify-content: space-between;
  2394. }
  2395. .OJBetter_setting_list.alert_danger {
  2396. color: #F44336;
  2397. background-color: #FFEBEE;
  2398. border: 1px solid #F44336;
  2399. margin: 10px 0px;
  2400. }
  2401. .OJBetter_setting_list.alert_warn {
  2402. color: #E65100;
  2403. background-color: #FFF3E0;
  2404. border: 1px solid #FF9800;
  2405. margin: 10px 0px;
  2406. }
  2407. .OJBetter_setting_list.alert_tip {
  2408. color: #009688;
  2409. background-color: #E0F2F1;
  2410. border: 1px solid #009688;
  2411. margin: 10px 0px;
  2412. }
  2413. .OJBetter_setting_list.alert_info {
  2414. color: #ffffff;
  2415. background-color: #009688;
  2416. margin: 10px 0px;
  2417. box-shadow: rgba(0, 0, 0, 0.06) 0px 2px 4px 0px inset;
  2418. }
  2419. .OJBetter_setting_list p:not(:last-child) {
  2420. margin-bottom: 10px;
  2421. }
  2422. .OJBetter_setting_list p:not(:first-child) {
  2423. margin-top: 10px;
  2424. }
  2425. /*设置面板-checkboxs*/
  2426. .OJBetter_setting_menu .OJBetter_checkboxs {
  2427. flex-basis: 100%;
  2428. display: flex;
  2429. padding: 8px;
  2430. margin: 10px 0px 0px 0px;
  2431. border-bottom: 1px solid #c9c6c696;
  2432. border-radius: 8px;
  2433. border: 1px solid #c5cae9;
  2434. background-color: #f0f8ff;
  2435. }
  2436. .OJBetter_setting_menu .OJBetter_checkboxs label {
  2437. font-size: 13px;
  2438. margin: 0px 6px 0px 3px;
  2439. }
  2440. .OJBetter_setting_menu .OJBetter_checkboxs input[type=checkbox]:checked+label{
  2441. color: #7986cb;
  2442. }
  2443. .OJBetter_setting_menu .OJBetter_checkboxs input[type="checkbox"] {
  2444. border: none;
  2445. width: 16px;
  2446. height: 16px;
  2447. }
  2448. .OJBetter_setting_menu .OJBetter_checkboxs input[type="checkbox"]::before{
  2449. background: #ffffff;
  2450. transform: none;
  2451. width: 16px;
  2452. height: 16px;
  2453. }
  2454. .OJBetter_setting_menu .OJBetter_checkboxs input[type="checkbox"]:checked {
  2455. background: none;
  2456. border: none;
  2457. }
  2458. .OJBetter_setting_menu .OJBetter_checkboxs input[type="checkbox"]:checked::before {
  2459. border: 1.5px solid #95a2de;
  2460. background: #e8eaf6;
  2461. transform: none;
  2462. }
  2463. .OJBetter_setting_menu .OJBetter_checkboxs input[type="checkbox"]:checked::after {
  2464. 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");
  2465. top: 0px;
  2466. left: 3.5px;
  2467. }
  2468. .OJBetter_setting_menu .OJBetter_checkboxs input[type="checkbox"]:disabled+label {
  2469. color: #BDBDBD;
  2470. }
  2471. /*设置面板-radio*/
  2472. .OJBetter_setting_menu label {
  2473. display: block;
  2474. font-weight: initial;
  2475. list-style-type: none;
  2476. padding-inline-start: 0px;
  2477. overflow-x: auto;
  2478. max-width: 100%;
  2479. margin: 3px 0px;
  2480. overflow-x: visible;
  2481. }
  2482. .OJBetter_setting_menu_label_text {
  2483. display: flex;
  2484. border: 1px dashed #00aeeccc;
  2485. height: 35px;
  2486. width: 100%;
  2487. color: #6e6e6e;
  2488. font-weight: 300;
  2489. font-size: 14px;
  2490. letter-spacing: 2px;
  2491. padding: 7px;
  2492. margin-bottom: 4px;
  2493. align-items: center;
  2494. -webkit-box-sizing: border-box;
  2495. -moz-box-sizing: border-box;
  2496. box-sizing: border-box;
  2497. }
  2498. input[type="radio"]:checked+.OJBetter_setting_menu_label_text {
  2499. background: #41e49930;
  2500. border: 1px solid green;
  2501. color: green;
  2502. text-shadow: 0px 0px 0.5px green;
  2503. }
  2504. input[type="radio"]:disabled+.OJBetter_setting_menu_label_text {
  2505. background: #fafafa00;
  2506. border: 1px solid #e0e0e07a;
  2507. color: #e0e0e0;
  2508. }
  2509. .OJBetter_setting_menu label input[type="radio"], .OJBetter_contextmenu label input[type="radio"]{
  2510. appearance: none;
  2511. list-style: none;
  2512. padding: 0px !important;
  2513. margin: 0px;
  2514. clip: rect(0 0 0 0);
  2515. -webkit-clip-path: inset(100%);
  2516. clip-path: inset(100%);
  2517. height: 1px;
  2518. overflow: hidden;
  2519. position: absolute;
  2520. white-space: nowrap;
  2521. width: 1px;
  2522. }
  2523. /*设置面板-文本输入框*/
  2524. .OJBetter_setting_menu input[type="text"] {
  2525. display: block;
  2526. height: 25px !important;
  2527. width: 100%;
  2528. background-color: #ffffff;
  2529. color: #727378;
  2530. font-size: 12px;
  2531. border-radius: 0.3rem;
  2532. padding: 1px 5px !important;
  2533. box-sizing: border-box;
  2534. margin: 5px 0px 5px 0px;
  2535. border: 1px solid #00aeeccc;
  2536. box-shadow: 0 0 1px #0000004d;
  2537. }
  2538. .OJBetter_setting_menu .OJBetter_setting_list input[type="text"] {
  2539. margin-left: 5px;
  2540. }
  2541. .OJBetter_setting_menu input[type="text"]:focus-visible{
  2542. border-style: solid;
  2543. border-color: #3f51b5;
  2544. outline: none;
  2545. }
  2546. .OJBetter_setting_menu_config_box {
  2547. width: 100%;
  2548. display: grid;
  2549. margin-top: 5px;
  2550. -webkit-box-sizing: border-box;
  2551. -moz-box-sizing: border-box;
  2552. box-sizing: border-box;
  2553. }
  2554. .OJBetter_setting_menu input::placeholder {
  2555. color: #727378;
  2556. }
  2557. .OJBetter_setting_menu input.no_default::placeholder{
  2558. color: #BDBDBD;
  2559. }
  2560. .OJBetter_setting_menu input.is_null::placeholder{
  2561. color: red;
  2562. border-width: 1.5px;
  2563. }
  2564. .OJBetter_setting_menu input.is_null{
  2565. border-color: red;
  2566. }
  2567. .OJBetter_setting_menu textarea {
  2568. resize: vertical;
  2569. display: block;
  2570. width: 100%;
  2571. height: 60px;
  2572. background-color: #ffffff;
  2573. color: #727378;
  2574. font-size: 12px;
  2575. padding: 1px 5px !important;
  2576. box-sizing: border-box;
  2577. margin: 5px 0px 5px 0px;
  2578. border: 1px solid #00aeeccc;
  2579. box-shadow: 0 0 1px #0000004d;
  2580. }
  2581. .OJBetter_setting_menu textarea:focus-visible{
  2582. border-style: solid;
  2583. border-color: #3f51b5;
  2584. outline: none;
  2585. }
  2586. .OJBetter_setting_menu textarea::placeholder{
  2587. color: #BDBDBD;
  2588. font-size: 14px;
  2589. }
  2590. .OJBetter_setting_menu #tempConfig_save {
  2591. cursor: pointer;
  2592. display: inline-flex;
  2593. padding: 5px;
  2594. background-color: #1aa06d;
  2595. color: #ffffff;
  2596. font-size: 14px;
  2597. line-height: 1.5rem;
  2598. font-weight: 500;
  2599. justify-content: center;
  2600. width: 100%;
  2601. border-radius: 0.375rem;
  2602. border: none;
  2603. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  2604. margin-top: 20px
  2605. }
  2606. .OJBetter_setting_menu button#debug_button.debug_button {
  2607. width: 18%;
  2608. }
  2609. .OJBetter_setting_menu span.tip {
  2610. color: #999;
  2611. font-size: 12px;
  2612. font-weight: 500;
  2613. padding: 5px 0px;
  2614. }
  2615. /*设置面板-tip*/
  2616. .help_tip {
  2617. margin-right: auto;
  2618. }
  2619. span.input_label {
  2620. font-size: 14px;
  2621. }
  2622. .help_tip .tip_text {
  2623. display: none;
  2624. position: absolute;
  2625. color: #697e91;
  2626. font-weight: 400;
  2627. font-size: 14px;
  2628. letter-spacing: 0px;
  2629. background-color: #ffffff;
  2630. padding: 10px;
  2631. margin: 5px 0px;
  2632. border-radius: 4px;
  2633. border: 1px solid #e4e7ed;
  2634. box-shadow: 0px 0px 12px rgba(0, 0, 0, .12);
  2635. z-index: 100;
  2636. }
  2637. .help_tip .tip_text p {
  2638. margin-bottom: 5px;
  2639. }
  2640. .help_tip .tip_text:before {
  2641. content: "";
  2642. position: absolute;
  2643. top: -20px;
  2644. right: -10px;
  2645. bottom: -10px;
  2646. left: -10px;
  2647. z-index: -1;
  2648. }
  2649. .help-icon {
  2650. cursor: help;
  2651. width: 15px;
  2652. color: #b4b9d4;
  2653. margin-left: 5px;
  2654. margin-top: 3px;
  2655. }
  2656. .OJBetter_setting_menu .OJBetter_setting_menu_label_text .help_tip .help-icon {
  2657. color: #7fbeb2;
  2658. }
  2659. .help_tip .help-icon:hover + .tip_text, .help_tip .tip_text:hover {
  2660. display: block;
  2661. cursor: help;
  2662. width: 250px;
  2663. }
  2664. /* 版本信息 */
  2665. .OJBetter_setting_menu .versionInfo{
  2666. display: grid;
  2667. justify-items: center;
  2668. font-size: 16px;
  2669. padding: 10px;
  2670. }
  2671. .OJBetter_setting_menu .versionInfo>* {
  2672. margin: 10px 0px;
  2673. }
  2674.  
  2675. /* 配置管理面板 */
  2676. .config{
  2677. width: 100%;
  2678. margin: 10px 0px;
  2679. }
  2680. .config li.tempConfig_add_button {
  2681. cursor: pointer;
  2682. height: 40px;
  2683. border: 1px dashed #BDBDBD;
  2684. border-radius: 8px;
  2685. background-color: #fcfbfb36;
  2686. color: #bdbdbd;
  2687. font-size: 14px;
  2688. align-items: center;
  2689. justify-content: center;
  2690. }
  2691. .config li.tempConfig_add_button:hover {
  2692. border: 1px dashed #03A9F4;
  2693. background-color: #d7f0fb8c;
  2694. color: #03A9F4;
  2695. }
  2696. .config .config_bar_list {
  2697. display: flex;
  2698. width: 100%;
  2699. padding-bottom: 2px;
  2700. border: 1px solid #c5cae9;
  2701. background-color: #f0f8ff;
  2702. box-sizing: border-box;
  2703. border-radius: 0px 0px 8px 8px;
  2704. }
  2705. .config .config_bar_list input[type="radio"] {
  2706. appearance: none;
  2707. width: 0;
  2708. height: 0;
  2709. overflow: hidden;
  2710. }
  2711. .config .config_bar_list input[type="radio"] {
  2712. margin: 0px;
  2713. }
  2714. .config .config_bar_list input[type=radio]:focus {
  2715. outline: 0px;
  2716. }
  2717. .config .config_bar_ul_li_text {
  2718. display: flex;
  2719. align-items: center;
  2720. justify-content: center;
  2721. max-width: 100%;
  2722. height: 40px;
  2723. overflow-x: auto;
  2724. font-size: 14px;
  2725. font-weight: 400;
  2726. margin: 0px 4px;
  2727. padding: 3px;
  2728. border: 1px solid #dedede;
  2729. border-radius: 10px;
  2730. box-shadow: 0px 2px 4px 0px rgba(0,0,0,.05);
  2731. box-sizing: border-box;
  2732. }
  2733. .config .config_bar_ul li button {
  2734. background-color: #e6e6e6;
  2735. color: #727378;
  2736. height: 23px;
  2737. font-size: 14px;
  2738. border-radius: 0.3rem;
  2739. padding: 1px 5px;
  2740. margin: 5px;
  2741. border: none;
  2742. box-shadow: 0 0 1px #0000004d;
  2743. }
  2744. .config .config_bar_ul {
  2745. display: flex;
  2746. align-items: center;
  2747. list-style-type: none;
  2748. padding-inline-start: 0px;
  2749. overflow-x: auto;
  2750. max-width: 100%;
  2751. margin: 0px;
  2752. padding: 5px;
  2753. }
  2754. .config .config_bar_ul li {
  2755. width: 80px;
  2756. display: grid;
  2757. margin: 4px 4px;
  2758. min-width: 100px;
  2759. box-sizing: border-box;
  2760. }
  2761. .config .config_bar_ul_li_text:hover {
  2762. background-color: #eae4dc24;
  2763. }
  2764. input[type="radio"]:checked + .config_bar_ul_li_text {
  2765. background: #41b3e430;
  2766. border: 1px solid #5e7ce0;
  2767. color: #5e7ce0;
  2768. }
  2769. .config .config_bar_ul::-webkit-scrollbar {
  2770. width: 5px;
  2771. height: 4px;
  2772. }
  2773. .config .config_bar_ul::-webkit-scrollbar-thumb {
  2774. background-clip: padding-box;
  2775. background-color: #d7d9e4;
  2776. border-radius: 8px;
  2777. }
  2778. .config .config_bar_ul::-webkit-scrollbar-button:start:decrement {
  2779. width: 4px;
  2780. background-color: transparent;
  2781. }
  2782. .config .config_bar_ul::-webkit-scrollbar-button:end:increment {
  2783. width: 4px;
  2784. background-color: transparent;
  2785. }
  2786. .config .config_bar_ul::-webkit-scrollbar-track {
  2787. border-radius: 5px;
  2788. }
  2789. .config .config_bar_ul_li_text::-webkit-scrollbar {
  2790. width: 5px;
  2791. height: 7px;
  2792. background-color: #aaa;
  2793. }
  2794. .config .config_bar_ul_li_text::-webkit-scrollbar-thumb {
  2795. background-clip: padding-box;
  2796. background-color: #d7d9e4;
  2797. }
  2798. .config .config_bar_ul_li_text::-webkit-scrollbar-track {
  2799. background-color: #f1f1f1;
  2800. }
  2801. .config .config_bar_list_add_div {
  2802. display: flex;
  2803. height: 40px;
  2804. margin: 4px 2px;
  2805. }
  2806.  
  2807. /* 修改菜单 */
  2808. #config_bar_menu {
  2809. z-index: 400;
  2810. position: fixed;
  2811. width: 60px;
  2812. background: #ffffff;
  2813. box-shadow: 1px 1px 4px 0px #0000004d;
  2814. border: 0px solid rgba(0,0,0,0.04);
  2815. border-radius: 4px;
  2816. padding: 8px 0;
  2817. }
  2818. .config_bar_menu_item {
  2819. cursor: pointer;
  2820. padding: 2px 6px;
  2821. display: flex;
  2822. justify-content: center;
  2823. align-items: center;
  2824. height: 32px;
  2825. font-size: 14px;
  2826. font-weight: 500;
  2827. box-shadow: inset 0px 0px 0px 0px #8bb2d9;
  2828. }
  2829. #config_bar_menu_edit:hover {
  2830. background-color: #00aeec;
  2831. color: white;
  2832. }
  2833. #config_bar_menu_delete:hover {
  2834. background-color: #FF5722;
  2835. color: white;
  2836. }
  2837.  
  2838. /* 配置编辑页面 */
  2839. #config_edit_menu {
  2840. z-index: 300;
  2841. width: 450px;
  2842. }
  2843.  
  2844. /* 黑暗模式选项按钮 */
  2845. .dark-mode-selection {
  2846. display: flex;
  2847. justify-content: center;
  2848. align-items: center;
  2849. max-width: 350px;
  2850. -webkit-user-select: none;
  2851. -moz-user-select: none;
  2852. -ms-user-select: none;
  2853. user-select: none;
  2854. }
  2855. .dark-mode-selection label {
  2856. margin: 8px 0px 8px 8px;
  2857. }
  2858. .dark-mode-selection > * {
  2859. margin: 6px;
  2860. }
  2861. .dark-mode-selection .OJBetter_setting_menu_label_text {
  2862. border-radius: 8px;
  2863. margin-bottom: 0px;
  2864. }
  2865.  
  2866. /*确认弹窗*/
  2867. .OJBetter_modal {
  2868. z-index: 600;
  2869. display: grid;
  2870. position: fixed;
  2871. top: 50%;
  2872. left: 50%;
  2873. transform: translate(-50%, -50%);
  2874. font-size: 12px;
  2875. font-family: var(--vp-font-family-base);
  2876. width: max-content;
  2877. padding: 10px 20px;
  2878. box-shadow: 0px 0px 0px 4px #ffffff;
  2879. border-radius: 6px;
  2880. background-color: #f0f4f9;
  2881. border-collapse: collapse;
  2882. border: 1px solid #ffffff;
  2883. color: #697e91;
  2884. }
  2885. .OJBetter_modal h2 {
  2886. font-size: 1.6em;
  2887. font-weight: 700;
  2888. }
  2889. .OJBetter_modal .content{
  2890. white-space: nowrap;
  2891. max-height: 500px;
  2892. overflow-y: auto;
  2893. }
  2894. .OJBetter_modal .buttons{
  2895. display: flex;
  2896. padding-top: 15px;
  2897. }
  2898. .OJBetter_modal button {
  2899. display: inline-flex;
  2900. justify-content: center;
  2901. align-items: center;
  2902. line-height: 1;
  2903. white-space: nowrap;
  2904. cursor: pointer;
  2905. text-align: center;
  2906. box-sizing: border-box;
  2907. outline: none;
  2908. transition: .1s;
  2909. user-select: none;
  2910. vertical-align: middle;
  2911. -webkit-appearance: none;
  2912. height: 24px;
  2913. padding: 5px 11px;
  2914. margin-right: 15px;
  2915. font-size: 12px;
  2916. border-radius: 4px;
  2917. color: #ffffff;
  2918. background: #009688;
  2919. border-color: #009688;
  2920. border: none;
  2921. }
  2922. .OJBetter_modal button.secondary{
  2923. background-color:#4DB6AC;
  2924. }
  2925. .OJBetter_modal button:hover{
  2926. background-color:#4DB6AC;
  2927. }
  2928. .OJBetter_modal button.secondary:hover {
  2929. background-color: #80CBC4;
  2930. }
  2931. .OJBetter_modal .help-icon {
  2932. margin: 0px 8px 0px 0px;
  2933. height: 1em;
  2934. width: 1em;
  2935. line-height: 1em;
  2936. display: inline-flex;
  2937. justify-content: center;
  2938. align-items: center;
  2939. position: relative;
  2940. fill: currentColor;
  2941. font-size: inherit;
  2942. }
  2943. .OJBetter_modal p {
  2944. margin: 5px 0px;
  2945. }
  2946.  
  2947. /* 右键菜单 */
  2948. .OJBetter_contextmenu {
  2949. z-index: 500;
  2950. display: grid;
  2951. position: absolute;
  2952. background-color: #f0f4f9;
  2953. border-collapse: collapse;
  2954. color: #697e91;
  2955. font-family: var(--vp-font-family-base);
  2956. overflow: hidden;
  2957. box-sizing: content-box;
  2958. box-shadow: 0px 0px 0px 2px #eddbdb4d;
  2959. }
  2960. .OJBetter_contextmenu label {
  2961. margin: 0px;
  2962. }
  2963. input[type="radio"]:checked+.OJBetter_contextmenu_label_text {
  2964. background: #41e49930;
  2965. border: 1px solid green;
  2966. color: green;
  2967. font-weight: 500;
  2968. }
  2969. .OJBetter_contextmenu_label_text {
  2970. display: flex;
  2971. border: 1px dashed #80cbc4;
  2972. height: 26px;
  2973. width: 100%;
  2974. color: gray;
  2975. font-size: 13px;
  2976. font-weight: initial;
  2977. padding: 4px;
  2978. align-items: center;
  2979. -webkit-box-sizing: border-box;
  2980. -moz-box-sizing: border-box;
  2981. box-sizing: border-box;
  2982. }
  2983. .OJBetter_contextmenu_label_text:hover {
  2984. color: #F44336;
  2985. border: 1px dashed #009688;
  2986. background-color: #ffebcd;
  2987. }
  2988.  
  2989. /* RatingByClist */
  2990. .ratingBadge, html[data-theme=dark] button.ratingBadge{
  2991. display: block;
  2992. font-weight: 700;
  2993. font-size: 11px;
  2994. margin-top: 5px;
  2995. padding: 2px;
  2996. border-radius: 4px;
  2997. color: #B0BEC5;
  2998. border: 1px solid #cccccc66;
  2999. }
  3000.  
  3001. /* 多选翻译 */
  3002. .block_selected{
  3003. box-shadow: 0px 0px 0px 1px #FF9800;
  3004. outline: none;
  3005. }
  3006.  
  3007. /* 悬浮菜单 */
  3008. .OJBetter_MiniTranslateButton {
  3009. z-index: 100;
  3010. display: grid;
  3011. position: absolute;
  3012. border-collapse: collapse;
  3013. fill: #F57C00;
  3014. background-color: #FFF3E0;
  3015. overflow: hidden;
  3016. box-sizing: content-box;
  3017. box-shadow: 0px 0px 0px 2px #FFE0B2;
  3018. border-radius: 100%;
  3019. }
  3020. .OJBetter_MiniTranslateButton:hover {
  3021. cursor: pointer;
  3022. box-shadow: 0px 0px 0px 2px #FFB74D;
  3023. }
  3024.  
  3025. /* acmsguru划分块 */
  3026. .OJBetter_acmsguru {
  3027. margin: 0 0 1em!important;
  3028. }
  3029.  
  3030. /* 代码提交表单 */
  3031. #OJBetter_SubmitForm.input-output-copier:hover {
  3032. background-color: #ffffff00;
  3033. }
  3034. #OJBetter_SubmitForm input[type="number"] {
  3035. width: 40px;
  3036. color: #009688;
  3037. appearance: none;
  3038. border-radius: 6px;
  3039. border-style: solid;
  3040. border: none;
  3041. background-color: #ffffff00;
  3042. }
  3043. #OJBetter_SubmitForm :focus-visible {
  3044. outline: none;
  3045. }
  3046. #OJBetter_SubmitForm .topDiv {
  3047. height: 50px;
  3048. display: flex;
  3049. align-items: center;
  3050. justify-content: space-between;
  3051. padding: 10px 0px;
  3052. box-sizing: border-box;
  3053. }
  3054. #OJBetter_SubmitForm .topDiv .topRightDiv {
  3055. height: 100%;
  3056. display: flex;
  3057. flex-wrap: wrap;
  3058. gap: 0px;
  3059. }
  3060. #OJBetter_SubmitForm input[type="checkbox"], #OJBetter_SubmitForm label {
  3061. margin: 0px;
  3062. font-weight: initial;
  3063. }
  3064. #OJBetter_SubmitForm #fontSizeInput {
  3065. border: none;
  3066. background-color: #ffffff00;
  3067. }
  3068.  
  3069. /* 顶部区域 */
  3070. #OJBetter_SubmitForm .topRightDiv>* {
  3071. height: 100%;
  3072. box-sizing: border-box;
  3073. }
  3074. #OJBetter_SubmitForm .topRightDiv>button{
  3075. padding: 0px 8px;
  3076. }
  3077. #OJBetter_SubmitForm .topRightDiv {
  3078. display: flex;
  3079. flex-wrap: wrap;
  3080. gap: 0px;
  3081. align-items: center;
  3082. }
  3083.  
  3084. /* LSP连接Log */
  3085. #LSPLog{
  3086. width: 500px;
  3087. height: 500px;
  3088. position: fixed;
  3089. top: 50%;
  3090. left: 50%;
  3091. padding: 10px;
  3092. transform: translate(-50%, -50%);
  3093. border: 1px solid;
  3094. z-index: 200;
  3095. background-color: #ffffff;
  3096. }
  3097. #LSPLog button{
  3098. position: fixed;
  3099. top: 10px;
  3100. right: 10px;
  3101. z-index: 200;
  3102. }
  3103. #LSPLog #LSPLogList{
  3104. width: 500px;
  3105. height: 500px;
  3106. overflow: auto;
  3107. color: #424242;
  3108. }
  3109. #LSPLog li:nth-child(odd){
  3110. background-color: #f5f5f5;
  3111. }
  3112. #LSPLog details{
  3113. padding: 2px;
  3114. }
  3115.  
  3116. /* 代码编辑器 */
  3117. #OJBetter_editor{
  3118. box-sizing: border-box;
  3119. height: 600px;
  3120. border: 1px solid #d3d3d3;
  3121. width: 100%;
  3122. resize: vertical;
  3123. display: flex;
  3124. flex-direction: column;
  3125. }
  3126. #OJBetter_editor.fullscreen{
  3127. position: fixed;
  3128. top: 0;
  3129. left: 0;
  3130. width: 100%;
  3131. height: 100vh;
  3132. z-index: 2000;
  3133. }
  3134. #OJBetter_editor.bottom{
  3135. position: fixed;
  3136. bottom: 0;
  3137. left: 0;
  3138. width: 100%;
  3139. height: 50vh;
  3140. z-index: 2000;
  3141. }
  3142. .ojb_btn.exit_button_bottom {
  3143. position: fixed;
  3144. bottom: 30px;
  3145. right: 15px;
  3146. z-index: 2000;
  3147. height: 28px;
  3148. }
  3149.  
  3150. /* monaco */
  3151. #OJBetter_monaco {
  3152. flex: 1;
  3153. min-height: 0;
  3154. width: 100%;
  3155. }
  3156. #OJBetter_monaco .highlight {
  3157. border: 1px solid #ffffff00;
  3158. background-color: #ffffff00!important
  3159. }
  3160. .monaco-hover hr {
  3161. margin: 4px -8px 4px !important;
  3162. }
  3163.  
  3164. /* 状态底栏 */
  3165. #OJBetter_statusBar{
  3166. height: 22px;
  3167. font-size: 12px;
  3168. color: #757575;
  3169. border: 1px solid #d3d3d3;
  3170. background-color: #f8f8f8;
  3171. padding: 3px;
  3172. box-sizing: border-box;
  3173. }
  3174.  
  3175. /* 提交 */
  3176. #OJBetter_submitDiv{
  3177. display: flex;
  3178. padding-top: 15px;
  3179. height: 50px;
  3180. box-sizing: border-box;
  3181. }
  3182. #OJBetter_submitDiv >* {
  3183. border-radius: 6px;
  3184. }
  3185. #OJBetter_submitDiv > button {
  3186. height: 100%;
  3187. aspect-ratio: 1 / 1;
  3188. }
  3189. #SubmitButton {
  3190. color: #fff;
  3191. background-color: #209978;
  3192. border-color: #17795E;
  3193. }
  3194. #SubmitButton:hover {
  3195. background-color: #17795e;
  3196. }
  3197. #SubmitButton.disabled {
  3198. background-color: red;
  3199. animation: shake 0.07s infinite alternate;
  3200. }
  3201. #programTypeId{
  3202. height: 100%;
  3203. padding: 5px 10px;
  3204. border-radius: 6px;
  3205. border-style: solid;
  3206. border: 1px solid #ced4da;
  3207. color: #212529;
  3208. }
  3209.  
  3210. /* 调试 */
  3211. .OJBetter_loding{
  3212. padding: 6px 0px 0px 5px;
  3213. height: 22px;
  3214. }
  3215. #CompilerArgsInput{
  3216. flex-grow: 1;
  3217. width: 100%;
  3218. height: 100%;
  3219. margin-bottom: 10px;
  3220. padding: 5px 10px;
  3221. border-radius: 6px;
  3222. box-sizing: border-box;
  3223. border: 1px solid #ccc;
  3224. box-shadow: inset 0px 1px 1px rgba(0,0,0,.075);
  3225. }
  3226. #CompilerArgsInput[disabled] {
  3227. cursor: not-allowed;
  3228. }
  3229. #CompilerSetting{
  3230. font-size: 14px;
  3231. margin-top: 10px;
  3232. display: none;
  3233. }
  3234. #CompilerSetting select, #CompilerSetting textarea{
  3235. padding: 4px 10px;
  3236. border-radius: 6px;
  3237. border-style: solid;
  3238. border: 1px solid #ced4da;
  3239. color: #212529;
  3240. }
  3241. #CompilerBox{
  3242. display: grid;
  3243. margin-top: 10px;
  3244. border: #d0d7de solid 1px;
  3245. border-radius: 6px;
  3246. }
  3247. #CompilerBox > * {
  3248. margin: 5px;
  3249. }
  3250.  
  3251. /* 自定义样例 */
  3252. #customTestBlock {
  3253. margin-top: 10px;
  3254. font-size: 14px;
  3255. color: #616161;
  3256. border: 1px solid #d3d3d3;
  3257. box-sizing: border-box;
  3258. position: relative;
  3259. }
  3260. #customTestBlock #customTests{
  3261. border-top: 1px solid #d3d3d3;
  3262. margin: 0px 0px 40px 0px;
  3263. }
  3264. #customTestBlock summary {
  3265. cursor: pointer;
  3266. padding: 10px;
  3267. }
  3268. #customTestBlock textarea {
  3269. resize: vertical;
  3270. }
  3271. .sampleDiv {
  3272. color: #727378;
  3273. background-color: #FAFAFA;
  3274. padding: 5px;
  3275. margin-bottom: 10px;
  3276. box-shadow: inset 0 0 1px #0000004d;
  3277. position: relative;
  3278. }
  3279. .dynamicTextarea {
  3280. width: 98%;
  3281. height: 120px;
  3282. margin: 10px 5px;
  3283. border: 1px solid #E0E0E0;
  3284. }
  3285. .deleteCustomTest {
  3286. cursor: pointer;
  3287. position: absolute;
  3288. top: 5px;
  3289. right: 5px;
  3290. display: flex;
  3291. fill: #9E9E9E;
  3292. padding: 2px 2px;
  3293. border-radius: 4px;
  3294. border: 1px solid #ffffff00;
  3295. background-color: #ffffff00;
  3296. align-items: center;
  3297. }
  3298. .deleteCustomTest:hover {
  3299. fill: #EF5350;
  3300. border: 1px solid #ef9a9a;
  3301. background-color: #FFEBEE;
  3302. }
  3303. #addCustomTest {
  3304. cursor: pointer;
  3305. position: absolute;
  3306. bottom: 5px;
  3307. right: 5px;
  3308. padding: 3px 10px;
  3309. color: #795548;
  3310. border: 1px solid #ccc;
  3311. border-radius: 4px;
  3312. background-color: #FAFAFA;
  3313. }
  3314. #addCustomTest:hover {
  3315. background-color: #f5f5f5;
  3316. }
  3317.  
  3318. /* 调试结果 */
  3319. #statePanel{
  3320. display: none;
  3321. padding: 5px;
  3322. margin-top: 10px;
  3323. border: 1px solid #ddd;
  3324. border-radius: 4px;
  3325. }
  3326. .test-case {
  3327. padding: 10px;
  3328. border: 1px solid #ddd;
  3329. border-radius: 4px;
  3330. }
  3331. .test-case:not(:first-child){
  3332. margin-top: 5px;
  3333. }
  3334. .test-case > * {
  3335. margin: 5px 0px;
  3336. }
  3337. .test-case > :first-child {
  3338. margin-top: 0px;
  3339. }
  3340. .test-case > :last-child {
  3341. margin-bottom: 0px;
  3342. }
  3343. .test-case-title, .test-case-status {
  3344. font-size: 16px;
  3345. display: inline;
  3346. }
  3347. .test-case-status{
  3348. margin-left: 5px;
  3349. }
  3350. .test-case-status.error{
  3351. color: red;
  3352. }
  3353. .test-case-status.success{
  3354. color: #449d44;
  3355. }
  3356. .test-case-judge {
  3357. font-size: 13px;
  3358. }
  3359.  
  3360. /* 差异对比 */
  3361. .output_diff {
  3362. color: #5d4037;
  3363. margin: 5px 0px;
  3364. display: grid;
  3365. border: 1px solid #bcaaa4;
  3366. font-size: 13px;
  3367. font-family: Consolas, "Lucida Console", "Andale Mono", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace;
  3368. overflow: auto;
  3369. }
  3370. .output_diff .added {
  3371. background-color: #c8f7c5;
  3372. user-select: none;
  3373. }
  3374. .output_diff .removed {
  3375. background-color: #f7c5c5;
  3376. }
  3377. .output_diff .diffLine {
  3378. display: flex;
  3379. }
  3380. .output_diff .diffLine:nth-child(odd) {
  3381. background-color: #f5f5f5;
  3382. }
  3383. .lineNo {
  3384. display: flex;
  3385. align-items: center;
  3386. justify-content: center;
  3387. width: 17px;
  3388. color: #BDBDBD;
  3389. font-size: 10px;
  3390. border-right: 1px solid;
  3391. user-select: none;
  3392. }
  3393. .lineContent {
  3394. display: grid;
  3395. width: 100%;
  3396. }
  3397. .lineContent>span {
  3398. height: 16px;
  3399. padding-left: 3px;
  3400. }
  3401. .output_no_diff {
  3402. padding: 5px;
  3403. border: 1px solid #ddd;
  3404. }
  3405. .diff_note {
  3406. font-size: 10px;
  3407. }
  3408.  
  3409. /* 移动设备 */
  3410. @media (max-device-width: 450px) {
  3411. .ojb_btn{
  3412. height: 2em;
  3413. font-size: 1.2em;
  3414. }
  3415. .ojb_btn.OJBetter_setting{
  3416. height: 2.5em;
  3417. font-size: 1em;
  3418. }
  3419. .OJBetter_setting_menu{
  3420. width: 90%;
  3421. }
  3422. .OJBetter_setting_menu label, #darkMode_span, #loaded_span, .OJBetter_setting_menu_label_text,
  3423. .OJBetter_setting_sidebar li{
  3424. font-size: 1em;
  3425. }
  3426. .translate-problem-statement{
  3427. font-size: 1.2em;
  3428. }
  3429. .OJBetter_modal{
  3430. font-size: 1.5em;
  3431. }
  3432. .OJBetter_setting_list, .translate-problem-statement{
  3433. padding: 0.5em;
  3434. }
  3435. .OJBetter_setting_menu_label_text{
  3436. height: 2.5em;
  3437. padding: 0.5em;
  3438. }
  3439. #pagBar #jump-input, #pagBar #items-per-page, .OJBetter_modal button{
  3440. height: 2.5em;
  3441. font-size: 1em;
  3442. }
  3443. .translate-problem-statement p, .translate-problem-statement ul li{
  3444. line-height: 1.5em !important;
  3445. }
  3446. .OJBetter_contextmenu_label_text{
  3447. height: 3em;
  3448. font-size: 1em;
  3449. }
  3450. }
  3451.  
  3452. /* 覆盖网站原本的样式 */
  3453. div#select-lang {
  3454. padding: 0px;
  3455. }
  3456. `);
  3457.  
  3458. /**
  3459. * 添加一些依赖库和条件加载的css样式
  3460. */
  3461. function addDependencyStyles() {
  3462. GM_addStyle(GM_getResourceText("xtermcss"));
  3463. // 自定义图标大小
  3464. GM_addStyle(`
  3465. .iconfont {
  3466. font-size: ${OJBetter.preference.iconButtonSize}px;
  3467. }
  3468. `);
  3469. }
  3470.  
  3471. /**
  3472. * 添加包含i18n内容的css样式
  3473. */
  3474. function addI18nStyles() {
  3475. GM_addStyle(`
  3476. /* 加载鼠标悬浮覆盖层css */
  3477. .overlay::before {
  3478. content: '';
  3479. position: absolute;
  3480. top: 0;
  3481. left: 0;
  3482. width: 100%;
  3483. height: 100%;
  3484. 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);
  3485. z-index: 100;
  3486. }
  3487. .overlay::after {
  3488. content: '${i18next.t('targetArea', { ns: 'common' })}';
  3489. position: absolute;
  3490. top: 50%;
  3491. left: 50%;
  3492. transform: translate(-50%, -50%);
  3493. color: #00695C;
  3494. font-size: 16px;
  3495. font-weight: bold;
  3496. z-index: 100;
  3497. }
  3498.  
  3499. .config::before {
  3500. content: "${i18next.t('common.configManageTitle', { ns: 'settings' })}";
  3501. display: block;
  3502. height: 20px;
  3503. background-color: #f0f8ff;
  3504. border: 1px solid #c5cae9;
  3505. border-bottom: 0px;
  3506. line-height: 20px;
  3507. padding: 2px 10px;
  3508. border-radius: 8px 8px 0px 0px;
  3509. box-sizing: content-box;
  3510. }
  3511. .config.missing::before {
  3512. content: "${i18next.t('common.missing.radio', { ns: 'settings' })}";
  3513. background-color: #fef0f0;
  3514. color: #f56c6c;
  3515. border: 1px solid #fab6b6;
  3516. }
  3517. `);
  3518. }
  3519.  
  3520. // ------------------------------
  3521. // 一些工具类
  3522. // ------------------------------
  3523.  
  3524.  
  3525. /**
  3526. * 自定义错误类,以区分不同的错误类型
  3527. */
  3528. class OJB_GMError extends Error {
  3529. constructor(type, message, originalError) {
  3530. super(message);
  3531. this.name = 'GMError';
  3532. this.type = type;
  3533. this.stack = originalError.stack;
  3534. Object.assign(this, originalError);
  3535. }
  3536. }
  3537.  
  3538. /**
  3539. * 文本块替换/恢复类
  3540. */
  3541. class TextBlockReplacer {
  3542. constructor() {
  3543. /** @type {string[]} 匹配项 */
  3544. this.matches = [];
  3545. /** @type {Map<string, string>} 待还原项 */
  3546. this.replacements = new Map();
  3547. /** @type {Map<string, string>} 暂时未找到的待还原项 */
  3548. this.tempReplacements = new Map();
  3549. /** @type {string} 替换符号 */
  3550. this.replaceSymbol = OJBetter.translation.replaceSymbol;
  3551. }
  3552.  
  3553. /**
  3554. * 替换文本
  3555. * @param {string} text 原文本
  3556. * @param {RegExp} regex 匹配规则
  3557. * @returns {string} 替换后的文本
  3558. */
  3559. replace(text, regex) {
  3560. this.matches = text.match(regex) || [];
  3561. try {
  3562. for (let i = 0; i < this.matches.length; i++) {
  3563. const match = this.matches[i];
  3564. const id = OJB_getRandomNumber(8);
  3565. let replacement = '';
  3566. switch (this.replaceSymbol) {
  3567. case "1":
  3568. replacement = `【${id}】`;
  3569. break;
  3570. case "2":
  3571. replacement = `{${id}}`;
  3572. break;
  3573. case "3":
  3574. replacement = `[${id}]`;
  3575. break;
  3576. default:
  3577. replacement = `【${id}】`;
  3578. break;
  3579. }
  3580. text = text.replace(match, replacement);
  3581. this.replacements.set(id, match);
  3582. }
  3583. } catch (e) { }
  3584. return text;
  3585. }
  3586.  
  3587.  
  3588. /**
  3589. * 恢复替换的文本
  3590. * @param {string} text 还原前的文本
  3591. * @returns {string} 还原后的文本
  3592. */
  3593. recover(text) {
  3594. let textCopy = text;
  3595.  
  3596. /**
  3597. * 替换文本
  3598. * @param {string} replacement 替换的文本
  3599. * @param {string} regexPattern 匹配规则
  3600. * @returns {void}
  3601. */
  3602. const replaceText = (replacement, regexPattern) => {
  3603. const latexMatch = '(?<latex_block>\\$\\$(\\\\.|[^\\$])*?\\$\\$)|(?<latex_inline>\\$(\\\\.|[^\\$])*?\\$)|';
  3604. const regex = new RegExp(latexMatch + regexPattern, 'g');
  3605. textCopy = textCopy.replace(regex, (match, ...args) => {
  3606. // LaTeX中的不替换
  3607. const groups = args[args.length - 1]; // groups是replace方法的最后一个参数
  3608. if (groups.latex_block || groups.latex_inline) return match;
  3609. // 没有空格则加一个
  3610. const offset = args[args.length - 3]; // offset是replace方法的倒数第三个参数
  3611. let leftSpace = "", rightSpace = "";
  3612. if (!/\s/.test(textCopy[offset - 1])) leftSpace = " ";
  3613. if (!/\s/.test(textCopy[offset + match.length])) rightSpace = " ";
  3614. return leftSpace + replacement + rightSpace;
  3615. });
  3616. };
  3617.  
  3618. /**
  3619. * 尝试还原
  3620. * @param {string} replacement 替换的文本
  3621. * @param {string} id 替换的 id
  3622. * @returns {boolean} 是否替换成功
  3623. */
  3624. const tryRecover = (replacement, id) => {
  3625. // 尝试还原,如果还原成功,则从 replacements 中删除
  3626. const originalText = textCopy;
  3627. replaceText(replacement, `【\\s*${id}\\s*】|\\[\\s*${id}\\s*\\]|{\\s*${id}\\s*}`); // 替换符完整匹配(考虑了多出空格的情况)
  3628. replaceText(replacement, `【\\s*${id}(?![】\\d])|(?<![【\\d])${id}\\s*】|\\[\\s*${id}(?![\\]\\d])|(?<![\\[\\d])${id}\\s*\\]|{\\s*${id}(?![}\\d])|(?<![{\\d])${id}\\s*}`); // 替换符部分匹配
  3629.  
  3630. if (textCopy === originalText) {
  3631. // 如果文本没有变化,说明没有找到,加入到 tempReplacements
  3632. this.tempReplacements.set(id, replacement);
  3633. return false;
  3634. } else {
  3635. // 如果文本变化了,说明找到并成功替换,则删除
  3636. this.replacements.delete(id);
  3637. this.tempReplacements.delete(id);
  3638. return true;
  3639. }
  3640. }
  3641.  
  3642. // 处理 replacements 中的项
  3643. this.replacements.forEach((replacement, id) => {
  3644. tryRecover(replacement, id);
  3645. });
  3646.  
  3647. // 处理 tempReplacements 中的项
  3648. while (this.tempReplacements.size > 0) {
  3649. let found = false;
  3650. this.tempReplacements.forEach((replacement, id) => {
  3651. found = tryRecover(replacement, id) || found;
  3652. });
  3653. if (!found) break; // 如果这一轮没有找到任何项,终止循环
  3654. }
  3655.  
  3656. // 如果 tempReplacements 还有未找到的项
  3657. if (this.tempReplacements.size > 0) {
  3658. console.warn("There are still some replacements not found:", this.tempReplacements);
  3659. }
  3660.  
  3661. return textCopy;
  3662. }
  3663. }
  3664.  
  3665. // ------------------------------
  3666. // 一些工具函数
  3667. // ------------------------------
  3668.  
  3669. /**
  3670. * 延迟函数
  3671. * @param {number} ms 延迟时间(毫秒)
  3672. * @returns {Promise<void>}
  3673. */
  3674. function OJB_delay(ms) {
  3675. return new Promise(resolve => setTimeout(resolve, ms));
  3676. }
  3677.  
  3678. /**
  3679. * 格式化链接格式
  3680. * @param {string} url 链接字符串
  3681. * @returns {string} 清理后的链接字符串
  3682. */
  3683. function OJB_cleanLink(url) {
  3684. // 替换'http://'为'https://'
  3685. let cleanUrl = url.replace(/^http:\/\//i, 'https://');
  3686.  
  3687. // 移除末尾的斜杠
  3688. cleanUrl = cleanUrl.replace(/\/$/, '');
  3689.  
  3690. return cleanUrl;
  3691. }
  3692.  
  3693. /**
  3694. * 深度比较两个对象或数组是否完全相等。
  3695. * @param {any} a - 第一个比较对象。
  3696. * @param {any} b - 第二个比较对象。
  3697. * @returns {boolean} - 如果两个对象或数组深度相等,则返回true,否则返回false。
  3698. */
  3699. function OJB_deepEquals(a, b) {
  3700. if (a === b) return true;
  3701. if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) return false;
  3702. const keysA = Object.keys(a);
  3703. const keysB = Object.keys(b);
  3704. if (keysA.length !== keysB.length) return false;
  3705. for (let key of keysA) {
  3706. if (!b.hasOwnProperty(key)) return false;
  3707. if (!OJB_deepEquals(a[key], b[key])) return false;
  3708. }
  3709. return true;
  3710. }
  3711.  
  3712. /**
  3713. * 用于封装需要重试的异步函数
  3714. * @param {Function} task 需要封装的异步函数
  3715. * @param {Object} options 配置项
  3716. * @param {Number} options.maxRetries 重试次数,默认为 5
  3717. * @param {Number} options.retryInterval 重试时间间隔,默认为 0 毫秒
  3718. * @param {Function} options.errorHandler 错误处理函数,默认为抛出错误
  3719. * @param {...any} args task 函数的参数
  3720. * @returns {Promise} 返回 Promise
  3721. */
  3722. async function OJB_promiseRetryWrapper(task, {
  3723. maxRetries = 5,
  3724. retryInterval = 0,
  3725. errorHandler = (err) => { throw err }
  3726. } = {}, ...args) {
  3727. let attemptsLeft = maxRetries;
  3728. while (attemptsLeft--) {
  3729. try {
  3730. return await task(...args);
  3731. } catch (err) {
  3732. if (attemptsLeft <= 0) {
  3733. return errorHandler(err, maxRetries, attemptsLeft);
  3734. }
  3735. if (retryInterval > 0) {
  3736. await OJB_delay(retryInterval);
  3737. }
  3738. }
  3739. }
  3740. }
  3741.  
  3742. /**
  3743. * GM_xmlhttpRequest 的 Promise 封装
  3744. * @param {Object} options GM_xmlhttpRequest 的参数
  3745. * @param {Boolean} isStream 是否为流式请求
  3746. * @returns {Promise<OJB_GMError>} 返回 Promise
  3747. */
  3748. function OJB_GMRequest(options, isStream = false) {
  3749. return new Promise((resolve, reject) => {
  3750. GM_xmlhttpRequest({
  3751. ...options,
  3752. ...(isStream ? {
  3753. onloadstart: resolve
  3754. } : {
  3755. onload: resolve
  3756. }),
  3757. onerror: (error) => reject(new OJB_GMError('error', 'An error occurred during the request.', error)),
  3758. ontimeout: (error) => reject(new OJB_GMError('timeout', 'The request timed out.', error)),
  3759. onabort: (error) => reject(new OJB_GMError('abort', 'The request was aborted.', error)),
  3760. });
  3761. });
  3762. }
  3763.  
  3764. /**
  3765. * 获取cookie
  3766. * @param {string} name cookie名称
  3767. * @returns {string} cookie值
  3768. */
  3769. function OJB_getCookie(name) {
  3770. const cookies = document.cookie.split(";");
  3771. for (let i = 0; i < cookies.length; i++) {
  3772. const cookie = cookies[i].trim();
  3773. const [cookieName, cookieValue] = cookie.split("=");
  3774.  
  3775. if (cookieName === name) {
  3776. return decodeURIComponent(cookieValue);
  3777. }
  3778. }
  3779. return "";
  3780. }
  3781.  
  3782. /**
  3783. * 检查是否仍在同一浏览器会话中
  3784. * @param {string} sessionKey - 会话键名,用于标识会话
  3785. * @returns {boolean} - 如果在当前会话中之前已经设置过这个键,则返回true,否则返回false
  3786. */
  3787. function OJB_isSameBrowserSession(sessionKey) {
  3788. const fullCookieName = `OJB_Session_${sessionKey}`;
  3789. const sessionValue = OJB_getCookie(fullCookieName);
  3790. if (sessionValue === "") {
  3791. document.cookie = `${fullCookieName}=true; path=/`;
  3792. return false;
  3793. }
  3794. return true;
  3795. }
  3796.  
  3797. /**
  3798. * 随机数生成
  3799. * @param {number} numDigits 位数
  3800. * @returns {number}
  3801. */
  3802. function OJB_getRandomNumber(numDigits) {
  3803. let min = Math.pow(10, numDigits - 1);
  3804. let max = Math.pow(10, numDigits) - 1;
  3805. return Math.floor(Math.random() * (max - min + 1)) + min;
  3806. }
  3807.  
  3808. /**
  3809. * 防抖函数
  3810. * @param {Function} callback 回调函数
  3811. * @returns {Function}
  3812. */
  3813. function OJB_debounce(callback) {
  3814. let timer;
  3815. let immediateExecuted = false;
  3816. const delay = 500;
  3817. return function () {
  3818. clearTimeout(timer);
  3819. if (!immediateExecuted) { callback.call(this); immediateExecuted = true; }
  3820. timer = setTimeout(() => { immediateExecuted = false; }, delay);
  3821. };
  3822. }
  3823.  
  3824. /**
  3825. * 为元素添加鼠标拖拽支持
  3826. * @param {JQuery<HTMLElement>} element 要添加拖拽支持的元素
  3827. * @returns {void}
  3828. */
  3829. function OJB_addDraggable(element) {
  3830. let isDragging = false;
  3831. let x, y, l, t, nl, nt;
  3832. let isSpecialMouseDown = false; // 选取某些元素时不拖动
  3833.  
  3834. element.on('mousedown', function (e) {
  3835. isSpecialMouseDown = $(e.target).is('label, p, input, textarea, span, select, details, summary');
  3836. if (isSpecialMouseDown) return;
  3837.  
  3838. isDragging = true;
  3839. x = e.clientX;
  3840. y = e.clientY;
  3841. l = element.offset().left - $(window).scrollLeft();
  3842. t = element.offset().top - $(window).scrollTop();
  3843.  
  3844. element.css({ left: l + 'px', top: t + 'px', transform: 'none' });
  3845.  
  3846. $(document).on("mousemove", drag);
  3847. $(document).on("mouseup", stopDrag);
  3848. element.css('cursor', 'all-scroll');
  3849. });
  3850.  
  3851. const drag = (e) => {
  3852. if (!isDragging) return;
  3853. // 不执行拖动操作
  3854. if ($(e.target).is('label, p, input, textarea, span') || isSpecialMouseDown && !$(e.target).is('input, textarea')) return;
  3855. e.preventDefault();
  3856.  
  3857. const nx = e.clientX;
  3858. const ny = e.clientY;
  3859. nl = nx - (x - l);
  3860. nt = ny - (y - t);
  3861. element.css({ transform: `translate(${nx - x}px, ${ny - y}px)` });
  3862. };
  3863.  
  3864. const stopDrag = () => {
  3865. isDragging = false;
  3866. isSpecialMouseDown = false;
  3867. element.css('cursor', 'default');
  3868.  
  3869. // 在停止拖拽后,设置元素的left和top,并还原transform
  3870. element.css({ left: nl + 'px', top: nt + 'px', transform: 'none' });
  3871. $(document).off("mousemove", drag);
  3872. $(document).off("mouseup", stopDrag);
  3873. };
  3874. }
  3875.  
  3876. /**
  3877. * 切换元素的折叠/展开过渡动画
  3878. * @param {HTMLElement} element
  3879. */
  3880. function OJB_toggleCollapseExpand(element) {
  3881. // 设置transitionend事件监听器的函数
  3882. const setTransitionListener = (listener) => {
  3883. const listenerName = `transitionEndListener${Date.now()}`;
  3884. window[listenerName] = listener;
  3885. element.addEventListener('transitionend', listener);
  3886. element.setAttribute('data-transition-end-listener', listenerName);
  3887. };
  3888.  
  3889. // 移除事件监听器的函数
  3890. const removeTransitionListener = () => {
  3891. const transitionEndListenerName = element.getAttribute('data-transition-end-listener');
  3892. if (transitionEndListenerName) {
  3893. element.removeEventListener('transitionend', window[transitionEndListenerName]);
  3894. element.removeAttribute('data-transition-end-listener');
  3895. }
  3896. };
  3897.  
  3898. const collapsed = element.getAttribute('data-collapsed') === 'true';
  3899. const sectionHeight = element.scrollHeight;
  3900.  
  3901. // 移除事件监听器
  3902. removeTransitionListener();
  3903.  
  3904. // 设置初始样式
  3905. element.style.overflow = 'hidden';
  3906. element.style.transition = 'height 0.3s ease-out 0s';
  3907. element.style.height = collapsed ? `0px` : `${sectionHeight}px`;
  3908. element.style.opacity = collapsed ? '' : '1';
  3909.  
  3910. // 需要立即开始动画
  3911. requestAnimationFrame(() => {
  3912. // 设置结束样式
  3913. element.style.height = collapsed ? `${sectionHeight}px` : `0px`;
  3914. });
  3915.  
  3916. const transitionEndListener = (event) => {
  3917. if (event.propertyName === 'height') {
  3918. if (collapsed) {
  3919. // 展开后的设置
  3920. element.style.height = '';
  3921. element.style.overflow = '';
  3922. } else {
  3923. // 折叠后的设置
  3924. element.style.opacity = '0';
  3925. }
  3926. removeTransitionListener();
  3927. }
  3928. };
  3929.  
  3930. setTransitionListener(transitionEndListener);
  3931.  
  3932. // 更新data-collapsed属性
  3933. element.setAttribute('data-collapsed', collapsed ? 'false' : 'true');
  3934. }
  3935.  
  3936. /**
  3937. * 获取外部JSON并转换为Object
  3938. * @param {string} url JSON Url
  3939. * @param {boolean} [nacache=true] 是否不使用缓存
  3940. * @returns {Promise<Object>} JSON Object
  3941. */
  3942. async function OJB_getExternalJSON(url, nacache = true) {
  3943. const response = await OJB_GMRequest({
  3944. method: "GET",
  3945. url: url,
  3946. nocache: nacache
  3947. });
  3948. try {
  3949. return JSON.parse(response.responseText);
  3950. } catch (e) {
  3951. throw new Error(`JSON parse error\n${e}`);
  3952. }
  3953. }
  3954.  
  3955. /**
  3956. * 创建确认对话框dialog
  3957. * @param {string} title 标题
  3958. * @param {string} content 内容
  3959. * @param {string[]} buttons 按钮 (取消 确定) 可以为null
  3960. * @param {boolean} renderMarkdown 是否使用markdown渲染文本
  3961. * @returns {Promise<boolean>} 用户点击了确定按钮返回true, 否则返回false
  3962. */
  3963. function OJB_createDialog(title, content, buttons, renderMarkdown = false) {
  3964. return new Promise(resolve => {
  3965. let contentHtml = content;
  3966.  
  3967. if (renderMarkdown) {
  3968. const md = window.markdownit();
  3969. contentHtml = md.render(content);
  3970. }
  3971.  
  3972. const dialog = OJB_safeCreateJQElement(`
  3973. <dialog class="OJBetter_modal">
  3974. <h2>${title}</h2>
  3975. <div class="content">${contentHtml}</div>
  3976. </dialog>
  3977. `);
  3978. const buttonbox = OJB_safeCreateJQElement(`<div class="buttons"></div>`);
  3979. const cancelButton = OJB_safeCreateJQElement(`<button class="cancelButton">${buttons[0]}</button>`)
  3980. .addClass("secondary");
  3981. const continueButton = OJB_safeCreateJQElement(`<button class="continueButton">${buttons[1]}</button>`);
  3982. if (buttons[0] !== null) buttonbox.append(cancelButton);
  3983. if (buttons[1] !== null) buttonbox.append(continueButton);
  3984. dialog.append(buttonbox);
  3985. $('body').append(dialog);
  3986.  
  3987. OJB_showModal(dialog);
  3988. OJB_addDraggable(dialog);
  3989.  
  3990. continueButton.click(function () {
  3991. OJB_closeAndRemoveModal(dialog);
  3992. resolve(true);
  3993. });
  3994.  
  3995. cancelButton.click(function () {
  3996. OJB_closeAndRemoveModal(dialog);
  3997. resolve(false);
  3998. });
  3999. });
  4000. }
  4001.  
  4002. /**
  4003. * 显示模态对话框并阻止页面滚动,同时考虑滚动条宽度变化和原始marginRight
  4004. * @param {JQuery<HTMLElement>} element
  4005. */
  4006. function OJB_showModal(element) {
  4007. const dialog = element.get(0);
  4008. dialog.showModal();
  4009. OJBetter.state.openDialogCount++;
  4010.  
  4011. if (OJBetter.state.openDialogCount === 1) {
  4012. const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
  4013. // 获取原始的html marginRight,考虑到可能的非数字值,比如auto
  4014. const originalMarginRight = window.getComputedStyle(document.documentElement).marginRight;
  4015. const marginRightValue = parseFloat(originalMarginRight) || 0; // 将非数字值转换为0
  4016.  
  4017. if (scrollbarWidth > 0) {
  4018. // 保存原始的marginRight,并设置新的值以补偿滚动条宽度
  4019. document.documentElement.style.setProperty('--original-margin-right', originalMarginRight);
  4020. document.documentElement.style.marginRight = `${marginRightValue + scrollbarWidth}px`;
  4021. }
  4022.  
  4023. // 保存原始的overflow样式
  4024. document.documentElement.setAttribute('data-original-overflow', document.documentElement.style.overflow);
  4025. document.documentElement.style.overflow = 'hidden';
  4026. }
  4027.  
  4028. const allowScrollIfNeeded = () => {
  4029. OJBetter.state.openDialogCount--;
  4030. if (OJBetter.state.openDialogCount === 0) {
  4031. // 恢复原始的html marginRight和overflow样式
  4032. const originalMarginRight = document.documentElement.style.getPropertyValue('--original-margin-right');
  4033. document.documentElement.style.marginRight = originalMarginRight;
  4034. document.documentElement.style.removeProperty('--original-margin-right');
  4035.  
  4036. const originalOverflow = document.documentElement.getAttribute('data-original-overflow');
  4037. document.documentElement.style.overflow = originalOverflow;
  4038. document.documentElement.removeAttribute('data-original-overflow');
  4039. }
  4040. };
  4041.  
  4042. dialog.addEventListener('close', allowScrollIfNeeded);
  4043. }
  4044.  
  4045. /**
  4046. * 关闭并移除模态对话框
  4047. * @param {JQuery<HTMLElement>} element
  4048. */
  4049. function OJB_closeAndRemoveModal(element) {
  4050. const dialog = element.get(0);
  4051. dialog.close();
  4052. dialog.remove();
  4053. }
  4054.  
  4055. /**
  4056. * 关闭并移除模态对话框
  4057. * @param {JQuery<HTMLElement>} element
  4058. */
  4059. function OJB_closeModal(element) {
  4060. const dialog = element.get(0);
  4061. dialog.close();
  4062. }
  4063.  
  4064. /**
  4065. * 清除i18next的缓存数据并刷新
  4066. */
  4067. function clearI18nextCache() {
  4068. Object.keys(localStorage)
  4069. .filter(key => key.startsWith('i18next_res_'))
  4070. .forEach(key => localStorage.removeItem(key));
  4071. window.location.reload();
  4072. }
  4073.  
  4074. /**
  4075. * 从Pre代码块中获取原始代码
  4076. * @param {HTMLElement} element pre代码块元素
  4077. * @returns {string|null} 代码文本
  4078. */
  4079. function OJB_getCodeFromPre(element) {
  4080. /**
  4081. * 从Ace格式化的代码块中获取原始代码
  4082. * @param {HTMLElement} element pre代码块元素
  4083. * @returns {string} 代码文本
  4084. */
  4085. const getCodeFromAcePre = function (element) {
  4086. const editor = ace.edit(element);
  4087. return editor.getValue();
  4088. }
  4089.  
  4090. /**
  4091. * 从Pretty格式化的代码块中获取原始代码-1
  4092. * 代码直接存放在 pre 元素中
  4093. * @param {HTMLElement} element pre代码块元素
  4094. * @returns {string} 代码文本
  4095. */
  4096. const getCodeFromPrettyPre = function (element) {
  4097. return Array.from(element.querySelectorAll('li')).map(function (li) {
  4098. return li.textContent;
  4099. }).join('\n');
  4100. }
  4101.  
  4102. /**
  4103. * 从Pretty格式化的代码块中获取原始代码-2
  4104. * 代码存放在子元素 code 中
  4105. * @param {HTMLElement} element pre代码块元素
  4106. * @returns {string} 代码文本
  4107. */
  4108. const getCodeFromPreChild = function (element) {
  4109. const code = element.querySelector("code.prettyprint");
  4110. if (code.classList.contains("linenums")) {
  4111. return getCodeFromPrettyPre(element);
  4112. } else {
  4113. return element.querySelector("code.prettyprint").textContent;
  4114. }
  4115. }
  4116.  
  4117. if (element.id === "submission-code") {
  4118. return getCodeFromAcePre(element);
  4119. } else if (element.classList.contains("prettyprint")) {
  4120. return getCodeFromPrettyPre(element);
  4121. } else if (element.querySelector("code.prettyprint")) {
  4122. return getCodeFromPreChild(element);
  4123. } else {
  4124. return null;
  4125. }
  4126. }
  4127.  
  4128. /**
  4129. * 判断代码的语言
  4130. * @param {string} code 代码文本
  4131. * @returns {string} 可能的语言
  4132. */
  4133. function OJB_codeLangDetect(code) {
  4134. result = hljs.highlightAuto(code);
  4135. return result.language;
  4136. }
  4137.  
  4138. /**
  4139. * 更新检查
  4140. */
  4141. async function checkScriptVersion() {
  4142. try {
  4143. const versionResponse = await OJB_GMRequest({
  4144. method: "GET",
  4145. url: "https://aowuucdn.oss-accelerate.aliyuncs.com/script/versions.json",
  4146. timeout: 10 * 1e3,
  4147. nocache: true
  4148. });
  4149. const versionData = JSON.parse(versionResponse.responseText);
  4150. const { [OJBetter.state.formatName]: { dev: version_dev, release: version_release } } = versionData;
  4151. const baseUrls = {
  4152. greasyfork: 'https://update.greatest.deepsurf.us/scripts/465777/Codeforces%20Better%21.user.js',
  4153. github: `https://github.com/beijixiaohu/OJBetter/raw/main/script/${OJBetter.about.updateChannel}/${OJBetter.state.formatName}.user.js`,
  4154. aliyunoss: `https://aowuucdn.oss-accelerate.aliyuncs.com/script/${OJBetter.about.updateChannel}/${OJBetter.state.formatName}.user.js`
  4155. };
  4156. /** @type {string} 更新跳转url */
  4157. const updateUrl = baseUrls[OJBetter.about.updateSource];
  4158. /** @type {string} 是否暂时跳过cookie */
  4159. const skipUpdate = OJB_getCookie("skipUpdate");
  4160. /** @type {string} 当前更新频道的最新版本 */
  4161. const version = OJBetter.about.updateChannel == "release" ? version_release : version_dev;
  4162. if (OJB_compareVersions(version, OJBetter.state.version) === 1 && skipUpdate !== "true") {
  4163. const updateConfirmed = await OJB_createDialog(
  4164. i18next.t('update.title', { ns: 'dialog', scriptName: OJBetter.state.name }),
  4165. i18next.t('update.content', { ns: 'dialog', oldVersion: OJBetter.state.version, newVersion: version }),
  4166. [
  4167. i18next.t('update.buttons.0', { ns: 'dialog' }),
  4168. i18next.t('update.buttons.1', { ns: 'dialog' })
  4169. ],
  4170. true
  4171. );
  4172.  
  4173. if (updateConfirmed) {
  4174. window.location.href = updateUrl;
  4175. } else {
  4176. document.cookie = "skipUpdate=true; path=/";
  4177. }
  4178. }
  4179. } catch (error) {
  4180. console.error("Update check failed: ", error);
  4181. }
  4182. }
  4183.  
  4184. /**
  4185. * 公告
  4186. */
  4187. async function showAnnounce() {
  4188. /** @type {string} 最新公告版本*/
  4189. const lastAnnounceVer = i18next.t('lastVersion', { ns: 'announce' });
  4190. if (OJB_compareVersions(OJBetter.state.version, OJBetter.state.lastAnnounceVer) === 1) {
  4191. const title = `🎉${i18next.t('announce.title', { ns: 'dialog' })} ${OJBetter.state.version}`;
  4192. /** @type {Boolean} 是否是新的公告 */
  4193. const isNewAnnounceVer = OJB_compareVersions(lastAnnounceVer, OJBetter.state.lastReadAnnounceVer) === 1;
  4194. /** @type {Boolean} 是否展示新的公告(高于当前版本的测试公告不展示) */
  4195. const showNewAnnounceVer = OJB_compareVersions(lastAnnounceVer, OJBetter.state.version) !== 1;
  4196. /**
  4197. * 获取最后三个公告的内容
  4198. * @param {string} lastAnnounceVer
  4199. * @returns {string} 公告内容
  4200. */
  4201. const getLastThreeAnnounceContent = function (lastAnnounceVer) {
  4202. let content = "";
  4203. for (let i = 0; i < 3; i++) {
  4204. content += `### ${lastAnnounceVer}\n\n`;
  4205. content += i18next.t(`${lastAnnounceVer}`, { ns: 'announce' });
  4206. content += "\n\n";
  4207. lastAnnounceVer = OJB_getPreviousVersion(lastAnnounceVer);
  4208. }
  4209. return content;
  4210. };
  4211.  
  4212. const content = (() => {
  4213. if (isNewAnnounceVer && showNewAnnounceVer) {
  4214. return `${i18next.t('announce.prefix', { ns: 'dialog' })}\n\n${getLastThreeAnnounceContent(lastAnnounceVer)}`;
  4215. } else {
  4216. return i18next.t('announce.divContent', { ns: 'dialog' });
  4217. }
  4218. })();
  4219. const ok = await OJB_createDialog(
  4220. title,
  4221. content,
  4222. [
  4223. null,
  4224. i18next.t('announce.buttons.0', { ns: 'dialog' })
  4225. ],
  4226. true
  4227. ); //跳过折叠块确认
  4228. if (ok) {
  4229. if (isNewAnnounceVer && showNewAnnounceVer) {
  4230. GM_setValue('lastReadAnnounceVer', lastAnnounceVer);
  4231. }
  4232. GM_setValue('lastAnnounceVer', OJBetter.state.version);
  4233. }
  4234. }
  4235. };
  4236.  
  4237. /**
  4238. * 页面顶部提示信息alert类
  4239. */
  4240. class LoadingMessage {
  4241. constructor() {
  4242. this._statusElement = null;
  4243. this._isDisplayed = false;
  4244. this.init();
  4245. }
  4246.  
  4247. /**
  4248. * 初始化加载提示信息
  4249. */
  4250. init() {
  4251. this._statusElement = this.createStatusElement();
  4252. this.insertStatusElement();
  4253. }
  4254.  
  4255. /**
  4256. * 创建提示信息元素
  4257. */
  4258. createStatusElement() {
  4259. const statusElement = $("<div></div>").addClass("alert OJBetter_alert")
  4260. .css({
  4261. "margin": "1em",
  4262. "text-align": "center",
  4263. "position": "relative"
  4264. }).hide();
  4265. return statusElement;
  4266. }
  4267.  
  4268. /**
  4269. * 插入提示信息
  4270. * @returns {void}
  4271. */
  4272. insertStatusElement() {
  4273. // (OJBetter.typeOfPage.is_mSite ? $("header") : $(".menu-box:first").next()).after(this._statusElement);
  4274. $("#main-container").prepend(this._statusElement);
  4275. }
  4276.  
  4277. /**
  4278. * 显示提示信息
  4279. */
  4280. showStatus() {
  4281. this._statusElement.show();
  4282. this._isDisplayed = true;
  4283. }
  4284.  
  4285. /**
  4286. * 隐藏提示信息
  4287. */
  4288. hideStatus() {
  4289. this._statusElement.fadeOut(500);
  4290. this._isDisplayed = false;
  4291. }
  4292.  
  4293. /**
  4294. * 移除提示信息
  4295. */
  4296. removeStatus() {
  4297. this._statusElement.remove();
  4298. this._isDisplayed = false;
  4299. }
  4300.  
  4301. /**
  4302. * 更新提示信息
  4303. * @param {string} text 提示信息文本
  4304. * @param {string} type 提示信息类型,可选值:info, success, warning, error
  4305. * @param {number} timeout 提示信息显示的持续时间(毫秒), 默认为无限长
  4306. */
  4307. updateStatus(text, type = 'info', timeout = Infinity, isMarkdown = false) {
  4308. if (isMarkdown) {
  4309. let md = window.markdownit({
  4310. html: !is_escapeHTML,
  4311. });
  4312. text = md.render(text);
  4313. }
  4314. this._statusElement.html(text).removeClass("alert-info alert-success alert-warning alert-error").addClass(`alert-${type}`);
  4315. if (!this._isDisplayed) {
  4316. this.showStatus();
  4317. }
  4318. if (timeout !== Infinity) {
  4319. setTimeout(() => {
  4320. this.hideStatus();
  4321. }, timeout);
  4322. }
  4323. }
  4324. }
  4325.  
  4326. /**
  4327. * 获取网站本地化的数据
  4328. * @param {*} localizationLanguage 本地化语言
  4329. * @returns {Promise<Object>} 本地化数据
  4330. */
  4331. async function getLocalizeWebsiteJson(localizationLanguage) {
  4332. let data = await OJBetter.common.database.localizeSubsData.get(localizationLanguage);
  4333. let url = localizationLanguage === "zh" ?
  4334. `https://aowuucdn.oss-accelerate.aliyuncs.com/resources/subs/${OJBetter.state.formatName}.json` :
  4335. `https://aowuucdn.oss-accelerate.aliyuncs.com/i18n/${localizationLanguage}/resources/subs/${OJBetter.state.formatName}.json`;
  4336. if (data) data = data.data;
  4337. if (!data) {
  4338. // 如果本地没有数据,从远端获取并保存
  4339. data = await OJB_getExternalJSON(url);
  4340. await OJBetter.common.database.localizeSubsData.put({ lang: localizationLanguage, data: data });
  4341. } else {
  4342. // 如果本地有数据,检查是否已经在当前会话中尝试过更新
  4343. const sessionKey = `ojb_updateL10nWebsiteJson_${localizationLanguage}`;
  4344. if (!OJB_isSameBrowserSession(sessionKey)) {
  4345. // 如果尚未更新,则在后台更新
  4346. (async () => {
  4347. try {
  4348. const newData = await OJB_getExternalJSON(url);
  4349. await OJBetter.common.database.localizeSubsData.put({ lang: localizationLanguage, data: newData });
  4350. console.log("Website local data has been refreshed!");
  4351. } catch (error) {
  4352. console.error('Failed to update localization data:', error);
  4353. }
  4354. })();
  4355. }
  4356. }
  4357. return data;
  4358. }
  4359.  
  4360. /**
  4361. * 网站本地化替换
  4362. * @returns
  4363. */
  4364. async function localizeWebsite() {
  4365. if (OJBetter.localization.websiteLang === "initial") return;
  4366.  
  4367. // 设置网页语言
  4368. var htmlTag = document.getElementsByTagName("html")[0];
  4369. htmlTag.setAttribute("lang", OJBetter.localization.websiteLang);
  4370.  
  4371. // 获取网站本地化的数据
  4372. var subs = await getLocalizeWebsiteJson(OJBetter.localization.websiteLang);
  4373.  
  4374. /**
  4375. * 文本节点遍历替换
  4376. * @param {JQuery} $nodes jQuery对象
  4377. * @param {Object} textReplaceRules 文本替换规则对象
  4378. */
  4379. function traverseTextNodes($nodes, textReplaceRules) {
  4380. if (!$nodes) return;
  4381.  
  4382. $nodes.each(function () {
  4383. let node = this;
  4384. if (node.nodeType === Node.TEXT_NODE) {
  4385. Object.keys(textReplaceRules).forEach(match => {
  4386. try {
  4387. const replace = textReplaceRules[match];
  4388. const regex = new RegExp(match, 'g');
  4389. node.textContent = node.textContent.replace(regex, replace);
  4390. } catch (error) {
  4391. console.error(`Error processing text replacement for match: ${match}`, error);
  4392. }
  4393. });
  4394. } else {
  4395. $(node).contents().each(function () {
  4396. traverseTextNodes($(this), textReplaceRules);
  4397. });
  4398. }
  4399. });
  4400. }
  4401.  
  4402. /**
  4403. * value替换
  4404. * @param {JQuery} $nodes jQuery对象
  4405. * @param {Object} valueReplaceRules 值替换规则对象
  4406. */
  4407. function traverseValueNodes($nodes, valueReplaceRules) {
  4408. if (!$nodes) return;
  4409.  
  4410. $nodes.each(function () {
  4411. let $node = $(this);
  4412. if ($node.is('[value]')) {
  4413. Object.keys(valueReplaceRules).forEach(match => {
  4414. const replace = valueReplaceRules[match];
  4415. const regex = new RegExp(match, 'g');
  4416. let currentValue = $node.val();
  4417. let newValue = currentValue.replace(regex, replace);
  4418. $node.val(newValue);
  4419. });
  4420. } else {
  4421. $node.children().each(function () {
  4422. traverseValueNodes($(this), valueReplaceRules);
  4423. });
  4424. }
  4425. });
  4426. }
  4427.  
  4428. /**
  4429. * 严格的文本节点遍历替换
  4430. * @param {JQuery} $node jQuery对象
  4431. * @param {Object} textReplaceRules 文本替换规则对象
  4432. */
  4433. function strictTraverseTextNodes($nodes, textReplaceRules) {
  4434. if (!$nodes) return;
  4435.  
  4436. $nodes.each(function () {
  4437. let $node = $(this);
  4438. if ($node.nodeType === Node.TEXT_NODE) {
  4439. const trimmedNodeText = $node.textContent.trim();
  4440. Object.keys(textReplaceRules).forEach(match => {
  4441. if (trimmedNodeText === match) {
  4442. $node.textContent = textReplaceRules[match];
  4443. }
  4444. });
  4445. } else {
  4446. $($node).contents().each(function () {
  4447. strictTraverseTextNodes($(this), textReplaceRules);
  4448. });
  4449. }
  4450. });
  4451. }
  4452.  
  4453. /**
  4454. * 应用文本替换
  4455. */
  4456. let commonReplacements = subs.commonReplacements;
  4457. Object.entries(commonReplacements).forEach(([key, value]) => {
  4458. const classSelectors = Array.isArray(value.class) ? value.class : [value.class]; // 兼容,class的值可以为数组或者字符串
  4459. classSelectors.forEach(classSelector => {
  4460. if (value.isStrict) {
  4461. strictTraverseTextNodes(OJB_safeCreateJQElement(`${classSelector}`), value.rules);
  4462. } else {
  4463. traverseTextNodes(OJB_safeCreateJQElement(`${classSelector}`), value.rules);
  4464. }
  4465. });
  4466. });
  4467.  
  4468. // 测试
  4469. {
  4470. // var translations = {
  4471. //
  4472. // };
  4473. // traverseTextNodes($('xxx'), translations);
  4474. };
  4475.  
  4476. /**
  4477. * 应用value替换
  4478. */
  4479. let InputValueReplacements = subs.InputValueReplacements;
  4480. Object.entries(InputValueReplacements).forEach(([key, value]) => {
  4481. const classSelectors = Array.isArray(value.class) ? value.class : [value.class];
  4482. classSelectors.forEach(classSelector => {
  4483. traverseValueNodes(OJB_safeCreateJQElement(`${classSelector}`), value.rules);
  4484. });
  4485. });
  4486.  
  4487. // // 杂项
  4488. // (function () {
  4489. // // 选项汉化input[type="radio"]
  4490. // var translations = {
  4491. // "as individual participant": "个人",
  4492. // "as a team member": "作为一个团队成员",
  4493. // };
  4494. // $('input[type="radio"]').each(function () {
  4495. // var tag = $(this).parent().contents().filter(function () {
  4496. // return this.nodeType === Node.TEXT_NODE;
  4497. // });
  4498. // for (var i = 0; i < tag.length; i++) {
  4499. // var text = tag[i].textContent.trim();
  4500. // if (translations.hasOwnProperty(text)) {
  4501. // $(this).addClass(text);
  4502. // tag[i].replaceWith(translations[text]);
  4503. // break;
  4504. // }
  4505. // }
  4506. // });
  4507. // })();
  4508. // (function () {
  4509. // var translations = {
  4510. // "(standard input\/output)": "标准输入/输出",
  4511. // };
  4512. // $("div.notice").each(function () {
  4513. // var tag = $(this).children().eq(0).text();
  4514. // for (var property in translations) {
  4515. // if (tag.match(property)) {
  4516. // $(this).children().eq(0).text(translations[property]);
  4517. // break;
  4518. // }
  4519. // }
  4520. // });
  4521. // })();
  4522.  
  4523. // // 轻量站特殊
  4524. // if (OJBetter.typeOfPage.is_mSite) {
  4525. // traverseTextNodes($('nav'), commonReplacements['.second-level-menu']['rules']);
  4526. // }
  4527. // if (OJBetter.typeOfPage.is_mSite) {
  4528. // (function () {
  4529. // var translations = {
  4530. // "Announcements": "公告",
  4531. // "Submissions": "提交记录",
  4532. // "Contests": "比赛",
  4533. // };
  4534. // $(".caption").each(function () {
  4535. // var optionValue = $(this).text();
  4536. // if (translations[optionValue]) {
  4537. // $(this).text(translations[optionValue]);
  4538. // }
  4539. // });
  4540. // })();
  4541. // }
  4542. };
  4543.  
  4544. /**
  4545. * i18next初始化
  4546. */
  4547. async function initI18next() {
  4548. return new Promise((resolve, reject) => {
  4549. i18next
  4550. .use(i18nextChainedBackend)
  4551. .init({
  4552. lng: OJBetter.localization.scriptLang,
  4553. ns: ['common', 'settings', 'config', 'dialog', 'alert', 'translator',
  4554. 'button', 'codeEditor', 'comments', 'announce', 'logMessage'], // 命名空间列表
  4555. defaultNS: 'settings',
  4556. fallbackLng: ['zh', OJBetter.translation.targetLang],
  4557. load: 'currentOnly',
  4558. debug: false,
  4559. backend: {
  4560. backends: [
  4561. i18nextLocalStorageBackend,
  4562. i18nextHttpBackend
  4563. ],
  4564. backendOptions: [{
  4565. prefix: 'i18next_res_',
  4566. expirationTime: 7 * 24 * 60 * 60 * 1000,
  4567. defaultVersion: `v${OJBetter.state.version}`,
  4568. store: typeof window !== 'undefined' ? window.localStorage : null
  4569. }, {
  4570. /* options for secondary backend */
  4571. loadPath: (lng, ns) => {
  4572. if (lng[0] === 'zh' || lng[0] === 'zh-Hans') {
  4573. return `https://aowuucdn.oss-accelerate.aliyuncs.com/resources/locales/${OJBetter.state.formatName}/${ns}.json`;
  4574. }
  4575. return `https://aowuucdn.oss-accelerate.aliyuncs.com/i18n/${lng}/resources/locales/${OJBetter.state.formatName}/${ns}.json`;
  4576. }
  4577. }]
  4578. }
  4579. }, (err, t) => {
  4580. if (err) {
  4581. reject(err);
  4582. } else {
  4583. jqueryI18next.init(i18next, $, {
  4584. useOptionsAttr: true
  4585. });
  4586. resolve(t);
  4587. }
  4588. });
  4589. });
  4590. };
  4591.  
  4592. /**
  4593. * 抽象命令类
  4594. */
  4595. class Command {
  4596. execute() { }
  4597. undo() { }
  4598. }
  4599.  
  4600. /**
  4601. * 命令调用者
  4602. */
  4603. class CommandInvoker {
  4604. constructor() {
  4605. this.history = [];
  4606. }
  4607.  
  4608. /**
  4609. * 执行命令
  4610. * @param {Command} command 命令对象
  4611. */
  4612. execute(command) {
  4613. this.history.push(command);
  4614. command.execute();
  4615. }
  4616.  
  4617. /**
  4618. * 撤销命令
  4619. */
  4620. undo() {
  4621. const command = this.history.pop();
  4622. if (command) {
  4623. command.undo();
  4624. }
  4625. }
  4626. }
  4627.  
  4628. /**
  4629. * 接收者
  4630. */
  4631. class DOMContainer {
  4632. /**
  4633. * @param {JQueryObject} element 容器对象
  4634. */
  4635. constructor(element) {
  4636. this.containerElement = element;
  4637. }
  4638.  
  4639. /**
  4640. * 添加元素
  4641. * @param {JQueryObject} element 元素对象
  4642. * @returns {JQueryObject} 添加的元素对象
  4643. */
  4644. add(element) {
  4645. this.containerElement.append(element);
  4646. return this.containerElement.children().last();
  4647. }
  4648.  
  4649. /**
  4650. * 删除元素
  4651. * @param {JQueryObject} element 元素对象
  4652. */
  4653. remove(element) {
  4654. $(element).remove();
  4655. }
  4656. }
  4657.  
  4658. /**
  4659. * 具体命令类:添加元素
  4660. */
  4661. class AddElementCommand extends Command {
  4662. /**
  4663. * @param {DOMContainer} receiver 接收者
  4664. * @param {JQueryObject} element 元素对象
  4665. */
  4666. constructor(receiver, element) {
  4667. super();
  4668. this.receiver = receiver;
  4669. this.element = element;
  4670. this.addedElement = null;
  4671. }
  4672.  
  4673. execute() {
  4674. this.addedElement = this.receiver.add(this.element);
  4675. }
  4676.  
  4677. undo() {
  4678. if (this.addedElement) {
  4679. this.receiver.remove(this.addedElement);
  4680. }
  4681. }
  4682. }
  4683.  
  4684. /**
  4685. * 具体命令类:删除元素
  4686. */
  4687. class RemoveElementCommand extends Command {
  4688. /**
  4689. * @param {DOMContainer} receiver 接收者
  4690. * @param {JQueryObject} element 元素对象
  4691. */
  4692. constructor(receiver, element) {
  4693. super();
  4694. this.receiver = receiver;
  4695. this.element = element;
  4696. this.parent = $(element).parent();
  4697. this.nextSibling = $(element).next();
  4698. }
  4699.  
  4700. execute() {
  4701. this.receiver.remove(this.element);
  4702. }
  4703.  
  4704. undo() {
  4705. if (this.nextSibling.length > 0) {
  4706. $(this.element).insertBefore(this.nextSibling);
  4707. } else {
  4708. this.parent.append(this.element);
  4709. }
  4710. }
  4711. }
  4712.  
  4713. /**
  4714. * 验证器
  4715. */
  4716. class Validator {
  4717. /**
  4718. * 表单必填项空值校验
  4719. */
  4720. static required(structure) {
  4721. let config = {};
  4722. let allFieldsValid = true;
  4723. for (const key in structure) {
  4724. let value = key.type == 'checkbox' ?
  4725. $(key).prop("checked") : $(key).val();
  4726.  
  4727. config[structure[key].value] = value;
  4728.  
  4729. if (value || structure[key].require === false) {
  4730. $(key).removeClass('is_null');
  4731. } else {
  4732. $(key).addClass('is_null');
  4733. allFieldsValid = false;
  4734. }
  4735. }
  4736. return {
  4737. valid: allFieldsValid,
  4738. config: config
  4739. };
  4740. }
  4741.  
  4742. /**
  4743. * 表单合法性校验
  4744. */
  4745. static checkKeyValuePairs(structure, config) {
  4746. let errorKeys = [];
  4747. let allFieldsValid = true;
  4748.  
  4749. for (const key in structure) {
  4750. const { check, value } = structure[key];
  4751. const fieldValue = config[value];
  4752.  
  4753. // 如果字段没有值或校验类型不匹配,则跳过当前迭代
  4754. if (!fieldValue) continue;
  4755.  
  4756. let isValid = true;
  4757. switch (check) {
  4758. case 'keyValuePairs':
  4759. isValid = Validator.keyValuePairs(fieldValue);
  4760. break;
  4761. case 'dotSeparatedPath':
  4762. isValid = Validator.validateDotSeparatedPath(fieldValue);
  4763. break;
  4764. default:
  4765. // 没有匹配的校验类型
  4766. continue;
  4767. }
  4768.  
  4769. Validator.toggleErrorDisplay(key, isValid);
  4770. if (!isValid) {
  4771. allFieldsValid = false;
  4772. errorKeys.push(key);
  4773. }
  4774. }
  4775.  
  4776. return {
  4777. valid: allFieldsValid,
  4778. errorKeys: errorKeys
  4779. };
  4780. }
  4781.  
  4782. /**
  4783. * 切换错误信息的显示和隐藏
  4784. * @param {string} key - 字段的键
  4785. * @param {boolean} isValid - 字段值是否有效
  4786. */
  4787. static toggleErrorDisplay(key, isValid) {
  4788. const errorMessage = i18next.t('common.unValid', { ns: 'settings' });
  4789. const $errorSpan = $(key).prev('span.text-error');
  4790. if (!isValid) {
  4791. if (!$errorSpan.length) {
  4792. $(key).before(`<span class="text-error" style="color: red;">${errorMessage}</span>`);
  4793. }
  4794. } else {
  4795. $errorSpan.remove();
  4796. }
  4797. }
  4798.  
  4799. /**
  4800. * 键值对合法性校验
  4801. * @param {string} value
  4802. * @returns {boolean}
  4803. */
  4804. static keyValuePairs(value) {
  4805. const keyValuePairs = value.split('\n');
  4806. // 允许值中包含空格和冒号
  4807. const regex = /^[a-zA-Z0-9_-]+\s*:\s*.+$/;
  4808. return keyValuePairs.every(pair => regex.test(pair));
  4809. }
  4810.  
  4811.  
  4812. /**
  4813. * 点分隔符路径格式校验,允许加减运算
  4814. * @param {string} path
  4815. * @returns {boolean}
  4816. */
  4817. static validateDotSeparatedPath(path) {
  4818. // 正则表达式允许标识符之间有点号,标识符可以包含加减运算
  4819. const regex = /^([a-zA-Z0-9_-]+(\s*[\+\-]\s*[a-zA-Z0-9_-]+)*\.)*([a-zA-Z0-9_-]+(\s*[\+\-]\s*[a-zA-Z0-9_-]+)*)$/;
  4820. return regex.test(path);
  4821. }
  4822. }
  4823.  
  4824. /**
  4825. * 配置管理
  4826. */
  4827. class ConfigManager {
  4828. /**
  4829. * @param {HTMLElement} element - 挂载容器
  4830. * @param {string} prefix - 前缀
  4831. * @param {object} tempConfig - 配置内容
  4832. * @param {object} structure - 配置结构
  4833. * @param {object} configHTML - 配置编辑页面HTML
  4834. * @param {boolean} allowChoice - 是否允许选择列表项
  4835. */
  4836. constructor(element, prefix, tempConfig, structure, configHTML, allowChoice = true) {
  4837. /** @param 设置面板DIV */
  4838. this.settingMenuDiv = $('#OJBetter_setting_menu');
  4839. this.element = $(element);
  4840. this.prefix = prefix;
  4841. this.tempConfig = tempConfig;
  4842. this.structure = structure;
  4843. this.configHTML = configHTML;
  4844. this.allowChoice = allowChoice;
  4845.  
  4846. this.controlTip = null;
  4847. this.config_bar_list = null;
  4848. this.config_bar_ul = null;
  4849. this.config_add_button = null;
  4850. this.menu = null;
  4851. this.editItem = null;
  4852. this.deleteItem = null;
  4853.  
  4854. // 绑定方法
  4855. this.onAdd = this.onAdd.bind(this);
  4856. this.onEdit = this.onEdit.bind(this);
  4857. this.onDelete = this.onDelete.bind(this);
  4858. this.createListItemElement = this.createListItemElement.bind(this);
  4859.  
  4860. this.lastItemId = 0; // 列表中当前最后一个元素的id号
  4861. this.init();
  4862. }
  4863.  
  4864. init() {
  4865. this.createControlBar();
  4866. this.createContextMenu();
  4867. this.renderList();
  4868. }
  4869.  
  4870. /**
  4871. * 创建控制栏
  4872. */
  4873. createControlBar() {
  4874. this.controlTip = OJB_safeCreateJQElement(`<div id='${this.prefix}configControlTip' style='color:red;'></div>`);
  4875. this.config_bar_list = OJB_safeCreateJQElement(`<div class='config_bar_list' id='${this.prefix}config_bar_list'></div>`);
  4876. this.config_bar_ul = OJB_safeCreateJQElement(`<ul class='config_bar_ul' id='${this.prefix}config_bar_ul'></ul>`);
  4877. this.element.append(this.controlTip);
  4878. this.element.append(this.config_bar_list);
  4879. this.config_bar_list.append(this.config_bar_ul);
  4880. }
  4881.  
  4882. /**
  4883. * 创建右键菜单
  4884. */
  4885. createContextMenu() {
  4886. const menu = OJB_safeCreateJQElement(`<div id='config_bar_menu' style='display: none;'></div>`);
  4887. const editItem = OJB_safeCreateJQElement(`
  4888. <div class='config_bar_menu_item' id='config_bar_menu_edit'>
  4889. ${i18next.t('contextMenu.edit', { ns: 'translator' })}
  4890. </div>`);
  4891. const deleteItem = OJB_safeCreateJQElement(`
  4892. <div class='config_bar_menu_item' id='config_bar_menu_delete'>
  4893. ${i18next.t('contextMenu.delete', { ns: 'translator' })}
  4894. </div>`);
  4895. menu.append(editItem);
  4896. menu.append(deleteItem);
  4897. this.editItem = editItem;
  4898. this.deleteItem = deleteItem;
  4899. this.menu = menu;
  4900. this.settingMenuDiv.append(menu);
  4901. }
  4902.  
  4903. /**
  4904. * 关闭右键菜单
  4905. */
  4906. closeContextMenu() {
  4907. this.menu.css({ display: "none" });
  4908. }
  4909.  
  4910. /**
  4911. * 创建列表项
  4912. * @param {string} text - 列表项文本
  4913. * @returns {HTMLElement} - 列表项
  4914. */
  4915. createListItemElement(text) {
  4916. const id = OJB_getRandomNumber(4);
  4917. const li = $("<li></li>");
  4918. const radio = OJB_safeCreateJQElement(`<input type='radio' name='${this.prefix}config_item'></input>`)
  4919. .attr("value", text)
  4920. .attr("id", id)
  4921. .attr("prev_id", this.lastItemId)
  4922. .appendTo(li);
  4923. if (!this.allowChoice) {
  4924. radio.prop("disabled", true);
  4925. }
  4926. const label = OJB_safeCreateJQElement(`<label for='${id}' class='config_bar_ul_li_text'>${text}</label>`).appendTo(li);
  4927.  
  4928.  
  4929. this.lastItemId = id;
  4930.  
  4931. // 添加右键菜单
  4932. li.on("contextmenu", (event) => {
  4933. event.preventDefault();
  4934. this.menu.css({
  4935. display: "block",
  4936. left: event.pageX, top: event.pageY
  4937. });
  4938.  
  4939. const deleteItem = this.deleteItem;
  4940. const editItem = this.editItem;
  4941.  
  4942. // 移除旧事件
  4943. deleteItem.off("click");
  4944. editItem.off("click");
  4945.  
  4946. // 获取 li 在 ul 中的索引
  4947. const index = li.index();
  4948.  
  4949. deleteItem.on("click", () => this.onDelete(index, li));
  4950. editItem.on("click", () => this.onEdit(index, li));
  4951.  
  4952. $(document).one("click", (event) => {
  4953. if (!this.menu.get(0).contains(event.target)) {
  4954. this.closeContextMenu();
  4955. deleteItem.off("click", () => this.onDelete);
  4956. editItem.off("click", () => this.onEdit);
  4957. }
  4958. });
  4959. });
  4960.  
  4961. return li;
  4962. }
  4963.  
  4964. /**
  4965. * 渲染配置列表
  4966. */
  4967. renderList() {
  4968. const list = this.config_bar_ul;
  4969. list.empty(); // 清空
  4970. this.tempConfig.configurations.forEach((item) => {
  4971. list.append(this.createListItemElement(item['name']));
  4972. });
  4973.  
  4974. // 添加按钮
  4975. let addButton = OJB_safeCreateJQElement(`<li id='${this.prefix}add_button' class="tempConfig_add_button">
  4976. <span>+ ${i18next.t('add', { ns: 'common' })}</span>
  4977. </li>`);
  4978. this.config_add_button = addButton;
  4979. list.append(addButton);
  4980. addButton.on("click", this.onAdd);
  4981. }
  4982.  
  4983. /**
  4984. * 添加配置项
  4985. */
  4986. onAdd() {
  4987. const configMenu = this.createConfigHTML();
  4988. const structure = this.structure;
  4989.  
  4990. configMenu.on("click", "#tempConfig_save", () => {
  4991.  
  4992. // 检查必填字段
  4993. const { valid, config } = Validator.required(structure);
  4994. if (!valid) return;
  4995.  
  4996. // 检查键值对
  4997. const { valid: checkOk, errorKey } = Validator.checkKeyValuePairs(structure, config);
  4998. if (!checkOk) return;
  4999.  
  5000. this.tempConfig.configurations.push(config);
  5001.  
  5002. this.createListItemElement(config.name).insertBefore(this.config_add_button);
  5003.  
  5004. configMenu.remove();
  5005. });
  5006.  
  5007. configMenu.on("click", ".btn-close", () => {
  5008. configMenu.remove();
  5009. });
  5010. }
  5011.  
  5012. /**
  5013. * 修改配置项
  5014. * @param {number} index - 配置项索引
  5015. * @param {HTMLElement} li - 配置项
  5016. * @returns {void}
  5017. */
  5018. onEdit(index, li) {
  5019. const configMenu = this.createConfigHTML();
  5020. const structure = this.structure;
  5021.  
  5022. this.closeContextMenu();
  5023.  
  5024. // 填充表单
  5025. for (const [key, { value, type }] of Object.entries(this.structure)) {
  5026. const configValue = this.tempConfig.configurations[index][value];
  5027. const $element = $(key);
  5028. if (type === 'checkbox') {
  5029. $element.prop("checked", configValue);
  5030. } else {
  5031. $element.val(configValue);
  5032. }
  5033. }
  5034.  
  5035. configMenu.on("click", "#tempConfig_save", () => {
  5036. // 检查必填字段
  5037. const { valid, config } = Validator.required(structure);
  5038. if (!valid) return;
  5039.  
  5040. // 检查键值对
  5041. const { valid: checkOk, errorKey } = Validator.checkKeyValuePairs(structure, config);
  5042. if (!checkOk) return;
  5043.  
  5044. // 更新配置
  5045. this.tempConfig.configurations[index] = config;
  5046. li.find('label').text(config.name);
  5047.  
  5048. OJB_closeAndRemoveModal(configMenu);
  5049. });
  5050.  
  5051. configMenu.on("click", ".btn-close", () => {
  5052. OJB_closeAndRemoveModal(configMenu);
  5053. });
  5054. }
  5055.  
  5056. /**
  5057. * 删除配置项
  5058. * @param {number} index - 配置项索引
  5059. * @param {HTMLElement} li - 配置项
  5060. * @returns {void}
  5061. */
  5062. onDelete(index, li) {
  5063. this.closeContextMenu();
  5064. this.tempConfig.configurations.splice(index, 1);
  5065. li.remove();
  5066. }
  5067.  
  5068. /**
  5069. * 创建配置编辑页面
  5070. * @returns {JQuery<HTMLElement>} 返回配置编辑页面
  5071. */
  5072. createConfigHTML() {
  5073. const configMenu = OJB_safeCreateJQElement(this.configHTML);
  5074. this.settingMenuDiv.after(configMenu);
  5075. OJB_showModal(configMenu);
  5076. OJB_addDraggable(configMenu);
  5077. elementLocalize(configMenu);
  5078. return configMenu;
  5079. }
  5080.  
  5081. /**
  5082. * 获取配置内容
  5083. * @returns {object} - 配置内容
  5084. */
  5085. getTempConfig() {
  5086. return this.tempConfig;
  5087. }
  5088.  
  5089. /**
  5090. * 注册列表项选中改变监听
  5091. */
  5092. registerChoiceChange() {
  5093. this.config_bar_ul.on("change", "input[type='radio']", (event) => {
  5094. const value = event.target.value;
  5095. this.tempConfig.choice = value;
  5096. });
  5097. }
  5098. }
  5099.  
  5100. const OJBetter_setting_sidebar_HTML = `
  5101. <div class="OJBetter_setting_sidebar">
  5102. <ul>
  5103. <li><a href="#basic-settings" id="sidebar-basic-settings" class="active" data-i18n="settings:sidebar.basic"></a></li>
  5104. <li><a href="#l10n_settings" id="sidebar-l10n_settings" data-i18n="settings:sidebar.localization"></a></li>
  5105. <li><a href="#translation-settings" id="sidebar-translation-settings" data-i18n="settings:sidebar.translation"></a></li>
  5106. <li><a href="#clist_rating-settings" id="sidebar-clist_rating-settings" data-i18n="settings:sidebar.clist"></a></li>
  5107. <li><a href="#code_editor-settings" id="sidebar-code_editor-settings" data-i18n="settings:sidebar.monaco"></a></li>
  5108. <li><a href="#preference-settings" id="sidebar-preference-settings" data-i18n="settings:sidebar.preference"></a></li>
  5109. <li><a href="#dev-settings" id="sidebar-dev-settings" data-i18n="settings:sidebar.dev"></a></li>
  5110. <li><a href="#about-settings" id="sidebar-about-settings" data-i18n="settings:sidebar.about"></a></li>
  5111. </ul>
  5112. </div>
  5113. `;
  5114.  
  5115. const basic_settings_HTML = `
  5116. <div id="basic-settings" class="settings-page active">
  5117. <h3 data-i18n="settings:basic.title"></h3>
  5118. <hr>
  5119. <div class='OJBetter_setting_list' style="padding: 0px 10px;">
  5120. <span id="darkMode_span" data-i18n="settings:basic.darkMode.name"></span>
  5121. <div class="dark-mode-selection">
  5122. <label>
  5123. <input class="radio-input" type="radio" name="darkMode" value="dark" />
  5124. <span class="OJBetter_setting_menu_label_text"
  5125. data-i18n="settings:basic.darkMode.options.dark"></span>
  5126. <span class="radio-icon"> </span>
  5127. </label>
  5128. <label>
  5129. <input checked="" class="radio-input" type="radio" name="darkMode" value="light" />
  5130. <span class="OJBetter_setting_menu_label_text"
  5131. data-i18n="settings:basic.darkMode.options.light"></span>
  5132. <span class="radio-icon"> </span>
  5133. </label>
  5134. <label>
  5135. <input class="radio-input" type="radio" name="darkMode" value="follow" />
  5136. <span class="OJBetter_setting_menu_label_text"
  5137. data-i18n="settings:basic.darkMode.options.system"></span>
  5138. <span class="radio-icon"> </span>
  5139. </label>
  5140. </div>
  5141. </div>
  5142. <div class='OJBetter_setting_list' style="display:none;">
  5143. <label for="expandFoldingblocks" data-i18n="settings:basic.expandBlocks"></label>
  5144. <input type="checkbox" id="expandFoldingblocks" name="expandFoldingblocks">
  5145. </div>
  5146. <div class='OJBetter_setting_list' style="display:none;">
  5147. <label for="renderPerfOpt" data-i18n="settings:basic.renderOptimization.label"></label>
  5148. <div class="help_tip">
  5149. ${helpCircleHTML}
  5150. <div class="tip_text" data-i18n="[html]settings:basic.renderOptimization.helpText"></div>
  5151. </div>
  5152. <input type="checkbox" id="renderPerfOpt" name="renderPerfOpt">
  5153. </div>
  5154. <div class='OJBetter_setting_list' style="display:none;">
  5155. <label for="commentPaging" data-i18n="settings:basic.paging.label"></label>
  5156. <div class="help_tip">
  5157. ${helpCircleHTML}
  5158. <div class="tip_text" data-i18n="[html]settings:basic.paging.helpText"></div>
  5159. </div>
  5160. <input type="checkbox" id="commentPaging" name="commentPaging">
  5161. </div>
  5162. <div class='OJBetter_setting_list'>
  5163. <label for="showJumpToLuogu" data-i18n="settings:basic.luoguJump.label"></label>
  5164. <div class="help_tip">
  5165. ${helpCircleHTML}
  5166. <div class="tip_text" data-i18n="[html]settings:basic.luoguJump.helpText"></div>
  5167. </div>
  5168. <input type="checkbox" id="showJumpToLuogu" name="showJumpToLuogu">
  5169. </div>
  5170. <div class='OJBetter_setting_list'>
  5171. <label for="showCF2vjudge" data-i18n="settings:basic.vjudgeJump.label"></label>
  5172. <div class="help_tip">
  5173. ${helpCircleHTML}
  5174. <div class="tip_text" data-i18n="[html]settings:basic.vjudgeJump.helpText"></div>
  5175. </div>
  5176. <input type="checkbox" id="showCF2vjudge" name="showCF2vjudge">
  5177. </div>
  5178. <div class='OJBetter_setting_list' style="display:none;">
  5179. <label for="standingsRecolor" data-i18n="settings:basic.recolor.label"></label>
  5180. <div class="help_tip">
  5181. ${helpCircleHTML}
  5182. <div class="tip_text" data-i18n="[html]settings:basic.recolor.helpText"></div>
  5183. </div>
  5184. <input type="checkbox" id="standingsRecolor" name="standingsRecolor">
  5185. </div>
  5186. </div>
  5187. `;
  5188.  
  5189. const l10n_settings_HTML = `
  5190. <div id="l10n_settings" class="settings-page">
  5191. <h3 data-i18n="settings:localization.title"></h3>
  5192. <hr>
  5193. <div class='OJBetter_setting_list'>
  5194. <label for="scriptL10nLanguage" style="display: flex;" data-i18n="settings:localization.scriptLanguageLabel"></label>
  5195. <select id="scriptL10nLanguage" name="scriptL10nLanguage">
  5196. <option value="zh">简体中文</option>
  5197. <option value="zh-Hant">繁體中文</option>
  5198. <option value="en">English</option>
  5199. <option value="de">Deutsch</option>
  5200. <option value="fr">Français</option>
  5201. <option value="ko">한국어</option>
  5202. <option value="pt">Português</option>
  5203. <option value="ja">日本語</option>
  5204. <option value="es">Español</option>
  5205. <option value="it">Italiano</option>
  5206. <option value="hi">हिन्दी</option>
  5207. </select>
  5208. </div>
  5209. <div class='OJBetter_setting_list'>
  5210. <label for="localizationLanguage" style="display: flex;" data-i18n="settings:localization.websiteLanguageLabel"></label>
  5211. <select id="localizationLanguage" name="localizationLanguage">
  5212. <option value="initial">——</option>
  5213. <option value="zh">简体中文</option>
  5214. <option value="zh-Hant">繁體中文</option>
  5215. <option value="de">Deutsch</option>
  5216. <option value="fr">Français</option>
  5217. <option value="ko">한국어</option>
  5218. <option value="pt">Português</option>
  5219. <option value="ja">日本語</option>
  5220. <option value="es">Español</option>
  5221. <option value="it">Italiano</option>
  5222. <option value="hi">हिन्दी</option>
  5223. </select>
  5224. </div>
  5225. <div class='OJBetter_setting_list alert_tip'>
  5226. <div data-i18n="[html]settings:localization.notice.1"></div>
  5227. </div>
  5228. <div class='OJBetter_setting_list alert_tip'>
  5229. <div data-i18n="[html]settings:localization.notice.2"></div>
  5230. </div>
  5231. </div>
  5232. `;
  5233.  
  5234. const translation_settings_HTML = `
  5235. <div id="translation-settings" class="settings-page">
  5236. <h3 data-i18n="settings:translation.title"></h3>
  5237. <hr>
  5238. <h4 data-i18n="settings:translation.options.title"></h4>
  5239. <div class='OJBetter_setting_list'>
  5240. <label for="transTargetLang" style="display: flex;" data-i18n="settings:translation.preference.target.title"></label>
  5241. <div class="help_tip">
  5242. ${helpCircleHTML}
  5243. <div class="tip_text" data-i18n="[html]settings:translation.preference.target.helpText"></div>
  5244. </div>
  5245. <select id="transTargetLang" name="transTargetLang">
  5246. <option value="zh">简体中文</option>
  5247. <option value="zh-Hant">繁體中文</option>
  5248. <option value="de">Deutsch</option>
  5249. <option value="fr">Français</option>
  5250. <option value="ko">한국어</option>
  5251. <option value="pt">Português</option>
  5252. <option value="ja">日本語</option>
  5253. <option value="es">Español</option>
  5254. <option value="it">Italiano</option>
  5255. <option value="hi">हिन्दी</option>
  5256. </select>
  5257. </div>
  5258. <div id="translationServices">
  5259. <label>
  5260. <input type='radio' name='translation' value='deepl'>
  5261. <span class='OJBetter_setting_menu_label_text'
  5262. data-i18n="settings:translation.options.services.deepl"></span>
  5263. </label>
  5264. <label>
  5265. <input type='radio' name='translation' value='iflyrec'>
  5266. <span class='OJBetter_setting_menu_label_text'
  5267. data-i18n="settings:translation.options.services.iflyrec"></span>
  5268. </label>
  5269. <label>
  5270. <input type='radio' name='translation' value='youdao'>
  5271. <span class='OJBetter_setting_menu_label_text'
  5272. data-i18n="settings:translation.options.services.youdao"></span>
  5273. </label>
  5274. <label>
  5275. <input type='radio' name='translation' value='google'>
  5276. <span class='OJBetter_setting_menu_label_text'
  5277. data-i18n="settings:translation.options.services.google"></span>
  5278. </label>
  5279. <label>
  5280. <input type='radio' name='translation' value='caiyun'>
  5281. <span class='OJBetter_setting_menu_label_text'
  5282. data-i18n="settings:translation.options.services.caiyun"></span>
  5283. </label>
  5284. <label>
  5285. <input type='radio' name='translation' value='openai'>
  5286. <span class='OJBetter_setting_menu_label_text'
  5287. data-i18n="settings:translation.options.services.openai.name">
  5288. <div class="help_tip">
  5289. ${helpCircleHTML}
  5290. <div class="tip_text"
  5291. data-i18n="[html]settings:translation.options.services.openai.helpText"></div>
  5292. </div>
  5293. </span>
  5294. </label>
  5295. </div>
  5296. <hr>
  5297. <h4>DeepL</h4>
  5298. <div class='OJBetter_setting_list'>
  5299. <label for="deepl_type" style="display: flex;" data-i18n="settings:translation.deepl.mode.title"></label>
  5300. <div class="help_tip">
  5301. ${helpCircleHTML}
  5302. <div class="tip_text" data-i18n="[html]settings:translation.deepl.mode.helpText"></div>
  5303. </div>
  5304. <select id="deepl_type" name="deepl_type">
  5305. <option value="free" data-i18n="settings:translation.deepl.mode.select.free"></option>
  5306. <option value="api" data-i18n="settings:translation.deepl.mode.select.api"></option>
  5307. </select>
  5308. </div>
  5309. <div id="deepl_config" class="config"></div>
  5310. <div class='OJBetter_setting_list'>
  5311. <label for="enableEmphasisProtection" data-i18n="settings:translation.deepl.enableEmphasisProtection.title"></label>
  5312. <div class="help_tip" style="margin-right: initial;">
  5313. ${helpCircleHTML}
  5314. <div class="tip_text" data-i18n="[html]settings:translation.deepl.enableEmphasisProtection.helpText"></div>
  5315. </div>
  5316. <div class="badge">Official API Only</div>
  5317. <input type="checkbox" id="enableEmphasisProtection" name="enableEmphasisProtection">
  5318. </div>
  5319. <div class='OJBetter_setting_list'>
  5320. <label for="enableLinkProtection" data-i18n="settings:translation.deepl.enableLinkProtection.title"></label>
  5321. <div class="help_tip" style="margin-right: initial;">
  5322. ${helpCircleHTML}
  5323. <div class="tip_text" data-i18n="[html]settings:translation.deepl.enableLinkProtection.helpText"></div>
  5324. </div>
  5325. <div class="badge">Official API Only</div>
  5326. <input type="checkbox" id="enableLinkProtection" name="enableLinkProtection">
  5327. </div>
  5328. <hr>
  5329. <h4>ChatGPT</h4>
  5330. <div id="chatgpt_config" class="config"></div>
  5331. <div class='OJBetter_setting_list'>
  5332. <label for="openai_isStream" data-i18n="settings:translation.chatgpt.isStream.name"></label>
  5333. <div class="help_tip">
  5334. ${helpCircleHTML}
  5335. <div class="tip_text" data-i18n="[html]settings:translation.chatgpt.isStream.helpText"></div>
  5336. </div>
  5337. <input type="checkbox" id="openai_isStream" name="openai_isStream">
  5338. </div>
  5339. <hr>
  5340. <h4 data-i18n="settings:translation.preference.title"></h4>
  5341. <div class='OJBetter_setting_list'>
  5342. <label for="comment_translation_choice" style="display: flex;"
  5343. data-i18n="settings:translation.preference.comment_translation_choice.title">
  5344. </label>
  5345. <select id="comment_translation_choice" name="comment_translation_choice">
  5346. <option value="0" data-i18n="settings:translation.preference.comment_translation_choice.services.follow"></option>
  5347. <option value="deepl" data-i18n="settings:translation.preference.comment_translation_choice.services.deepl"></option>
  5348. <option value="iflyrec" data-i18n="settings:translation.preference.comment_translation_choice.services.iflyrec"></option>
  5349. <option value="youdao" data-i18n="settings:translation.preference.comment_translation_choice.services.youdao"></option>
  5350. <option value="google" data-i18n="settings:translation.preference.comment_translation_choice.services.google"></option>
  5351. <option value="caiyun" data-i18n="settings:translation.preference.comment_translation_choice.services.caiyun"></option>
  5352. <option value="openai" data-i18n="settings:translation.preference.comment_translation_choice.services.openai"></option>
  5353. </select>
  5354. </div>
  5355. <hr>
  5356.  
  5357. <div style="display:none;">
  5358. <h4 data-i18n="settings:translation.autoTranslation.title"></h4>
  5359. <div class='OJBetter_setting_list'>
  5360. <label for="autoTranslation" data-i18n="settings:translation.autoTranslation.enable"></label>
  5361. <div class="help_tip">
  5362. ${helpCircleHTML}
  5363. <div class="tip_text" data-i18n="[html]settings:translation.autoTranslation.helpText"></div>
  5364. </div>
  5365. <input type="checkbox" id="autoTranslation" name="autoTranslation">
  5366. </div>
  5367. <div class='OJBetter_setting_list'>
  5368. <label for='shortTextLength'>
  5369. <div style="display: flex;align-items: center;"
  5370. data-i18n="settings:translation.autoTranslation.shortTextLength.name"></div>
  5371. </label>
  5372. <div class="help_tip">
  5373. ${helpCircleHTML}
  5374. <div class="tip_text" data-i18n="[html]settings:translation.autoTranslation.shortTextLength.helpText">
  5375. </div>
  5376. </div>
  5377. <input type='number' id='shortTextLength' class='no_default' require=true data-i18n="[placeholder]settings:translation.autoTranslation.shortTextLength.placeholder">
  5378. <span data-i18n="settings:translation.autoTranslation.shortTextLength.end"></span>
  5379. </div>
  5380. <div class='OJBetter_setting_list'>
  5381. <label for="allowMixTrans" data-i18n="settings:translation.autoTranslation.allowMixTrans.name"></label>
  5382. <div class="help_tip">
  5383. ${helpCircleHTML}
  5384. <div class="tip_text" data-i18n="[html]settings:translation.autoTranslation.allowMixTrans.helpText">
  5385. </div>
  5386. </div>
  5387. <input type="checkbox" id="allowMixTrans" name="allowMixTrans">
  5388. <div class='OJBetter_checkboxs'>
  5389. <input type="checkbox" id="deepl" name="mixedTranslation" value="deepl">
  5390. <label for="deepl" data-i18n="settings:translation.autoTranslation.allowMixTrans.checkboxs.deepl"></label>
  5391. <input type="checkbox" id="iflyrec" name="mixedTranslation" value="iflyrec">
  5392. <label for="iflyrec" data-i18n="settings:translation.autoTranslation.allowMixTrans.checkboxs.iflyrec"></label>
  5393. <input type="checkbox" id="youdao" name="mixedTranslation" value="youdao">
  5394. <label for="youdao" data-i18n="settings:translation.autoTranslation.allowMixTrans.checkboxs.youdao"></label>
  5395. <input type="checkbox" id="google" name="mixedTranslation" value="google">
  5396. <label for="google" data-i18n="settings:translation.autoTranslation.allowMixTrans.checkboxs.google">Google</label>
  5397. <input type="checkbox" id="caiyun" name="mixedTranslation" value="caiyun">
  5398. <label for="caiyun" data-i18n="settings:translation.autoTranslation.allowMixTrans.checkboxs.caiyun"></label>
  5399. </div>
  5400. </div>
  5401. <hr>
  5402. </div>
  5403.  
  5404. <h4 data-i18n="settings:translation.advanced.name"></h4>
  5405. <div class='OJBetter_setting_list'>
  5406. <label for="comment_translation_mode" style="display: flex;" data-i18n="settings:translation.advanced.mode.name"></label>
  5407. <div class="help_tip">
  5408. ${helpCircleHTML}
  5409. <div class="tip_text" data-i18n="[html]settings:translation.advanced.mode.helpText"></div>
  5410. </div>
  5411. <select id="comment_translation_mode" name="comment_translation_mode">
  5412. <option value="0" data-i18n="settings:translation.advanced.mode.options.0"></option>
  5413. <option value="1" data-i18n="settings:translation.advanced.mode.options.1"></option>
  5414. <option value="2" data-i18n="settings:translation.advanced.mode.options.2"></option>
  5415. </select>
  5416. </div>
  5417. <div class='OJBetter_setting_list'>
  5418. <label for="memoryTranslateHistory" data-i18n="settings:translation.advanced.memory.name"></label>
  5419. <div class="help_tip">
  5420. ${helpCircleHTML}
  5421. <div class="tip_text" data-i18n="[html]settings:translation.advanced.memory.helpText"></div>
  5422. </div>
  5423. <input type="checkbox" id="memoryTranslateHistory" name="memoryTranslateHistory">
  5424. </div>
  5425. <div class='OJBetter_setting_list'>
  5426. <label for="translation_retransAction" style="display: flex;" data-i18n="settings:translation.advanced.retrans.name"></label>
  5427. <div class="help_tip">
  5428. ${helpCircleHTML}
  5429. <div class="tip_text" data-i18n="[html]settings:translation.advanced.retrans.helpText"></div>
  5430. </div>
  5431. <select id="translation_retransAction" name="translation_retransAction">
  5432. <option value=0 data-i18n="settings:translation.advanced.retrans.options.0"></option>
  5433. <option value=1 data-i18n="settings:translation.advanced.retrans.options.1"></option>
  5434. </select>
  5435. </div>
  5436. <div class='OJBetter_setting_list'>
  5437. <label for='transWaitTime'>
  5438. <div style="display: flex;align-items: center;" data-i18n="settings:translation.advanced.transWaitTime.name"></div>
  5439. </label>
  5440. <div class="help_tip">
  5441. ${helpCircleHTML}
  5442. <div class="tip_text" data-i18n="[html]settings:translation.advanced.transWaitTime.helpText"></div>
  5443. </div>
  5444. <input type='number' id='transWaitTime' class='no_default' require=true data-i18n="[placeholder]settings:translation.advanced.transWaitTime.placeholder">
  5445. <span data-i18n="settings:translation.advanced.transWaitTime.end"></span>
  5446. </div>
  5447. <div class='OJBetter_setting_list'>
  5448. <label for="translation_replaceSymbol" style="display: flex;" data-i18n="settings:translation.advanced.replaceSymbol.name"></label>
  5449. <div class="help_tip">
  5450. ${helpCircleHTML}
  5451. <div class="tip_text" data-i18n="[html]settings:translation.advanced.replaceSymbol.helpText"></div>
  5452. </div>
  5453. <select id="translation_replaceSymbol" name="translation_replaceSymbol">
  5454. <option value=2 data-i18n="settings:translation.advanced.replaceSymbol.options.2"></option>
  5455. <option value=1 data-i18n="settings:translation.advanced.replaceSymbol.options.1"></option>
  5456. <option value=3 data-i18n="settings:translation.advanced.replaceSymbol.options.3"></option>
  5457. </select>
  5458. </div>
  5459. <div class='OJBetter_setting_list'>
  5460. <label for="filterTextWithoutEmphasis" data-i18n="settings:translation.advanced.filterTextWithoutEmphasis.name"></label>
  5461. <div class="help_tip">
  5462. ${helpCircleHTML}
  5463. <div class="tip_text" data-i18n="[html]settings:translation.advanced.filterTextWithoutEmphasis.helpText"></div>
  5464. </div>
  5465. <input type="checkbox" id="filterTextWithoutEmphasis" name="filterTextWithoutEmphasis">
  5466. </div>
  5467. </div>
  5468. `;
  5469.  
  5470. const clist_rating_settings_HTML = `
  5471. <div id="clist_rating-settings" class="settings-page">
  5472. <h3 data-i18n="settings:clist.title"></h3>
  5473. <hr>
  5474. <h4 data-i18n="settings:clist.basics.name"></h4>
  5475. <div class='OJBetter_setting_list alert_tip'>
  5476. <div>
  5477. <p data-i18n="[html]settings:clist.basics.notice"></p>
  5478. </div>
  5479. </div>
  5480. <div class='OJBetter_setting_list'>
  5481. <label for='clist_Authorization'>
  5482. <div style="display: flex;align-items: center;">
  5483. <span class="input_label" data-i18n="settings:clist.basics.key.title"></span>
  5484. </div>
  5485. </label>
  5486. <div class="help_tip">
  5487. ${helpCircleHTML}
  5488. <div class="tip_text" data-i18n="[html]settings:clist.basics.key.helpText"></div>
  5489. </div>
  5490. <input type='text' id='clist_Authorization' class='no_default' required="true"
  5491. data-i18n="[placeholder]settings:clist.basics.key.keyPlaceholder">
  5492. </div>
  5493. <hr>
  5494. <h4 data-i18n="settings:clist.displayRating.title"></h4>
  5495. <div class='OJBetter_setting_list'>
  5496. <label for="showClistRating_contest"><span data-i18n="settings:clist.displayRating.contest.name"></span></label>
  5497. <input type="checkbox" id="showClistRating_contest" name="showClistRating_contest">
  5498. </div>
  5499. <div class='OJBetter_setting_list'>
  5500. <label for="showClistRating_problem"><span data-i18n="settings:clist.displayRating.problem.name"></span></label>
  5501. <input type="checkbox" id="showClistRating_problem" name="showClistRating_problem">
  5502. </div>
  5503. <div class='OJBetter_setting_list' style='display:none;'>
  5504. <label for="showClistRating_problemset"><span data-i18n="settings:clist.displayRating.problemset.name"></span></label>
  5505. <input type="checkbox" id="showClistRating_problemset" name="showClistRating_problemset">
  5506. </div>
  5507. <hr>
  5508. <div class='OJBetter_setting_list'>
  5509. <label for="RatingHidden"><span data-i18n="settings:clist.spoilerProtection.title"></span></label>
  5510. <div class="help_tip">
  5511. ${helpCircleHTML}
  5512. <div class="tip_text" data-i18n="[html]settings:clist.spoilerProtection.helpText"></div>
  5513. </div>
  5514. <input type="checkbox" id="RatingHidden" name="RatingHidden">
  5515. </div>
  5516. </div>
  5517. `;
  5518.  
  5519. const code_editor_settings_HTML = `
  5520. <div id="code_editor-settings" class="settings-page">
  5521. <h3 data-i18n="settings:codeEditor.title"></h3>
  5522. <hr>
  5523. <h4 data-i18n="settings:codeEditor.basics"></h4>
  5524. <div class='OJBetter_setting_list'>
  5525. <label for="problemPageCodeEditor"><span
  5526. data-i18n="settings:codeEditor.problemPageCodeEditor.label"></span></label>
  5527. <div class="help_tip">
  5528. ${helpCircleHTML}
  5529. <div class="tip_text" data-i18n="settings:codeEditor.problemPageCodeEditor.helpText"></div>
  5530. </div>
  5531. <input type="checkbox" id="problemPageCodeEditor" name="problemPageCodeEditor">
  5532. </div>
  5533. <div class='OJBetter_setting_list'>
  5534. <label for="beautifyPreBlocks"><span
  5535. data-i18n="settings:codeEditor.beautifyPreBlocks.label"></span></label>
  5536. <div class="help_tip">
  5537. ${helpCircleHTML}
  5538. <div class="tip_text" data-i18n="settings:codeEditor.beautifyPreBlocks.helpText"></div>
  5539. </div>
  5540. <input type="checkbox" id="beautifyPreBlocks" name="beautifyPreBlocks">
  5541. </div>
  5542. <hr>
  5543. <h4 data-i18n="settings:codeEditor.preferences.title"></h4>
  5544. <div class='OJBetter_setting_list'>
  5545. <label for="isCodeSubmitConfirm"><span
  5546. data-i18n="settings:codeEditor.preferences.isCodeSubmitConfirm.label"></span></label>
  5547. <div class="help_tip">
  5548. ${helpCircleHTML}
  5549. <div class="tip_text" data-i18n="settings:codeEditor.preferences.isCodeSubmitConfirm.helpText"></div>
  5550. </div>
  5551. <input type="checkbox" id="isCodeSubmitConfirm" name="isCodeSubmitConfirm">
  5552. </div>
  5553. <div class='OJBetter_setting_list'>
  5554. <label for="alwaysConsumeMouseWheel"><span
  5555. data-i18n="settings:codeEditor.preferences.alwaysConsumeMouseWheel.label"></span></label>
  5556. <div class="help_tip">
  5557. ${helpCircleHTML}
  5558. <div class="tip_text" data-i18n="settings:codeEditor.preferences.alwaysConsumeMouseWheel.helpText"></div>
  5559. </div>
  5560. <input type="checkbox" id="alwaysConsumeMouseWheel" name="alwaysConsumeMouseWheel">
  5561. </div>
  5562. <div class='OJBetter_setting_list'>
  5563. <label for="submitButtonPosition"><span
  5564. data-i18n="settings:codeEditor.preferences.submitButtonPosition.label"></span></label>
  5565. <div class="help_tip">
  5566. ${helpCircleHTML}
  5567. <div class="tip_text" data-i18n="settings:codeEditor.preferences.submitButtonPosition.helpText"></div>
  5568. </div>
  5569. <select id="submitButtonPosition" name="submitButtonPosition">
  5570. <option value="bottom" data-i18n="settings:codeEditor.preferences.submitButtonPosition.options.bottom"></option>
  5571. <option value="top" data-i18n="settings:codeEditor.preferences.submitButtonPosition.options.top"></option>
  5572. </select>
  5573. </div>
  5574. <hr>
  5575. <h4 data-i18n="settings:codeEditor.onlineCodeExecution.title"></h4>
  5576. <label>
  5577. <input type='radio' name='compiler' value='official'>
  5578. <span class='OJBetter_setting_menu_label_text'
  5579. data-i18n="settings:codeEditor.onlineCodeExecution.compilerOptions.codeforces"></span>
  5580. </label>
  5581. <label>
  5582. <input type='radio' name='compiler' value='wandbox'>
  5583. <span class='OJBetter_setting_menu_label_text'
  5584. data-i18n="settings:codeEditor.onlineCodeExecution.compilerOptions.wandbox"></span>
  5585. </label>
  5586. <label>
  5587. <input type='radio' name='compiler' value='rextester'>
  5588. <span class='OJBetter_setting_menu_label_text'
  5589. data-i18n="settings:codeEditor.onlineCodeExecution.compilerOptions.rextester"></span>
  5590. </label>
  5591. <hr>
  5592. <h4 data-i18n="settings:codeEditor.lsp.title"></h4>
  5593. <div class='OJBetter_setting_list'>
  5594. <label for="useLSP"><span data-i18n="settings:codeEditor.lsp.useLSP.label"></span></label>
  5595. <div class="help_tip">
  5596. ${helpCircleHTML}
  5597. <div class="tip_text" data-i18n="[html]settings:codeEditor.lsp.useLSP.helpText"></div>
  5598. </div>
  5599. <input type="checkbox" id="useLSP" name="useLSP">
  5600. </div>
  5601. <div class='OJBetter_setting_list'>
  5602. <label for='OJBetter_Bridge_WorkUri'>
  5603. <div style="display: flex;align-items: center;">
  5604. <span class="input_label" data-i18n="settings:codeEditor.lsp.OJBetter_Bridge_WorkUri.label"></span>
  5605. </div>
  5606. </label>
  5607. <div class="help_tip">
  5608. ${helpCircleHTML}
  5609. <div class="tip_text" data-i18n="[html]settings:codeEditor.lsp.OJBetter_Bridge_WorkUri.helpText"></div>
  5610. </div>
  5611. <input type='text' id='OJBetter_Bridge_WorkUri' class='no_default'
  5612. require=true data-i18n="[placeholder]settings:codeEditor.lsp.OJBetter_Bridge_WorkUri.placeholder">
  5613. </div>
  5614. <div class='OJBetter_setting_list'>
  5615. <label for='OJBetter_Bridge_SocketUrl'>
  5616. <div style="display: flex;align-items: center;">
  5617. <span class="input_label"
  5618. data-i18n="settings:codeEditor.lsp.OJBetter_Bridge_SocketUrl.label"></span>
  5619. </div>
  5620. </label>
  5621. <div class="help_tip">
  5622. ${helpCircleHTML}
  5623. <div class="tip_text" data-i18n="[html]settings:codeEditor.lsp.OJBetter_Bridge_SocketUrl.helpText"></div>
  5624. </div>
  5625. <input type='text' id='OJBetter_Bridge_SocketUrl' class='no_default'
  5626. require=true data-i18n="[placeholder]settings:codeEditor.lsp.OJBetter_Bridge_SocketUrl.placeholder">
  5627. </div>
  5628. <hr>
  5629. <h4 data-i18n="settings:codeEditor.staticCompletionEnhancement.title"></h4>
  5630. <div class='OJBetter_setting_list'>
  5631. <label for="cppCodeTemplateComplete"><span
  5632. data-i18n="settings:codeEditor.staticCompletionEnhancement.cppCodeTemplateComplete.label"></span></label>
  5633. <div class="help_tip">
  5634. ${helpCircleHTML}
  5635. <div class="tip_text" data-i18n="[html]settings:codeEditor.staticCompletionEnhancement.cppCodeTemplateComplete.helpText"></div>
  5636. </div>
  5637. <input type="checkbox" id="cppCodeTemplateComplete" name="cppCodeTemplateComplete">
  5638. </div>
  5639. <hr>
  5640. <h5 data-i18n="settings:codeEditor.staticCompletionEnhancement.customization"></h5>
  5641. <div class='OJBetter_setting_list alert_warn'>
  5642. <div>
  5643. <p data-i18n="settings:codeEditor.staticCompletionEnhancement.performanceWarning"></p>
  5644. </div>
  5645. </div>
  5646. <div id="Complet_config" class="config"></div>
  5647. </div>
  5648. `;
  5649.  
  5650. const preference_settings_HTML = `
  5651. <div id="preference-settings" class="settings-page">
  5652. <h3 data-i18n="settings:preference.title"></h3>
  5653. <hr>
  5654. <div class='OJBetter_setting_list'>
  5655. <label for="showLoading" data-i18n="settings:preference.loadingInfo.label"></label>
  5656. <div class="help_tip">
  5657. ${helpCircleHTML}
  5658. <div class="tip_text" data-i18n="[html]settings:preference.loadingInfo.helpText" data-i18n-options='{ "scriptName": "${OJBetter.state.name}" }'></div>
  5659. </div>
  5660. <input type="checkbox" id="showLoading" name="showLoading">
  5661. </div>
  5662. <div class='OJBetter_setting_list'>
  5663. <label for="hoverTargetAreaDisplay" data-i18n="settings:preference.targetArea.label"></label>
  5664. <div class="help_tip">
  5665. ${helpCircleHTML}
  5666. <div class="tip_text" data-i18n="[html]settings:preference.targetArea.helpText"></div>
  5667. </div>
  5668. <input type="checkbox" id="hoverTargetAreaDisplay" name="hoverTargetAreaDisplay">
  5669. </div>
  5670. <div class='OJBetter_setting_list'>
  5671. <label for='iconButtonSize'>
  5672. <div style="display: flex;align-items: center;" data-i18n="settings:preference.iconButtonSize.title"></div>
  5673. </label>
  5674. <div class="help_tip">
  5675. ${helpCircleHTML}
  5676. <div class="tip_text" data-i18n="[html]settings:preference.iconButtonSize.helpText"></div>
  5677. </div>
  5678. <input type='number' id='iconButtonSize' class='no_default' require=true data-i18n="[placeholder]settings:preference.iconButtonSize.placeholder">
  5679. <span>px</span>
  5680. </div>
  5681. </div>
  5682. `;
  5683.  
  5684. const dev_settings_HTML = `
  5685. <div id="dev-settings" class="settings-page">
  5686. <h3 data-i18n="settings:dev.title"></h3>
  5687. <hr>
  5688. <div class='OJBetter_setting_list alert_danger'>
  5689. <div>
  5690. <p data-i18n="[html]settings:dev.notice"></p>
  5691. </div>
  5692. </div>
  5693. <hr>
  5694. <h5 data-i18n="settings:dev.load.title"></h5>
  5695. <div class='OJBetter_setting_list'>
  5696. <label for="notWaiteLoaded"><span data-i18n="settings:dev.load.notWaiteLoaded.label"></span></label>
  5697. <div class="help_tip">
  5698. ${helpCircleHTML}
  5699. <div class="tip_text" data-i18n="[html]settings:dev.load.notWaiteLoaded.helpText"></div>
  5700. </div>
  5701. <input type="checkbox" id="notWaiteLoaded" name="notWaiteLoaded">
  5702. </div>
  5703. <hr>
  5704. <h5 data-i18n="settings:dev.l10n.title"></h5>
  5705. <div class='OJBetter_setting_list'>
  5706. <label><span data-i18n="settings:dev.l10n.refreshScrpitCache.label"></span></label>
  5707. <div class="help_tip">
  5708. ${helpCircleHTML}
  5709. <div class="tip_text" data-i18n="[html]settings:dev.l10n.refreshScrpitCache.helpText"></div>
  5710. </div>
  5711. <button type="button" id="l10n_refreshScrpitCacheButton" name="l10n_refreshScrpitCacheButton" data-i18n="settings:dev.l10n.refreshScrpitCache.button"></button>
  5712. </div>
  5713. <hr>
  5714. <h5 data-i18n="settings:dev.indexedDB.title"></h5>
  5715. <div class='OJBetter_setting_list'>
  5716. <label><span data-i18n="settings:dev.indexedDB.clear.label"></span></label>
  5717. <div class="help_tip">
  5718. ${helpCircleHTML}
  5719. <div class="tip_text" data-i18n="[html]settings:dev.indexedDB.clear.helpText"></div>
  5720. </div>
  5721. <button type="button" id="indexedDB_clearButton" name="indexedDB_clearButton" data-i18n="settings:dev.indexedDB.clear.button"></button>
  5722. </div>
  5723. <div class='OJBetter_setting_list'>
  5724. <label><span data-i18n="settings:dev.indexedDB.inputOrExport.label"></span></label>
  5725. <div class="help_tip">
  5726. ${helpCircleHTML}
  5727. <div class="tip_text" data-i18n="[html]settings:dev.indexedDB.inputOrExport.helpText"></div>
  5728. </div>
  5729. <button type="button" id="indexedDB_exportButton" name="indexedDB_exportButton" data-i18n="settings:dev.indexedDB.inputOrExport.export"></button>
  5730. <button type="button" id="indexedDB_importButton" name="indexedDB_importButton" data-i18n="settings:dev.indexedDB.inputOrExport.import"></button>
  5731. </div>
  5732. <hr>
  5733. <h5 data-i18n="settings:dev.configuration.title"></h5>
  5734. <div class='OJBetter_setting_list'>
  5735. <label><span data-i18n="settings:dev.configuration.clear.label"></span></label>
  5736. <div class="help_tip">
  5737. ${helpCircleHTML}
  5738. <div class="tip_text" data-i18n="[html]settings:dev.configuration.clear.helpText"></div>
  5739. </div>
  5740. <button type="button" id="configuration_clearButton" name="configuration_clearButton" data-i18n="settings:dev.configuration.clear.button"></button>
  5741. </div>
  5742. <div class='OJBetter_setting_list'>
  5743. <label><span data-i18n="settings:dev.configuration.inputOrExport.label"></span></label>
  5744. <div class="help_tip">
  5745. ${helpCircleHTML}
  5746. <div class="tip_text" data-i18n="[html]settings:dev.configuration.inputOrExport.helpText"></div>
  5747. </div>
  5748. <button type="button" id="configuration_exportButton" name="configuration_exportButton" data-i18n="settings:dev.configuration.inputOrExport.export"></button>
  5749. <button type="button" id="configuration_importButton" name="configuration_importButton" data-i18n="settings:dev.configuration.inputOrExport.import"></button>
  5750. </div>
  5751. </div>
  5752. `;
  5753.  
  5754. const about_settings_HTML = `
  5755. <div id="about-settings" class="settings-page">
  5756. <h3 data-i18n="settings:about.title"></h3>
  5757. <hr>
  5758. <div class='versionInfo'>
  5759. <p>${OJBetter.state.name}</p>
  5760. <p><span data-i18n="settings:about.version"></span><span id="nowVersion">${OJBetter.state.version}</span></p>
  5761. <p> @北极小狐 <a target="_blank" href="https://github.com/beijixiaohu/OJBetter">Github</a>
  5762. <a target="_blank" href="https://greatest.deepsurf.us/zh-CN/scripts/465777">GreasyFork</a></p>
  5763. </div>
  5764. <hr>
  5765. <h5 data-i18n="settings:about.update.title"></h5>
  5766. <div id="thanksforDevChannelNotice" class='OJBetter_setting_list alert_info'>
  5767. <div data-i18n="[html]settings:about.update.thanksforDevChannelNotice"} data-i18n-options='{ "scriptName": "${OJBetter.state.name}" }' ></div>
  5768. </div>
  5769. <div class='OJBetter_setting_list'>
  5770. <label for="updateChannel"><span data-i18n="settings:about.update.channel.label"></span></label>
  5771. <div class="help_tip">
  5772. ${helpCircleHTML}
  5773. <div class="tip_text" data-i18n="[html]settings:about.update.channel.helpText"></div>
  5774. </div>
  5775. <select id="updateChannel" name="updateChannel">
  5776. <option value="release" data-i18n="settings:about.update.channel.options.release"></option>
  5777. <option value="dev" data-i18n="settings:about.update.channel.options.dev"></option>
  5778. </select>
  5779. </div>
  5780. <div class='OJBetter_setting_list'>
  5781. <label for="updateSource"><span data-i18n="settings:about.update.source.label"></span></label>
  5782. <div class="help_tip">
  5783. ${helpCircleHTML}
  5784. <div class="tip_text" data-i18n="[html]settings:about.update.source.helpText"></div>
  5785. </div>
  5786. <select id="updateSource" name="updateSource">
  5787. <option value="greasyfork" data-i18n="settings:about.update.source.options.greasyfork"></option>
  5788. <option value="github" data-i18n="settings:about.update.source.options.github"></option>
  5789. <option value="aliyunoss" data-i18n="settings:about.update.source.options.aliyunoss"></option>
  5790. </select>
  5791. </div>
  5792. </div>
  5793. `;
  5794.  
  5795. const OJBetter_setting_content_HTML = `
  5796. <div class="OJBetter_setting_content">
  5797. ${basic_settings_HTML}
  5798. ${l10n_settings_HTML}
  5799. ${translation_settings_HTML}
  5800. ${clist_rating_settings_HTML}
  5801. ${code_editor_settings_HTML}
  5802. ${preference_settings_HTML}
  5803. ${dev_settings_HTML}
  5804. ${about_settings_HTML}
  5805. </div>
  5806. `;
  5807.  
  5808. // 设置界面HTML
  5809. const OJBetterSettingMenu_HTML = `
  5810. <dialog class='OJBetter_setting_menu' id='OJBetter_setting_menu'>
  5811. <div class="tool-box">
  5812. <button class='ojb_btn ojb_btn_popover top btn-close'>
  5813. <i class="iconfont">&#xe614;</i>
  5814. </button>
  5815. </div>
  5816. <div class="OJBetter_setting_container">
  5817. ${OJBetter_setting_sidebar_HTML}
  5818. ${OJBetter_setting_content_HTML}
  5819. </div>
  5820. </dialog>
  5821. `;
  5822.  
  5823. const apiCustomConfigHTML = (prefix) => {
  5824. return `
  5825. <div class="OJBetter_setting_list">
  5826. <label for='${prefix}_header'>
  5827. <div style="display: flex;align-items: center;">
  5828. <span class="input_label" data-i18n="config:common.advanced.header.label"></span>
  5829. <div class="help_tip">
  5830. ${helpCircleHTML}
  5831. <div class="tip_text" data-i18n="[html]config:common.advanced.header.tipText"></div>
  5832. </div>
  5833. </div>
  5834. </label>
  5835. <textarea id="${prefix}_header" placeholder='' require = false data-i18n="[placeholder]config:common.advanced.header.placeholder"></textarea>
  5836. </div>
  5837. <div class="OJBetter_setting_list">
  5838. <label for='${prefix}_data'>
  5839. <div style="display: flex;align-items: center;">
  5840. <span class="input_label" data-i18n="config:common.advanced.data.label"></span>
  5841. <div class="help_tip">
  5842. ${helpCircleHTML}
  5843. <div class="tip_text" data-i18n="[html]config:common.advanced.data.tipText"></div>
  5844. </div>
  5845. </div>
  5846. </label>
  5847. <textarea id="${prefix}_data" placeholder='' require = false data-i18n="[placeholder]config:common.advanced.data.placeholder"></textarea>
  5848. </div>
  5849. `;
  5850. };
  5851.  
  5852. const apiQuotaConfigHTML = (prefix) => {
  5853. return `
  5854. <div class="OJBetter_setting_list">
  5855. <label for='${prefix}_quota_url'>
  5856. <div style="display: flex;align-items: center;">
  5857. <span class="input_label" data-i18n="config:common.quota.url.label"></span>
  5858. <div class="help_tip">
  5859. ${helpCircleHTML}
  5860. <div class="tip_text" data-i18n="[html]config:common.quota.url.tipText"></div>
  5861. </div>
  5862. </div>
  5863. </label>
  5864. <input type='text' id='${prefix}_quota_url' class='no_default' placeholder='' require = true data-i18n="[placeholder]config:common.quota.url.placeholder">
  5865. </div>
  5866. <div class="OJBetter_setting_list">
  5867. <label for="${prefix}_quota_method" style="display: flex;" data-i18n="config:common.quota.method.label"></label>
  5868. <div class="help_tip">
  5869. ${helpCircleHTML}
  5870. <div class="tip_text" data-i18n="[html]config:common.quota.method.tipText"></div>
  5871. </div>
  5872. <select id="${prefix}_quota_method" name="${prefix}_quota_method">
  5873. <option value="get">GET</option>
  5874. <option value="post">POST</option>
  5875. </select>
  5876. </div>
  5877. <div class="OJBetter_setting_list">
  5878. <label for='${prefix}_quota_header'>
  5879. <div style="display: flex;align-items: center;">
  5880. <span class="input_label" data-i18n="config:common.quota.header.label"></span>
  5881. <div class="help_tip">
  5882. ${helpCircleHTML}
  5883. <div class="tip_text" data-i18n="[html]config:common.quota.header.tipText"></div>
  5884. </div>
  5885. </div>
  5886. </label>
  5887. <textarea id="${prefix}_quota_header" placeholder='' require = false data-i18n="[placeholder]config:common.quota.header.placeholder"></textarea>
  5888. </div>
  5889. <div class="OJBetter_setting_list">
  5890. <label for='${prefix}_quota_data'>
  5891. <div style="display: flex;align-items: center;">
  5892. <span class="input_label" data-i18n="config:common.quota.data.label"></span>
  5893. <div class="help_tip">
  5894. ${helpCircleHTML}
  5895. <div class="tip_text" data-i18n="[html]config:common.quota.data.tipText"></div>
  5896. </div>
  5897. </div>
  5898. </label>
  5899. <textarea id="${prefix}_quota_data" placeholder='' require = false data-i18n="[placeholder]config:common.quota.data.placeholder"></textarea>
  5900. </div>
  5901. <div class="OJBetter_setting_list">
  5902. <div style="display: flex;align-items: center;">
  5903. <span class="input_label" data-i18n="config:common.quota.surplus.label"></span>
  5904. <div class="help_tip">
  5905. ${helpCircleHTML}
  5906. <div class="tip_text" data-i18n="[html]config:common.quota.surplus.tipText"></div>
  5907. </div>
  5908. </div>
  5909. </label>
  5910. <input type='text' id='${prefix}_quota_surplus' class='no_default' placeholder='' require = true data-i18n="[placeholder]config:common.quota.surplus.placeholder">
  5911. </div>
  5912. `;
  5913. }
  5914.  
  5915. const deeplConfigEditHTML = `
  5916. <dialog class='OJBetter_setting_menu' id='config_edit_menu'>
  5917. <div class='OJBetter_setting_content'>
  5918. <div class="tool-box">
  5919. <button class='ojb_btn ojb_btn_popover top btn-close'>
  5920. <i class="iconfont">&#xe614;</i>
  5921. </button>
  5922. </div>
  5923. <h4 data-i18n="config:deepl.title"></h4>
  5924. <h5 data-i18n="config:deepl.basic.title"></h5>
  5925. <hr>
  5926. <div class="OJBetter_setting_list">
  5927. <label for='name'>
  5928. <span class="input_label" data-i18n="config:deepl.basic.name.label"></span>
  5929. </label>
  5930. <input type='text' id='name' class='no_default' placeholder='' require = true data-i18n="[placeholder]config:deepl.basic.name.placeholder">
  5931. </div>
  5932. <div class='OJBetter_setting_list'>
  5933. <label for="deepl_apiGenre" style="display: flex;" data-i18n="config:deepl.genre.label"></label>
  5934. <div class="help_tip">
  5935. ${helpCircleHTML}
  5936. <div class="tip_text" data-i18n="[html]config:deepl.genre.tipText"></div>
  5937. </div>
  5938. <select id="deepl_apiGenre" name="deepl_apiGenre">
  5939. <option value="api-free">api-free</option>
  5940. <option value="api-pro">api-pro</option>
  5941. <option value="deeplx">deeplx</option>
  5942. </select>
  5943. </div>
  5944. <div class="OJBetter_setting_list">
  5945. <label for='deepl_key'>
  5946. <div style="display: flex;align-items: center;">
  5947. <span class="input_label" data-i18n="config:deepl.basic.key.label"></span>
  5948. <div class="help_tip">
  5949. ${helpCircleHTML}
  5950. <div class="tip_text" data-i18n="[html]config:deepl.basic.key.tipText"></div>
  5951. </div>
  5952. </div>
  5953. </label>
  5954. <input type='text' id='deepl_key' class='no_default' placeholder='' require = true data-i18n="[placeholder]config:deepl.basic.key.placeholder">
  5955. </div>
  5956. <div class="OJBetter_setting_list">
  5957. <label for='deepl_proxy'>
  5958. <div style="display: flex;align-items: center;">
  5959. <span class="input_label" data-i18n="config:deepl.basic.proxy.label">Proxy API:</span>
  5960. <div class="help_tip">
  5961. ${helpCircleHTML}
  5962. <div class="tip_text" data-i18n="[html]config:deepl.basic.proxy.tipText"></div>
  5963. </div>
  5964. </div>
  5965. </label>
  5966. <input type='text' id='deepl_proxy' placeholder='' require = false>
  5967. </div>
  5968. <hr>
  5969. <details>
  5970. <summary data-i18n="config:common.advanced.title"></summary>
  5971. ${apiCustomConfigHTML('deepl')}
  5972. </details>
  5973. <details>
  5974. <summary data-i18n="config:common.quota.title"></summary>
  5975. ${apiQuotaConfigHTML('deepl')}
  5976. </details>
  5977. <button id='tempConfig_save' data-i18n="common:save"></button>
  5978. </div>
  5979. </dialog>
  5980. `;
  5981.  
  5982. const chatgptConfigEditHTML = `
  5983. <dialog class='OJBetter_setting_menu' id='config_edit_menu'>
  5984. <div class='OJBetter_setting_content'>
  5985. <div class="tool-box">
  5986. <button class='ojb_btn ojb_btn_popover top btn-close'>
  5987. <i class="iconfont">&#xe614;</i>
  5988. </button>
  5989. </div>
  5990. <h4 data-i18n="config:chatgpt.title"></h4>
  5991. <h5 data-i18n="config:chatgpt.basic.title"></h5>
  5992. <hr>
  5993. <div class="OJBetter_setting_list">
  5994. <label for='name'>
  5995. <span class="input_label" data-i18n="config:chatgpt.basic.name.label"></span>
  5996. </label>
  5997. <input type='text' id='name' class='no_default' placeholder='' require = true data-i18n="[placeholder]config:chatgpt.basic.name.placeholder">
  5998. </div>
  5999. <div class="OJBetter_setting_list">
  6000. <label for='chatgpt_model'>
  6001. <div style="display: flex;align-items: center;">
  6002. <span class="input_label" data-i18n="[html]config:chatgpt.basic.model.label"></span>
  6003. <div class="help_tip">
  6004. ${helpCircleHTML}
  6005. <div class="tip_text" data-i18n="[html]config:chatgpt.basic.model.tipText"></div>
  6006. </div>
  6007. </div>
  6008. </label>
  6009. <input type='text' id='chatgpt_model' placeholder='gpt-3.5-turbo' require = false>
  6010. </div>
  6011. <div class="OJBetter_setting_list">
  6012. <label for='chatgpt_key'>
  6013. <div style="display: flex;align-items: center;">
  6014. <span class="input_label" data-i18n="config:chatgpt.basic.key.label"></span>
  6015. <div class="help_tip">
  6016. ${helpCircleHTML}
  6017. <div class="tip_text" data-i18n="[html]config:chatgpt.basic.key.tipText"></div>
  6018. </div>
  6019. </div>
  6020. </label>
  6021. <input type='text' id='chatgpt_key' class='no_default' placeholder='' require = true data-i18n="[placeholder]config:chatgpt.basic.key.placeholder">
  6022. </div>
  6023. <div class="OJBetter_setting_list">
  6024. <label for='chatgpt_proxy'>
  6025. <div style="display: flex;align-items: center;">
  6026. <span class="input_label" data-i18n="config:chatgpt.basic.proxy.label">Proxy API:</span>
  6027. <div class="help_tip">
  6028. ${helpCircleHTML}
  6029. <div class="tip_text" data-i18n="[html]config:chatgpt.basic.proxy.tipText"></div>
  6030. </div>
  6031. </div>
  6032. </label>
  6033. <input type='text' id='chatgpt_proxy' placeholder='https://api.openai.com/v1/chat/completions' require = false>
  6034. </div>
  6035. <hr>
  6036. <details>
  6037. <summary data-i18n="config:common.advanced.title"></summary>
  6038. ${apiCustomConfigHTML('chatgpt')}
  6039. </details>
  6040. <details>
  6041. <summary data-i18n="config:common.quota.title"></summary>
  6042. ${apiQuotaConfigHTML('chatgpt')}
  6043. </details>
  6044. <button id='tempConfig_save' data-i18n="common:save"></button>
  6045. </div>
  6046. </dialog>
  6047. `;
  6048.  
  6049. const CompletConfigEditHTML = `
  6050. <dialog class='OJBetter_setting_menu' id='config_edit_menu'>
  6051. <div class='OJBetter_setting_content'>
  6052. <div class="tool-box">
  6053. <button class='ojb_btn ojb_btn_popover top btn-close'>
  6054. <i class="iconfont">&#xe614;</i>
  6055. </button>
  6056. </div>
  6057. <h4 data-i18n="config:complet.title"></h4>
  6058. <hr>
  6059. <div class="OJBetter_setting_list">
  6060. <label for='name'>
  6061. <span class="input_label" data-i18n="config:complet.name.label"></span>
  6062. </label>
  6063. <input type='text' id='name' class='no_default' placeholder='' require = true data-i18n="[placeholder]config:complet.name.placeholder">
  6064. </div>
  6065. <div class='OJBetter_setting_list'>
  6066. <label for="complet_isChoose"><span id="loaded_span" data-i18n="config:complet.choose.label"></span></label>
  6067. <input type="checkbox" id="complet_isChoose" name="complet_isChoose" require = false>
  6068. </div>
  6069. <div class='OJBetter_setting_list'>
  6070. <label for="complet_genre" style="display: flex;" data-i18n="config:complet.genre.label"></label>
  6071. <div class="help_tip">
  6072. ${helpCircleHTML}
  6073. <div class="tip_text" data-i18n="[html]config:complet.genre.tipText"></div>
  6074. </div>
  6075. <select id="complet_genre" name="complet_genre">
  6076. <option value="monaco">monaco</option>
  6077. <option value="ace">ace</option>
  6078. </select>
  6079. </div>
  6080. <div class='OJBetter_setting_list'>
  6081. <label for="complet_language" style="display: flex;" data-i18n="config:complet.language.label"></label>
  6082. <select id="complet_language" name="complet_language">
  6083. <option value="cpp">cpp</option>
  6084. <option value="python">python</option>
  6085. <option value="java">java</option>
  6086. <option value="c">c</option>
  6087. </select>
  6088. </div>
  6089. <div class="OJBetter_setting_list">
  6090. <label for='complet_jsonUrl'>
  6091. <div style="display: flex;align-items: center;">
  6092. <span class="input_label">JSON URL:</span>
  6093. <div class="help_tip">
  6094. ${helpCircleHTML}
  6095. <div class="tip_text" data-i18n="[html]config:complet.jsonurl.tipText"></div>
  6096. </div>
  6097. </div>
  6098. </label>
  6099. <div class='OJBetter_setting_list alert_warn' data-i18n="[html]config:complet.jsonurl.alert"></div>
  6100. <input type='text' id='complet_jsonUrl' class='no_default' placeholder='' require = true data-i18n="[placeholder]config:complet.jsonurl.placeholder">
  6101. </div>
  6102. <button id='tempConfig_save' data-i18n="common:save"></button>
  6103. </div>
  6104. </dialog>
  6105. `;
  6106.  
  6107. /**
  6108. * 加载设置按钮面板
  6109. */
  6110. async function initSettingsPanel() {
  6111. /**
  6112. * 添加右上角设置按钮
  6113. * @param {string} location 位置选择器
  6114. * @param {string} method 插入方法
  6115. */
  6116. function insertOJBetterSettingButton(location, method) {
  6117. $(location)[method](`<button class='ojb_btn OJBetter_setting'>
  6118. ${OJBetter.state.name} ${i18next.t('settings', { ns: 'common' })}</button>`);
  6119. }
  6120.  
  6121. /**
  6122. * ============================================
  6123. * 该网站插入设置按钮的位置和方式
  6124. */
  6125. if (OJBetter.typeOfPage.isEnglishLanguage) {
  6126. insertOJBetterSettingButton("#navbar-collapse > ul:nth-child(2) > li:last-child", "after");
  6127. } else {
  6128. if ($('.header-mypage').length > 0) insertOJBetterSettingButton(".header-mypage", "after");
  6129. else insertOJBetterSettingButton("#navbar-collapse > ul:nth-child(2) > li:last-child", "after");
  6130. }
  6131. /**
  6132. * ============================================
  6133. */
  6134.  
  6135. const $settingBtns = $(".OJBetter_setting");
  6136. $settingBtns.click(() => {
  6137. $settingBtns.prop("disabled", true).addClass("open");
  6138.  
  6139. // 设置面板div
  6140. const settingMenu = OJB_safeCreateJQElement(OJBetterSettingMenu_HTML);
  6141. $("body").append(settingMenu);
  6142.  
  6143. elementLocalize(settingMenu); // 加载i18n
  6144. OJB_showModal(settingMenu);
  6145. OJB_addDraggable($('#OJBetter_setting_menu')); // 窗口支持拖拽
  6146.  
  6147. // help帮助悬浮窗位置更新
  6148. $(document).on('mouseenter', '.help-icon', function (event) {
  6149. var menuOffset = $('.OJBetter_setting_menu:last').offset();
  6150. var mouseX = event.pageX - menuOffset.left;
  6151. var mouseY = event.pageY - menuOffset.top;
  6152.  
  6153. $('.tip_text').css({
  6154. 'top': mouseY + 'px',
  6155. 'left': mouseX + 'px'
  6156. });
  6157. });
  6158.  
  6159. // 选项卡切换
  6160. $('.OJBetter_setting_sidebar a').click(function (event) {
  6161. event.preventDefault();
  6162. $('.OJBetter_setting_sidebar a').removeClass('active');
  6163. $('.settings-page').removeClass('active');
  6164. $(this).addClass('active');
  6165. const targetPageId = $(this).attr('href').substring(1);
  6166. $('#' + targetPageId).addClass('active');
  6167. });
  6168.  
  6169. /**
  6170. * 更新单选按钮组的可用状态
  6171. * @param {string} selector 单选按钮组的选择器
  6172. * @param {string} targetLanguage 目标语言
  6173. * @param {Object} translationSupport 翻译支持的语言对应表
  6174. */
  6175. const updateRadioButtonsAvailability = (selector, targetLanguage) => {
  6176. Object.entries(OJBetter.supportList.translationSupport).forEach(([service, languages]) => {
  6177. const radioButton = $(selector).find(`input[value="${service}"]`);
  6178. const isEnabled = languages[targetLanguage];
  6179. $(radioButton).prop('disabled', !isEnabled);
  6180. if (!isEnabled) {
  6181. $(radioButton).prop('checked', false);
  6182. }
  6183. });
  6184. };
  6185.  
  6186. /**
  6187. * 检查下拉框选中项是否有效,若无效则清空
  6188. * @param {string} selector 下拉框的选择器
  6189. */
  6190. const validateSelectOption = (selector) => {
  6191. const selectedValue = $(selector).val();
  6192. if (!selectedValue) {
  6193. $(selector).val('');
  6194. }
  6195. };
  6196.  
  6197. /**
  6198. * 更新翻译目标语言下拉框的可用状态
  6199. * @param {string} selector 下拉框的选择器
  6200. * @param {string} targetLanguage 目标语言
  6201. * @param {Object} translationSupport 翻译支持的语言对应表
  6202. */
  6203. const updateSelectOptionsAvailability = (selector, targetLanguage) => {
  6204. $(selector).children('option').each(function () {
  6205. const optionValue = $(this).val();
  6206. const isEnabled = OJBetter.supportList.translationSupport[optionValue] ? OJBetter.supportList.translationSupport[optionValue][targetLanguage] : true;
  6207. $(this).prop('disabled', !isEnabled);
  6208. });
  6209. validateSelectOption(selector);
  6210. };
  6211.  
  6212. /**
  6213. * 更新翻译服务复选框的可用状态
  6214. * @param {string} selector 复选框的选择器
  6215. * @param {string} targetLanguage 目标语言
  6216. * @param {Object} translationSupport 翻译支持的语言对应表
  6217. */
  6218. const updateCheckboxesAvailability = (selector, targetLanguage) => {
  6219. $(selector).children('input').each(function () {
  6220. const checkboxValue = $(this).val();
  6221. const isEnabled = OJBetter.supportList.translationSupport[checkboxValue][targetLanguage];
  6222. $(this).prop('disabled', !isEnabled);
  6223. if (!isEnabled) {
  6224. $(this).prop('checked', false);
  6225. }
  6226. });
  6227. };
  6228.  
  6229. /**
  6230. * 更新更新源下拉框的可用状态
  6231. * @param {string} selector 下拉框的选择器
  6232. * @param {string} targetLanguage 目标语言
  6233. * @param {Object} translationSupport 翻译支持的语言对应表
  6234. */
  6235. const updateUpdateSourceSelectOptionsAvailability = (selector, updateChannel) => {
  6236. $(selector).children('option').each(function () {
  6237. const optionValue = $(this).val();
  6238. const isEnabled = OJBetter.supportList.updateSourceSupportList[optionValue][updateChannel];
  6239. $(this).prop('disabled', !isEnabled);
  6240. });
  6241. validateSelectOption(selector);
  6242. };
  6243.  
  6244. /**
  6245. * 创建配置结构
  6246. * @param {string} type - 该字段的在表单中的类型
  6247. * @param {string} value - 在配置中的键值
  6248. * @param {boolean} require - 是否是表单的必填项
  6249. * @param {string} [check=""] check - 调用的合法性检查
  6250. */
  6251. function createStructure(type, value, require, check = "") {
  6252. return { type, value, require, check };
  6253. }
  6254.  
  6255. // deepl配置
  6256. const deeplStructure = {
  6257. '#name': createStructure('text', 'name', true),
  6258. '#deepl_apiGenre': createStructure('text', 'apiGenre', true),
  6259. '#deepl_key': createStructure('text', 'key', false),
  6260. '#deepl_proxy': createStructure('text', 'proxy', false),
  6261. '#deepl_header': createStructure('text', '_header', false, 'keyValuePairs'),
  6262. '#deepl_data': createStructure('text', '_data', false, 'keyValuePairs'),
  6263. '#deepl_quota_url': createStructure('text', 'quota_url', false),
  6264. '#deepl_quota_method': createStructure('text', 'quota_method', false),
  6265. '#deepl_quota_header': createStructure('text', 'quota_header', false, 'keyValuePairs'),
  6266. '#deepl_quota_data': createStructure('text', 'quota_data', false, 'keyValuePairs'),
  6267. '#deepl_quota_surplus': createStructure('text', 'quota_surplus', false, 'dotSeparatedPath'),
  6268. };
  6269. let tempConfig_deepl = GM_getValue('deepl_config'); // 获取配置信息
  6270. const configManager_deepl = new ConfigManager('#deepl_config', 'deepl_config_', tempConfig_deepl, deeplStructure, deeplConfigEditHTML);
  6271. configManager_deepl.registerChoiceChange();
  6272.  
  6273. // chatgpt配置
  6274. const chatgptStructure = {
  6275. '#name': createStructure('text', 'name', true),
  6276. '#chatgpt_model': createStructure('text', 'model', false),
  6277. '#chatgpt_key': createStructure('text', 'key', true),
  6278. '#chatgpt_proxy': createStructure('text', 'proxy', false),
  6279. '#chatgpt_header': createStructure('text', '_header', false, 'keyValuePairs'),
  6280. '#chatgpt_data': createStructure('text', '_data', false, 'keyValuePairs'),
  6281. '#chatgpt_quota_url': createStructure('text', 'quota_url', false),
  6282. '#chatgpt_quota_header': createStructure('text', 'quota_header', false, 'keyValuePairs'),
  6283. '#chatgpt_quota_data': createStructure('text', 'quota_data', false, 'keyValuePairs'),
  6284. '#chatgpt_quota_surplus': createStructure('text', 'quota_surplus', false, 'dotSeparatedPath'),
  6285. '#chatgpt_quota_method': createStructure('text', 'quota_method', false),
  6286. };
  6287. let tempConfig_chatgpt = GM_getValue('chatgpt_config'); // 获取配置信息
  6288. const configManager_chatgpt = new ConfigManager('#chatgpt_config', 'chatgpt_config_', tempConfig_chatgpt, chatgptStructure, chatgptConfigEditHTML);
  6289. configManager_chatgpt.registerChoiceChange();
  6290.  
  6291. // Complet配置
  6292. const CompletStructure = {
  6293. '#name': createStructure('text', 'name', true),
  6294. '#complet_isChoose': createStructure('checkbox', 'isChoose', true),
  6295. '#complet_genre': createStructure('text', 'genre', true),
  6296. '#complet_language': createStructure('text', 'language', true),
  6297. '#complet_jsonUrl': createStructure('text', 'jsonUrl', true)
  6298. };
  6299. let tempConfig_Complet = GM_getValue('Complet_config'); // 获取配置信息
  6300. const configManager_complet = new ConfigManager('#Complet_config', 'complet_config_', tempConfig_Complet, CompletStructure, CompletConfigEditHTML, false);
  6301.  
  6302. // 状态更新
  6303. $("input[name='darkMode'][value='" + OJBetter.basic.darkMode + "']").prop("checked", true);
  6304. $("#showLoading").prop("checked", GM_getValue("showLoading") === true);
  6305. $("#expandFoldingblocks").prop("checked", GM_getValue("expandFoldingblocks") === true);
  6306. $("#renderPerfOpt").prop("checked", GM_getValue("renderPerfOpt") === true);
  6307. $("#commentPaging").prop("checked", GM_getValue("commentPaging") === true);
  6308. $("#standingsRecolor").prop("checked", GM_getValue("standingsRecolor") === true);
  6309. $("#showJumpToLuogu").prop("checked", GM_getValue("showJumpToLuogu") === true);
  6310. $("#showCF2vjudge").prop("checked", GM_getValue("showCF2vjudge") === true);
  6311. $("#hoverTargetAreaDisplay").prop("checked", GM_getValue("hoverTargetAreaDisplay") === true);
  6312. $("#showClistRating_contest").prop("checked", GM_getValue("showClistRating_contest") === true);
  6313. $("#showClistRating_problemset").prop("checked", GM_getValue("showClistRating_problemset") === true);
  6314. $("#showClistRating_problem").prop("checked", GM_getValue("showClistRating_problem") === true);
  6315. $("#RatingHidden").prop("checked", GM_getValue("RatingHidden") === true);
  6316. $('#scriptL10nLanguage').val(GM_getValue("scriptL10nLanguage"));
  6317. $('#localizationLanguage').val(GM_getValue("localizationLanguage"));
  6318. $("input[name='translation'][value='" + OJBetter.translation.choice + "']").prop("checked", true);
  6319. $("input[name='translation']").css("color", "gray");
  6320. $('#deepl_type').val(GM_getValue("deepl_type"));
  6321. $("#deepl_config_config_bar_ul").find(`input[name='deepl_config_config_item'][value='${tempConfig_deepl.choice}']`).prop("checked", true);
  6322. $('#enableEmphasisProtection').prop("checked", GM_getValue("enableEmphasisProtection") === true);
  6323. $('#enableLinkProtection').prop("checked", GM_getValue("enableLinkProtection") === true);
  6324. $("#chatgpt_config_config_bar_ul").find(`input[name='chatgpt_config_config_item'][value='${tempConfig_chatgpt.choice}']`).prop("checked", true);
  6325. $("#openai_isStream").prop("checked", GM_getValue("openai_isStream") === true);
  6326. $('#comment_translation_choice').val(GM_getValue("commentTranslationChoice"));
  6327. $('#iconButtonSize').val(GM_getValue("iconButtonSize"));
  6328. $("#autoTranslation").prop("checked", GM_getValue("autoTranslation") === true);
  6329. $('#shortTextLength').val(GM_getValue("shortTextLength"));
  6330. $("#allowMixTrans").prop("checked", GM_getValue("allowMixTrans") === true);
  6331. $('.OJBetter_checkboxs').find('input[type="checkbox"][name="mixedTranslation"]').each(function () {
  6332. if (OJBetter.translation.auto.mixTrans.servers.indexOf($(this).val()) > -1) {
  6333. $(this).prop('checked', true);
  6334. }
  6335. });
  6336. // 翻译目标语言下拉框
  6337. $('#transTargetLang').change(function () {
  6338. var selectedLang = $(this).val();
  6339. updateRadioButtonsAvailability('#translationServices', selectedLang);
  6340. updateSelectOptionsAvailability('#comment_translation_choice', selectedLang);
  6341. updateCheckboxesAvailability('.OJBetter_checkboxs', selectedLang);
  6342. });
  6343. $('#transTargetLang').val(GM_getValue("transTargetLang"));
  6344. $('#transTargetLang').change();
  6345. //
  6346. $('#comment_translation_mode').val(GM_getValue("commentTranslationMode"));
  6347. $("#memoryTranslateHistory").prop("checked", GM_getValue("memoryTranslateHistory") === true);
  6348. $('#transWaitTime').val(GM_getValue("transWaitTime"));
  6349. $('#translation_replaceSymbol').val(GM_getValue("replaceSymbol"));
  6350. $("#filterTextWithoutEmphasis").prop("checked", GM_getValue("filterTextWithoutEmphasis") === true);
  6351. $('#translation_retransAction').val(GM_getValue("retransAction"));
  6352. $("#clist_Authorization").val(GM_getValue("clist_Authorization"));
  6353. $("#problemPageCodeEditor").prop("checked", GM_getValue("problemPageCodeEditor") === true);
  6354. $("#beautifyPreBlocks").prop("checked", GM_getValue("beautifyPreBlocks") === true);
  6355. $("#isCodeSubmitConfirm").prop("checked", GM_getValue("isCodeSubmitConfirm") === true);
  6356. $("#alwaysConsumeMouseWheel").prop("checked", GM_getValue("alwaysConsumeMouseWheel") === true);
  6357. $("#submitButtonPosition").val(GM_getValue("submitButtonPosition"));
  6358. $("#cppCodeTemplateComplete").prop("checked", GM_getValue("cppCodeTemplateComplete") === true);
  6359. $("#useLSP").prop("checked", GM_getValue("useLSP") === true);
  6360. $("#OJBetter_Bridge_WorkUri").val(GM_getValue("OJBetter_Bridge_WorkUri"));
  6361. $("#OJBetter_Bridge_SocketUrl").val(GM_getValue("OJBetter_Bridge_SocketUrl"));
  6362. $("input[name='compiler'][value='" + OJBetter.monaco.onlineCompilerChoice + "']").prop("checked", true);
  6363. $("input[name='compiler']").css("color", "gray");
  6364. // 调试
  6365. $("#notWaiteLoaded").prop("checked", GM_getValue("notWaiteLoaded") === true);
  6366. $('#l10n_refreshScrpitCacheButton').click(clearI18nextCache);
  6367. $('#indexedDB_clearButton').click(async () => { await clearDatabase(); });
  6368. $('#indexedDB_exportButton').click(async () => { downloadDataAsFile(await exportDatabase(), 'database_export.json') });
  6369. $('#indexedDB_importButton').click(() => { readFileInput(async (fileContent) => { await importDatabase(fileContent); }); });
  6370. $('#configuration_clearButton').click(deleteAllConfigSettings);
  6371. $('#configuration_exportButton').click(() => { downloadDataAsFile(exportSettingsToJSON(), 'configuration_export.json') });
  6372. $('#configuration_importButton').click(() => { readFileInput((fileContent) => { importSettingsFromJSON(fileContent); }) });
  6373. // 关于
  6374. $('#updateChannel').val(GM_getValue("updateChannel"));
  6375. $('#updateSource').val(GM_getValue("updateSource"));
  6376. $('#updateChannel').change(function () {
  6377. var selectedLang = $(this).val();
  6378. updateUpdateSourceSelectOptionsAvailability('#updateSource', selectedLang);
  6379. if (selectedLang == "dev") $('#thanksforDevChannelNotice').show();
  6380. else $('#thanksforDevChannelNotice').hide();
  6381. });
  6382. $('#updateChannel').change();
  6383.  
  6384. // 关闭
  6385. const $settingMenu = $(".OJBetter_setting_menu");
  6386. $settingMenu.on("click", ".btn-close", async () => {
  6387. // 设置的数据
  6388. const settings = {
  6389. darkMode: $("input[name='darkMode']:checked").val(),
  6390. showLoading: $("#showLoading").prop("checked"),
  6391. hoverTargetAreaDisplay: $("#hoverTargetAreaDisplay").prop("checked"),
  6392. expandFoldingblocks: $("#expandFoldingblocks").prop("checked"),
  6393. renderPerfOpt: $("#renderPerfOpt").prop("checked"),
  6394. commentPaging: $("#commentPaging").prop("checked"),
  6395. standingsRecolor: $("#standingsRecolor").prop("checked"),
  6396. showJumpToLuogu: $("#showJumpToLuogu").prop("checked"),
  6397. showCF2vjudge: $("#showCF2vjudge").prop("checked"),
  6398. scriptL10nLanguage: $('#scriptL10nLanguage').val(),
  6399. localizationLanguage: $('#localizationLanguage').val(),
  6400. transTargetLang: $('#transTargetLang').val(),
  6401. translation: $("input[name='translation']:checked").val(),
  6402. deepl_type: $('#deepl_type').val(),
  6403. enableEmphasisProtection: $("#enableEmphasisProtection").prop("checked"),
  6404. enableLinkProtection: $("#enableLinkProtection").prop("checked"),
  6405. openai_isStream: $("#openai_isStream").prop("checked"),
  6406. commentTranslationChoice: $('#comment_translation_choice').val(),
  6407. iconButtonSize: $('#iconButtonSize').val(),
  6408. autoTranslation: $("#autoTranslation").prop("checked"),
  6409. shortTextLength: $('#shortTextLength').val(),
  6410. allowMixTrans: $("#allowMixTrans").prop("checked"),
  6411. mixedTranslation: (() => {
  6412. let mixedTranslation = [];
  6413. $('.OJBetter_checkboxs').find('input[type="checkbox"][name="mixedTranslation"]').each(function () {
  6414. if ($(this).is(":checked")) {
  6415. mixedTranslation.push($(this).val());
  6416. }
  6417. });
  6418. return mixedTranslation;
  6419. })(),
  6420. commentTranslationMode: $('#comment_translation_mode').val(),
  6421. memoryTranslateHistory: $('#memoryTranslateHistory').prop("checked"),
  6422. transWaitTime: $('#transWaitTime').val(),
  6423. replaceSymbol: $('#translation_replaceSymbol').val(),
  6424. filterTextWithoutEmphasis: $('#filterTextWithoutEmphasis').prop("checked"),
  6425. retransAction: $('#translation_retransAction').val(),
  6426. showClistRating_contest: $('#showClistRating_contest').prop("checked"),
  6427. showClistRating_problemset: $('#showClistRating_problemset').prop("checked"),
  6428. showClistRating_problem: $('#showClistRating_problem').prop("checked"),
  6429. RatingHidden: $('#RatingHidden').prop("checked"),
  6430. clist_Authorization: $('#clist_Authorization').val(),
  6431. problemPageCodeEditor: $("#problemPageCodeEditor").prop("checked"),
  6432. beautifyPreBlocks: $("#beautifyPreBlocks").prop("checked"),
  6433. isCodeSubmitConfirm: $("#isCodeSubmitConfirm").prop("checked"),
  6434. alwaysConsumeMouseWheel: $("#alwaysConsumeMouseWheel").prop("checked"),
  6435. submitButtonPosition: $('#submitButtonPosition').val(),
  6436. cppCodeTemplateComplete: $("#cppCodeTemplateComplete").prop("checked"),
  6437. useLSP: $("#useLSP").prop("checked"),
  6438. OJBetter_Bridge_WorkUri: $('#OJBetter_Bridge_WorkUri').val().replace(/\\/g, '/').replace(/\/$/, ''),
  6439. OJBetter_Bridge_SocketUrl: $('#OJBetter_Bridge_SocketUrl').val(),
  6440. onlineCompilerChoice: $("input[name='compiler']:checked").val(),
  6441. notWaiteLoaded: $("#notWaiteLoaded").prop("checked"),
  6442. updateChannel: $('#updateChannel').val(),
  6443. updateSource: $('#updateSource').val()
  6444. };
  6445. // tempConfigs的数据
  6446. const tempConfigs = {
  6447. 'deepl_config': configManager_deepl.getTempConfig(),
  6448. 'chatgpt_config': configManager_chatgpt.getTempConfig(),
  6449. 'Complet_config': configManager_complet.getTempConfig()
  6450. }
  6451.  
  6452. // 判断是否改变
  6453. let changes = {};
  6454. const combinedConfigs = Object.assign({}, settings, tempConfigs); // 合并settings和tempConfigs对象
  6455. for (const [key, value] of Object.entries(combinedConfigs)) {
  6456. const storedValue = GM_getValue(key);
  6457. if (!OJB_deepEquals(value, storedValue)) {
  6458. changes[key] = { oldValue: storedValue, newValue: value };
  6459. }
  6460. }
  6461.  
  6462. // 如果changes对象不为空,则有变化
  6463. if (Object.keys(changes).length > 0) {
  6464. console.log("Changes detected:", changes);
  6465. const shouldSave = await OJB_createDialog(
  6466. i18next.t('saveSetting.title', { ns: 'dialog' }),
  6467. i18next.t('saveSetting.content', { ns: 'dialog' }),
  6468. [
  6469. i18next.t('saveSetting.buttons.0', { ns: 'dialog' }),
  6470. i18next.t('saveSetting.buttons.1', { ns: 'dialog' })
  6471. ]
  6472. ); // 配置改变保存确认
  6473. if (shouldSave) {
  6474. // 数据校验
  6475. // TODO
  6476. if (settings.deepl_type !== 'free') {
  6477. let selectedIndex = $('input[name="deepl_config_config_item"]:checked').length > 0;
  6478. if (!selectedIndex) {
  6479. $('.deepl_config a').removeClass('active');
  6480. $('.settings-page').removeClass('active');
  6481. $('#sidebar-translation-settings').addClass('active');
  6482. $('#translation-settings').addClass('active');
  6483.  
  6484. $('#deepl_config').addClass('missing');
  6485. return;
  6486. } else {
  6487. $('#deepl_config').removeClass('missing');
  6488. }
  6489. }
  6490. if (settings.translation === "openai") {
  6491. let selectedIndex = $('input[name="chatgpt_config_config_item"]:checked').length > 0;
  6492. if (!selectedIndex) {
  6493. $('.chatgpt_config a').removeClass('active');
  6494. $('.settings-page').removeClass('active');
  6495. $('#sidebar-translation-settings').addClass('active');
  6496. $('#translation-settings').addClass('active');
  6497.  
  6498. $('#chatgpt_config').addClass('missing');
  6499. return;
  6500. } else {
  6501. $('#chatgpt_config').removeClass('missing');
  6502. }
  6503. }
  6504. {
  6505. let selectedIndex = $('input[name="translation"]:checked').length > 0;
  6506. if (!selectedIndex) {
  6507. $('.OJBetter_setting_sidebar a').removeClass('active');
  6508. $('.settings-page').removeClass('active');
  6509. $('#sidebar-translation-settings').addClass('active');
  6510. $('#translation-settings').addClass('active');
  6511.  
  6512. $('#translationServices').addClass('missing');
  6513. return;
  6514. } else {
  6515. $('#translationServices').removeClass('missing');
  6516. }
  6517. }
  6518.  
  6519. // 保存数据
  6520. let refreshPage = false; // 是否需要刷新页面
  6521. for (const [key, value] of Object.entries(settings)) {
  6522. if (!refreshPage && !(key == 'translation' || key == 'darkMode' || key == 'commentTranslationChoice')) {
  6523. if (GM_getValue(key) != value) refreshPage = true;
  6524. }
  6525. GM_setValue(key, value);
  6526. }
  6527. for (const [key, value] of Object.entries(tempConfigs)) {
  6528. if (!refreshPage && (JSON.stringify(GM_getValue(key)) != JSON.stringify(value))) refreshPage = true;
  6529. GM_setValue(key, value);
  6530. }
  6531.  
  6532. if (refreshPage) location.reload();
  6533. else {
  6534. // 切换黑暗模式
  6535. if (OJBetter.basic.darkMode != settings.darkMode) {
  6536. OJBetter.basic.darkMode = settings.darkMode;
  6537. // 移除旧的事件监听器
  6538. changeEventListeners.forEach(listener => {
  6539. mediaQueryList.removeEventListener('change', listener);
  6540. });
  6541.  
  6542. if (OJBetter.basic.darkMode == "follow") {
  6543. changeEventListeners.push(handleColorSchemeChange);
  6544. mediaQueryList.addEventListener('change', handleColorSchemeChange);
  6545. $('html').removeAttr('data-theme');
  6546. } else if (OJBetter.basic.darkMode == "dark") {
  6547. $('html').attr('data-theme', 'dark');
  6548. if (OJBetter.monaco.editor) {
  6549. monaco.editor.setTheme('vs-dark');
  6550. }
  6551. } else {
  6552. $('html').attr('data-theme', 'light');
  6553. if (OJBetter.monaco.editor) {
  6554. monaco.editor.setTheme('vs');
  6555. }
  6556. // 移除旧的事件监听器
  6557. const mediaQueryList = window.matchMedia('(prefers-color-scheme: dark)');
  6558. window.matchMedia('(prefers-color-scheme: dark)');
  6559. }
  6560. }
  6561. // 更新配置信息
  6562. OJBetter.translation.choice = settings.translation;
  6563. OJBetter.translation.comment.choice = settings.commentTranslationChoice;
  6564. }
  6565. }
  6566. }
  6567. OJB_closeAndRemoveModal(settingMenu);
  6568. $settingBtns.prop("disabled", false).removeClass("open");
  6569. });
  6570. });
  6571. };
  6572.  
  6573. // html2markdown转换/处理规则
  6574. const turndownService = new TurndownService({ bulletListMarker: '-' });
  6575.  
  6576. // 保留原始
  6577. turndownService.keep(['del']);
  6578.  
  6579. turndownService.addRule('removeByClass', {
  6580. filter: function (node) {
  6581. return node.classList.contains('html2md-panel') ||
  6582. node.classList.contains('div-btn-copy') ||
  6583. node.classList.contains('btn-copy') ||
  6584. node.classList.contains('overlay')
  6585. },
  6586. replacement: function () {
  6587. return '';
  6588. }
  6589. });
  6590.  
  6591. // inline math
  6592. turndownService.addRule('inline-math', {
  6593. filter: function (node, options) {
  6594. return node.tagName.toLowerCase() == "span" && node.className == "katex";
  6595. },
  6596. replacement: function (content, node) {
  6597. var latex = $(node).find('annotation').text();
  6598. latex = latex.replace(/</g, "&lt;").replace(/>/g, "&gt;");
  6599. return "$" + latex + "$";
  6600. }
  6601. });
  6602.  
  6603. // block math
  6604. turndownService.addRule('block-math', {
  6605. filter: function (node, options) {
  6606. return node.tagName.toLowerCase() == "span" && node.className == "katex-display";
  6607. },
  6608. replacement: function (content, node) {
  6609. var latex = $(node).find('annotation').text();
  6610. latex = latex.replace(/</g, "&lt;").replace(/>/g, "&gt;");
  6611. return "\n$$\n" + latex + "\n$$\n";
  6612. }
  6613. });
  6614.  
  6615. // pre
  6616. turndownService.addRule('pre', {
  6617. filter: function (node, options) {
  6618. return node.tagName.toLowerCase() == "pre";
  6619. },
  6620. replacement: function (content, node) {
  6621. return "```\n" + content + "```\n";
  6622. }
  6623. });
  6624.  
  6625. // bordertable
  6626. turndownService.addRule('bordertable', {
  6627. filter: 'table',
  6628. replacement: function (content, node) {
  6629. if (node.classList.contains('table')) {
  6630. var output = [],
  6631. thead = '',
  6632. trs = node.querySelectorAll('tr');
  6633. if (trs.length > 0) {
  6634. var ths = trs[0].querySelectorAll('th, td');
  6635. if (ths.length > 0) {
  6636. thead = '| ' + Array.from(ths).map(th => turndownService.turndown(th.innerHTML.trim())).join(' | ') + ' |\n'
  6637. thead += '| ' + Array.from(ths).map(() => ' --- ').join('|') + ' |\n';
  6638. }
  6639. }
  6640. var rows = node.querySelectorAll('tr');
  6641. Array.from(rows).forEach(function (row, i) {
  6642. if (i > 0) {
  6643. var cells = row.querySelectorAll('td,th');
  6644. var trow = '| ' + Array.from(cells).map(cell => turndownService.turndown(cell.innerHTML.trim())).join(' | ') + ' |';
  6645. output.push(trow);
  6646. }
  6647. });
  6648. return thead + output.join('\n');
  6649. } else {
  6650. return content;
  6651. }
  6652. }
  6653. });
  6654.  
  6655. /**
  6656. * 任务队列
  6657. */
  6658. class TaskQueue {
  6659. constructor() {
  6660. this.taskQueues = {};
  6661. this.isProcessing = {}; // 处理状态
  6662. this.delays = {}; // 等待时间(毫秒)
  6663. }
  6664.  
  6665. getDelay(type) {
  6666. if (type === 'openai') {
  6667. return 0;
  6668. } else {
  6669. return OJBetter.translation.waitTime;
  6670. }
  6671. }
  6672.  
  6673. /**
  6674. * 添加任务
  6675. * @param {string} type 任务类型
  6676. * @param {function} fn 任务函数
  6677. * @param {boolean} isNonQueueTask 是否为非队列任务
  6678. */
  6679. addTask(type, fn, isNonQueueTask = false) {
  6680. if (!this.taskQueues[type]) {
  6681. this.taskQueues[type] = [];
  6682. }
  6683.  
  6684. if (isNonQueueTask) {
  6685. fn();
  6686. } else {
  6687. this.taskQueues[type].push(fn);
  6688.  
  6689. if (!this.isProcessing[type]) {
  6690. this.processQueue(type);
  6691. }
  6692. }
  6693. }
  6694.  
  6695. async processQueue(type) {
  6696. this.isProcessing[type] = true;
  6697.  
  6698. while (this.taskQueues[type].length > 0) {
  6699. const task = this.taskQueues[type].shift();
  6700. await task();
  6701.  
  6702. if (this.taskQueues[type].length > 0) {
  6703. await this.wait(this.getDelay(type));
  6704. }
  6705. }
  6706.  
  6707. this.isProcessing[type] = false;
  6708. }
  6709.  
  6710. wait(delay) {
  6711. return new Promise(resolve => {
  6712. setTimeout(resolve, delay);
  6713. });
  6714. }
  6715. }
  6716.  
  6717. /**
  6718. * 检测文本是否可能为代码片段
  6719. * @param {string} text 待检测的文本
  6720. * @returns {boolean} 是否可能为代码片段
  6721. */
  6722. function isLikelyCodeSnippet(text) {
  6723. // 过滤文本中可能的HTML标签
  6724. text = OJB_removeHTMLTags(text);
  6725.  
  6726. // 移除LaTeX公式部分
  6727. const cleanedText = text.replace(/(\$\$?[\s\S]*?\$\$?)/g, '');
  6728.  
  6729. // 代码的关键字
  6730. const keywords = [
  6731. 'int', 'float', 'return', 'if', 'else', 'while', 'for', 'switch', 'case', 'break', 'continue',
  6732. 'class', 'public', 'private', 'protected', 'void', 'static', 'const', 'enum', 'struct',
  6733. 'char', 'double', 'long', 'include', 'def', 'import', 'from', 'as', 'elif', 'try', 'except',
  6734. 'raise', 'with', 'lambda', 'print'
  6735. ];
  6736. // 代码的特殊字符
  6737. const codeChars = [';', '{', '}', '>', '<', '<<', '>>', '=', '+', '-',
  6738. '&', '|', ':', '\'\'\'', '\"\"\"', '->'];
  6739.  
  6740. // 普通文本的标点符号
  6741. const textChars = ['.', ',', '?', '!', ':', '"', "'"];
  6742.  
  6743. // 关键字的数量
  6744. const keywordCount = keywords.reduce((count, keyword) => {
  6745. const regex = new RegExp("\\b" + keyword + "\\b", 'gi');
  6746. return count + (cleanedText.match(regex) || []).length;
  6747. }, 0);
  6748.  
  6749. // 代码的特殊字符的数量
  6750. const codeCharCount = codeChars.reduce((count, char) => {
  6751. const regex = new RegExp("\\" + char, 'g');
  6752. return count + (cleanedText.match(regex) || []).length;
  6753. }, 0);
  6754.  
  6755. // 普通文本字符的数量
  6756. const textCharCount = textChars.reduce((count, char) => {
  6757. const regex = new RegExp("\\" + char, 'g');
  6758. return count + (cleanedText.match(regex) || []).length;
  6759. }, 0);
  6760.  
  6761. // 如果代码关键字数量或者代码的特殊字符数量显著高于普通文本标点符号数量,或者存在Python缩进,则可能是代码
  6762. if (keywordCount > textCharCount * 2 || codeCharCount > textCharCount * 2) {
  6763. console.log("keywordCount:", keywordCount, "codeCharCount:", codeCharCount, "textCharCount:", textCharCount);
  6764. return true;
  6765. }
  6766.  
  6767. return false;
  6768. }
  6769.  
  6770. /**
  6771. * 加载按钮相关函数
  6772. */
  6773. async function initButtonFunc() {
  6774. // 鼠标悬浮时为目标元素区域添加一个覆盖层
  6775. $.fn.addHoverOverlay = function (target) {
  6776. let position = $(target).css('position');
  6777. let display = $(target).css('display');
  6778.  
  6779. this.hover(() => {
  6780. $(target)
  6781. .addClass('overlay')
  6782. .css('position', 'relative');
  6783. if (display == "inline" || display == "contents") {
  6784. $(target).css('display', 'block');
  6785. }
  6786. }, () => {
  6787. $(target)
  6788. .removeClass('overlay')
  6789. .css('position', position);
  6790. if (display == "inline" || display == "contents") {
  6791. $(target).css('display', display);
  6792. }
  6793. })
  6794. }
  6795.  
  6796. /**
  6797. * 为按钮设置图标
  6798. * @param {string} icon 图标
  6799. * @returns {JQuery<HTMLElement>} 按钮
  6800. */
  6801. $.fn.setButtonIcon = function (icon) {
  6802. let i = this.find("i");
  6803. if (i.length != 0 && i.hasClass("iconfont")) {
  6804. i.html(icon);
  6805. } else {
  6806. i = OJB_safeCreateJQElement(`<i>${icon}</i>`);
  6807. this.prepend(i);
  6808. }
  6809. return this;
  6810. }
  6811.  
  6812. /**
  6813. * 设置按钮为加载等待状态
  6814. */
  6815. $.fn.setButtonLoading = function () {
  6816. this.addClass("loading");
  6817. this.prop("disabled", true);
  6818. return this;
  6819. }
  6820.  
  6821. /**
  6822. * 解除按钮的加载等待状态
  6823. */
  6824. $.fn.setButtonLoaded = function () {
  6825. this.removeClass("loading");
  6826. this.prop("disabled", false);
  6827. return this;
  6828. }
  6829.  
  6830. /**
  6831. * 为按钮设置popover提示文本
  6832. * @param {string} text 文本
  6833. * @returns {JQuery<HTMLElement>} 按钮
  6834. */
  6835. $.fn.setButtonPopover = function (text) {
  6836. // find if has popover_content class element
  6837. let popover_content = this.find(".popover_content");
  6838. if (popover_content.length != 0) {
  6839. popover_content.text(text);
  6840. } else {
  6841. popover_content = OJB_safeCreateJQElement(`<span class="popover_content">${text}</span>`);
  6842. this.append(popover_content);
  6843. }
  6844. return this;
  6845. }
  6846.  
  6847. /**
  6848. * 获取MarkDown
  6849. * @returns {string} MarkDown
  6850. */
  6851. $.fn.getMarkdown = function () {
  6852. const markdown = this.data('markdown');
  6853. if (markdown === undefined) {
  6854. const htmlContent = this.html();
  6855. const newMarkdown = turndownService.turndown(htmlContent);
  6856. this.data('markdown', newMarkdown);
  6857. return newMarkdown;
  6858. }
  6859. return markdown;
  6860. }
  6861.  
  6862. // 设置按钮状态
  6863. $.fn.setButtonState = function (state, popoverText = null, disabled = false) {
  6864. this.data('buttonState', state)
  6865. .prop('disabled', disabled)
  6866. .css('cursor', disabled ? 'not-allowed' : 'pointer')
  6867. .removeClass('running success enabled error loading redo');
  6868. if (popoverText) this.setButtonPopover(popoverText);
  6869.  
  6870. if (state !== 'initial') this.addClass(state);
  6871. return this;
  6872. };
  6873.  
  6874. // 为按钮添加鼠标悬浮重试
  6875. $.fn.setHoverRedo = function () {
  6876. this.hover(() => {
  6877. prevState = this.getButtonState();
  6878. if (prevState !== "normal" && prevState !== "running") {
  6879. this.setButtonState('redo');
  6880. }
  6881. }, () => {
  6882. const currentState = this.getButtonState();
  6883. if (prevState !== "normal" && ["normal", "redo"].includes(currentState)) {
  6884. this.setButtonState(prevState);
  6885. prevState = null;
  6886. }
  6887. });
  6888. };
  6889.  
  6890. // 获取按钮状态
  6891. $.fn.getButtonState = function () {
  6892. return this.data('buttonState') || 'normal';
  6893. };
  6894.  
  6895. // 设置翻译按钮状态
  6896. $.fn.setTransButtonState = function (state, text = null) {
  6897. const popoverText = text || i18next.t(`trans.${state}`, { ns: 'button' });
  6898. const disabled = state === 'running' || state === 'loading';
  6899. this.setButtonState(state, popoverText, disabled);
  6900. return this;
  6901. };
  6902.  
  6903. // 存翻译结果
  6904. $.fn.pushResultToTransButton = function (result) {
  6905. let resultStack = this.data('resultStack');
  6906. if (!resultStack) resultStack = [];
  6907. resultStack.push(result);
  6908. this.data('resultStack', resultStack);
  6909. }
  6910.  
  6911. // 获取翻译结果
  6912. $.fn.getResultFromTransButton = function () {
  6913. return this.data('resultStack');
  6914. }
  6915.  
  6916. // 标记为不自动翻译
  6917. $.fn.setNotAutoTranslate = function () {
  6918. this.data('notAutoTranslate', true);
  6919. }
  6920.  
  6921. // 获取是否为不自动翻译
  6922. $.fn.getNotAutoTranslate = function () {
  6923. return this.data('notAutoTranslate');
  6924. }
  6925.  
  6926. // 判断是否已经翻译
  6927. $.fn.IsTranslated = function () {
  6928. if (this.hasAttr('translated')) {
  6929. return true;
  6930. } else {
  6931. return false;
  6932. }
  6933. }
  6934.  
  6935. // 判断是否为评论区按钮
  6936. $.fn.IsCommentButton = function () {
  6937. let isCommentButton = this.data('isCommentButton');
  6938. if (isCommentButton == undefined) {
  6939. this.parents('.comments').length > 0 ? isCommentButton = true : isCommentButton = false;
  6940. this.data('isCommentButton', isCommentButton);
  6941. }
  6942. return isCommentButton;
  6943. }
  6944.  
  6945. // 按钮点击效果
  6946. $(document).on('mousedown', '.ojb_btn', function () {
  6947. $(this).addClass('active').on('animationend', () => $(this).removeClass('active'));
  6948. });
  6949. }
  6950.  
  6951. /**
  6952. * 添加题目markdown转换/复制/翻译按钮面板
  6953. * @param {HTMLElement} element 需要添加按钮面板的元素
  6954. * @param {string} suffix 按钮面板id后缀
  6955. * @param {string} type 按钮面板添加位置
  6956. * @param {boolean} is_simple 是否是简单模式
  6957. * @returns {object} 返回按钮面板元素
  6958. */
  6959. function addButtonPanel(element, suffix, type, is_simple = false) {
  6960. let text;
  6961. if (OJBetter.translation.comment.transMode == "1") text = i18next.t('trans.segment', { ns: 'button' });
  6962. else if (OJBetter.translation.comment.transMode == "2") text = i18next.t('trans.select', { ns: 'button' });
  6963. else text = i18next.t('trans.normal', { ns: 'button' });
  6964.  
  6965. let panel = OJB_safeCreateJQElement(`<div class='html2md-panel input-output-copier ${is_simple ? 'is_simple' : ''}'></div>`);
  6966. let viewButton = OJB_safeCreateJQElement(`
  6967. <button class='ojb_btn ojb_btn_popover top' id='html2md-view${suffix}'>
  6968. <i class="iconfont">&#xe7e5;</i>
  6969. <span class="popover_content">${i18next.t('md.normal', { ns: 'button' })}</span>
  6970. </button>`);
  6971. let copyButton = OJB_safeCreateJQElement(`
  6972. <button class='ojb_btn ojb_btn_popover top' id='html2md-cb${suffix}'>
  6973. <i class="iconfont">&#xe608;</i>
  6974. <span class="popover_content">${i18next.t('copy.normal', { ns: 'button' })}</span>
  6975. </button>`);
  6976. let translateButton = OJB_safeCreateJQElement(`
  6977. <button class='ojb_btn translateButton ojb_btn_popover top' id='translateButton${suffix}'>
  6978. <i class="iconfont">&#xe6be;</i>
  6979. <span class="popover_content">${text}</span>
  6980. </button>`);
  6981. if (!is_simple) panel.append(viewButton);
  6982. if (!is_simple) panel.append(copyButton);
  6983. panel.append(translateButton);
  6984. if (type === "this_level") {
  6985. $(element).before(panel);
  6986. } else if (type === "child_level") {
  6987. $(element).prepend(panel);
  6988. }
  6989.  
  6990. return {
  6991. panel: panel,
  6992. viewButton: viewButton,
  6993. copyButton: copyButton,
  6994. translateButton: translateButton
  6995. }
  6996. }
  6997.  
  6998. /**
  6999. * 添加MD视图按钮
  7000. * @param {JQuery<HTMLElement>} button 按钮
  7001. * @param {JQuery<HTMLElement>} element 目标元素
  7002. * @param {string} suffix id后缀
  7003. * @param {string} type 类型
  7004. * @returns {void}
  7005. */
  7006. async function addButtonWithHTML2MD(button, element, suffix, type) {
  7007. /**
  7008. * 改变按钮状态
  7009. * @param {string} state 状态
  7010. */
  7011. function changeButtonState(state) {
  7012. if (state == "loading") {
  7013. button.setButtonLoading();
  7014. button.setButtonPopover(i18next.t('state.waitMathJax', { ns: 'button' }));
  7015. } else if (state == "loaded") {
  7016. button.setButtonLoaded();
  7017. button.setButtonPopover(i18next.t('md.normal', { ns: 'button' }));
  7018. } else if (state == "normal") {
  7019. button.removeClass("enabled");
  7020. button.setButtonPopover(i18next.t('md.normal', { ns: 'button' }));
  7021. } else if (state == "mdView") {
  7022. button.addClass("enabled");
  7023. button.setButtonPopover(i18next.t('md.reduction', { ns: 'button' }));
  7024. } else if (state == "disabled") {
  7025. button.prop("disabled", true);
  7026. button.setButtonPopover(i18next.t('md.disabled', { ns: 'button' }));
  7027. }
  7028. }
  7029.  
  7030. if (OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru) {
  7031. changeButtonState("disabled");
  7032. return;
  7033. } else {
  7034. changeButtonState("loading");
  7035. await waitForMathJaxIdle();
  7036. changeButtonState("loaded");
  7037. }
  7038.  
  7039. button.click(OJB_debounce(function () {
  7040. var target = $(element).get(0);
  7041.  
  7042. /**
  7043. * 检查是否是MarkDown视图
  7044. * @returns {boolean} 是否是MarkDown视图
  7045. */
  7046. function checkViewmd() {
  7047. if ($(element).attr("viewmd") === "true") {
  7048. return true;
  7049. } else {
  7050. return false;
  7051. }
  7052. }
  7053.  
  7054. /**
  7055. * 设置是否是MarkDown视图
  7056. * @param {boolean} value 是否是MarkDown视图
  7057. * @returns {void}
  7058. */
  7059. function setViewmd(value) {
  7060. $(element).attr("viewmd", value);
  7061. if (value) {
  7062. changeButtonState("mdView");
  7063. } else {
  7064. changeButtonState("normal");
  7065. }
  7066. }
  7067.  
  7068. if (checkViewmd()) {
  7069. setViewmd(false);
  7070. $(element).next(".mdViewContent").remove();
  7071. $(element).show();
  7072. } else {
  7073. setViewmd(true);
  7074. var markdown = $(element).getMarkdown();
  7075. var mdViewContent = OJB_safeCreateJQElement(`<span class="mdViewContent" style="width:auto; height:auto;">${markdown}</span>`);
  7076. $(element).after(mdViewContent);
  7077. $(element).hide();
  7078. }
  7079. }));
  7080.  
  7081. if (OJBetter.preference.hoverTargetAreaDisplay && !OJBetter.typeOfPage.is_oldLatex && !OJBetter.typeOfPage.is_acmsguru) {
  7082. button.addHoverOverlay($(element));
  7083. }
  7084. }
  7085.  
  7086. /**
  7087. * 添加复制按钮
  7088. * @param {JQuery<HTMLElement>} button 按钮
  7089. * @param {JQuery<HTMLElement>} element 目标元素
  7090. * @param {string} suffix 后缀
  7091. * @param {string} type 类型
  7092. */
  7093. async function addButtonWithCopy(button, element, suffix, type) {
  7094. /**
  7095. * 改变按钮状态
  7096. * @param {string} state 状态
  7097. */
  7098. function changeButtonState(state) {
  7099. if (state == "loading") {
  7100. button.setButtonLoading();
  7101. button.setButtonPopover(i18next.t('state.waitMathJax', { ns: 'button' }));
  7102. } else if (state == "loaded") {
  7103. button.setButtonLoaded();
  7104. button.setButtonPopover(i18next.t('copy.normal', { ns: 'button' }));
  7105. } else if (state == "normal") {
  7106. button.setButtonPopover(i18next.t('copy.normal', { ns: 'button' }));
  7107. } else if (state == "copied") {
  7108. button.setButtonPopover(i18next.t('copy.copied', { ns: 'button' }));
  7109. } else if (state == "disabled") {
  7110. button.prop("disabled", true);
  7111. button.setButtonPopover(i18next.t('copy.disabled', { ns: 'button' }));
  7112. }
  7113. }
  7114.  
  7115. // 等待MathJax队列完成
  7116. if (OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru) {
  7117. changeButtonState("disabled");
  7118. return;
  7119. } else {
  7120. changeButtonState("loading");
  7121. await waitForMathJaxIdle();
  7122. changeButtonState("loaded");
  7123. }
  7124.  
  7125. button.click(OJB_debounce(function () {
  7126. var target = $(element).get(0);
  7127.  
  7128. var markdown = $(element).getMarkdown();
  7129.  
  7130. GM_setClipboard(markdown);
  7131.  
  7132. $(this).addClass("success");
  7133. changeButtonState("copied");
  7134.  
  7135.  
  7136. // 更新复制按钮文本
  7137. setTimeout(() => {
  7138. $(this).removeClass("success");
  7139. changeButtonState("normal")
  7140. }, 2000);
  7141. }));
  7142.  
  7143. if (OJBetter.preference.hoverTargetAreaDisplay && !OJBetter.typeOfPage.is_oldLatex && !OJBetter.typeOfPage.is_acmsguru) {
  7144. button.addHoverOverlay($(element));
  7145. }
  7146. }
  7147.  
  7148. /**
  7149. * 添加翻译按钮
  7150. * @param {JQuery<HTMLElement>} button 按钮
  7151. * @param {JQuery<HTMLElement>} element 目标元素
  7152. * @param {string} suffix 后缀
  7153. * @param {string} type 类型
  7154. * @param {boolean} is_comment 是否是评论
  7155. */
  7156. async function addButtonWithTranslation(button, element, suffix, type, is_comment = false) {
  7157. // 添加可指定翻译服务的方法调用
  7158. button.data("translatedItBy", function (translation) {
  7159. button.setTransButtonState('running', i18next.t('trans.wait', { ns: 'button' }));
  7160. OJBetter.common.taskQueue.addTask(translation, () => transTask(button, element, type, is_comment, translation), translation == 'openai');
  7161. });
  7162.  
  7163. // 等待MathJax队列完成
  7164. button.setButtonLoading();
  7165. await waitForMathJaxIdle();
  7166. button.setButtonLoaded();
  7167.  
  7168. // 标记目标文本区域不自动翻译
  7169. {
  7170. let text;
  7171. if (OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru) {
  7172. text = $(element).html();
  7173. } else {
  7174. text = $(element).getMarkdown();
  7175. }
  7176. let length = text.length;
  7177. if (length > OJBetter.translation.auto.shortTextLength || isLikelyCodeSnippet(text)) {
  7178. button.setNotAutoTranslate();
  7179. }
  7180. // button.after(`<span>${length}</span>`); // 显示字符数
  7181. }
  7182.  
  7183. button.click(OJB_debounce(async function () {
  7184. // 重新翻译
  7185. let resultStack = $(this).getResultFromTransButton();
  7186. if (resultStack) {
  7187. let pElements = $(element).find("p.block_selected:not(li p), li.block_selected");
  7188. for (let item of resultStack) {
  7189. if (OJBetter.translation.retransAction == "0") {
  7190. // 选段翻译不直接移除旧结果
  7191. if (OJBetter.translation.comment.transMode == "2") {
  7192. // 只移除即将要翻译的段的结果
  7193. if (pElements.is(item.translateDiv.getDiv().prev())) {
  7194. item.translateDiv.close();
  7195. }
  7196. } else {
  7197. item.translateDiv.close();
  7198. $($(element)).find(".translate-problem-statement, .translate-problem-statement-panel").remove();
  7199. }
  7200. } else {
  7201. item.translateDiv.foldMainDiv();
  7202. }
  7203. }
  7204. }
  7205.  
  7206. // 翻译
  7207. button.setTransButtonState('running', i18next.t('trans.wait', { ns: 'button' }));
  7208. OJBetter.common.taskQueue.addTask(OJBetter.translation.choice, () => transTask(button, element, type, is_comment), OJBetter.translation.choice == 'openai');
  7209. }));
  7210.  
  7211. // 重新翻译提示
  7212. let prevState;
  7213. button.hover(() => {
  7214. prevState = button.getButtonState();
  7215. if (prevState !== "normal" && prevState !== "running") {
  7216. button.setTransButtonState('redo');
  7217. }
  7218. }, () => {
  7219. const currentState = button.getButtonState();
  7220. if (prevState !== "normal" && ["normal", "redo"].includes(currentState)) {
  7221. button.setTransButtonState(prevState);
  7222. prevState = null;
  7223. }
  7224. });
  7225.  
  7226. // 目标区域指示
  7227. if (OJBetter.preference.hoverTargetAreaDisplay) {
  7228. button.addHoverOverlay($(element));
  7229. }
  7230.  
  7231. // 翻译右键切换菜单
  7232. $(document).on('contextmenu', '#translateButton' + suffix, function (e) {
  7233. e.preventDefault();
  7234.  
  7235. // 是否为评论的翻译
  7236. let is_comment = button.IsCommentButton();
  7237.  
  7238. // 移除旧的
  7239. if (!$(e.target).closest('.OJBetter_contextmenu').length) {
  7240. $('.OJBetter_contextmenu').remove();
  7241. }
  7242.  
  7243. var menu = $('<div class="OJBetter_contextmenu"></div>');
  7244. var translations = [
  7245. { value: 'deepl', name: i18next.t('translation.options.services.deepl', { ns: 'settings' }) },
  7246. { value: 'iflyrec', name: i18next.t('translation.options.services.iflyrec', { ns: 'settings' }) },
  7247. { value: 'youdao', name: i18next.t('translation.options.services.youdao', { ns: 'settings' }) },
  7248. { value: 'google', name: i18next.t('translation.options.services.google', { ns: 'settings' }) },
  7249. { value: 'caiyun', name: i18next.t('translation.options.services.caiyun', { ns: 'settings' }) },
  7250. { value: 'openai', name: i18next.t('translation.options.services.openai.name', { ns: 'settings' }) }
  7251. ];
  7252.  
  7253. // Function to check if the service supports the target language
  7254. function supportsTargetLanguage(service, targetLang) {
  7255. return OJBetter.supportList.translationSupport[service] && OJBetter.supportList.translationSupport[service][targetLang] !== undefined;
  7256. }
  7257.  
  7258. if (is_comment) {
  7259. var label = OJB_safeCreateJQElement(`<label><input type="radio" name="translation" value="0">
  7260. <span class="OJBetter_contextmenu_label_text">
  7261. ${i18next.t('translation.preference.comment_translation_choice.services.follow', { ns: 'settings' })}
  7262. </span></label>`);
  7263. menu.append(label);
  7264. }
  7265. translations.forEach(function (translation) {
  7266. if (supportsTargetLanguage(translation.value, OJBetter.translation.targetLang)) {
  7267. var label = OJB_safeCreateJQElement(`<label><input type="radio" name="translation" value="${translation.value}">
  7268. <span class="OJBetter_contextmenu_label_text">${translation.name}</span></label>`);
  7269. menu.append(label);
  7270. }
  7271. });
  7272.  
  7273. // 初始化
  7274. if (is_comment) {
  7275. menu.find(`input[name="translation"][value="${OJBetter.translation.comment.choice}"]`).prop('checked', true);
  7276. } else {
  7277. menu.find(`input[name="translation"][value="${OJBetter.translation.choice}"]`).prop('checked', true);
  7278. }
  7279. menu.css({
  7280. top: e.pageY + 'px',
  7281. left: e.pageX + 'px'
  7282. }).appendTo('body');
  7283.  
  7284. $(document).one('change', 'input[name="translation"]', function () {
  7285. if (is_comment) {
  7286. OJBetter.translation.comment.choice = $('input[name="translation"]:checked').val();
  7287. GM_setValue("commentTranslationChoice", OJBetter.translation.comment.choice);
  7288. } else {
  7289. OJBetter.translation.choice = $('input[name="translation"]:checked').val();
  7290. GM_setValue("translation", OJBetter.translation.choice);
  7291. }
  7292. $('.OJBetter_contextmenu').remove();
  7293. });
  7294.  
  7295. // 点击区域外关闭菜单
  7296. function handleClick(event) {
  7297. if (!$(event.target).closest('.OJBetter_contextmenu').length) {
  7298. $('.OJBetter_contextmenu').remove();
  7299. $(document).off('change', 'input[name="translation"]');
  7300. } else {
  7301. $(document).one('click', handleClick);
  7302. }
  7303. }
  7304. $(document).one('click', handleClick);
  7305. });
  7306. }
  7307.  
  7308. /**
  7309. * 创建翻译任务
  7310. * @param {JQuery<HTMLElement>} button 按钮
  7311. * @param {HTMLElement} element 目标元素
  7312. * @param {string} type 类型
  7313. * @param {boolean} is_comment 是否是评论
  7314. * @param {string} overrideTrans 覆盖全局翻译服务设定
  7315. */
  7316. async function transTask(button, element, type, is_comment, overrideTrans) {
  7317. /** @type {HTMLElement} 目标元素 */
  7318. let target;
  7319. /**
  7320. * 错误计数数据结构
  7321. * @typedef {Object} count
  7322. * @property {number} errerNum 错误数量
  7323. * @property {number} skipNum 跳过数量
  7324. */
  7325. const count = {
  7326. errerNum: 0,
  7327. skipNum: 0
  7328. };
  7329. if (OJBetter.translation.comment.transMode == "1") {
  7330. // 分段翻译
  7331. let pElements = $(element).find("p:not(li p), li, .OJBetter_acmsguru");
  7332. for (let i = 0; i < pElements.length; i++) {
  7333. target = $(pElements[i]).eq(0).clone();
  7334. element_node = pElements[i];
  7335. await process(button, target, element_node, type, is_comment, count, overrideTrans);
  7336. }
  7337. } else if (OJBetter.translation.comment.transMode == "2") {
  7338. // 选段翻译
  7339. let pElements = $(element).find("p.block_selected:not(li p), li.block_selected, .OJBetter_acmsguru");
  7340. for (let i = 0; i < pElements.length; i++) {
  7341. target = $(pElements[i]).eq(0).clone();
  7342. element_node = pElements[i];
  7343. await process(button, target, element_node, type, is_comment, count, overrideTrans);
  7344. }
  7345. $(element).find("p.block_selected:not(li p), li.block_selected").removeClass('block_selected');
  7346. } else {
  7347. // 普通翻译
  7348. target = $(element).eq(0).clone();
  7349. if (type === "child_level") $(target).children(':first').remove();
  7350. element_node = $($(element)).get(0);
  7351. await process(button, target, element_node, type, is_comment, count, overrideTrans);
  7352. }
  7353.  
  7354. // 翻译完成
  7355. if (!count.errerNum && !count.skipNum) {
  7356. button.setTransButtonState('success');
  7357. }
  7358. }
  7359.  
  7360. /**
  7361. * 翻译处理
  7362. * @param {JQuery<HTMLElement>} button 按钮
  7363. * @param {HTMLElement} target 目标元素
  7364. * @param {HTMLElement} element_node 目标节点
  7365. * @param {string} type 类型
  7366. * @param {boolean} is_comment 是否是评论
  7367. * @param {string} overrideTrans 覆盖全局翻译服务设定
  7368. */
  7369. async function process(button, target, element_node, type, is_comment, count, overrideTrans) {
  7370. if (type === "child_level") {
  7371. let div = $("<div>");
  7372. $(element_node).append(div);
  7373. element_node = div.get(0);
  7374. }
  7375.  
  7376. //是否跳过折叠块
  7377. if ($(target).find('.spoiler').length > 0) {
  7378. const shouldSkip = await OJB_createDialog(
  7379. i18next.t('skipFold.title', { ns: 'dialog' }),
  7380. i18next.t('skipFold.content', { ns: 'dialog' }),
  7381. [
  7382. i18next.t('skipFold.buttons.0', { ns: 'dialog' }),
  7383. i18next.t('skipFold.buttons.1', { ns: 'dialog' })
  7384. ],
  7385. true
  7386. ); //跳过折叠块确认
  7387. if (shouldSkip) {
  7388. $(target).find('.spoiler').remove();
  7389. } else {
  7390. $(target).find('.html2md-panel').remove();
  7391. }
  7392. }
  7393.  
  7394. // 等待并获取结果
  7395. button.setTransButtonState('running');
  7396. const result = await blockProcessing(button, target, element_node, is_comment, overrideTrans);
  7397. button.pushResultToTransButton(result);
  7398.  
  7399. if (result.status == "error") count.errerNum += 1;
  7400. else if (result.status == "skip") count.skipNum += 1;
  7401. $(target).remove();
  7402. }
  7403.  
  7404. /**
  7405. * 块处理
  7406. * @param {JQuery<HTMLElement>} button
  7407. * @param {HTMLElement} target 目标元素
  7408. * @param {HTMLElement} element_node 目标节点
  7409. * @param {boolean} is_comment 是否是评论
  7410. * @param {string} overrideTrans 覆盖全局翻译服务设定
  7411. * @returns {TranslateResult} 翻译结果对象
  7412. */
  7413. async function blockProcessing(button, target, element_node, is_comment, overrideTrans) {
  7414. if (OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru) {
  7415. target.markdown = $(target).html();
  7416. } else if (!target.markdown) {
  7417. target.markdown = turndownService.turndown($(target).html());
  7418. }
  7419.  
  7420. const result = await translateProblemStatement(target.markdown, element_node, is_comment, overrideTrans);
  7421. if (result.status == "skip") {
  7422. button.setTransButtonState('error', i18next.t('trans.tooLong', { ns: 'button' }));
  7423. result.translateDiv.close();
  7424. } else if (result.status == "error" || !result.rawData.done) {
  7425. result.translateDiv.setError();
  7426. result.translateDiv.setRawData(result.rawData);
  7427. result.translateDiv.showDebugButton();
  7428. button.setTransButtonState('error', i18next.t('trans.error', { ns: 'button' }));
  7429. $(target).remove();
  7430. }
  7431. return result;
  7432. }
  7433.  
  7434. /**
  7435. * 选段翻译支持
  7436. */
  7437. async function multiChoiceTranslation() {
  7438. GM_addStyle(`
  7439. .topic .content #task-statement {
  7440. overflow: initial;
  7441. }
  7442. `);
  7443.  
  7444. $(document).on('click', 'p, li:not(:has(.comment)), .OJBetter_acmsguru', function (e) {
  7445. let $this = $(this);
  7446. e.stopPropagation();
  7447. if ($this.hasClass('block_selected')) {
  7448. $this.removeClass('block_selected');
  7449. // 移除对应的按钮
  7450. $('.OJBetter_MiniTranslateButton').remove("#translateButton_selected_" + $this.attr('OJBetter_p_id'));
  7451. } else {
  7452. let id = OJB_getRandomNumber(8);
  7453. $this.attr('OJBetter_p_id', id);
  7454. $this.addClass('block_selected');
  7455. // 添加按钮
  7456. let menu = OJB_safeCreateJQElement(`<div class="OJBetter_MiniTranslateButton" id='translateButton_selected_${id}'>${translateIcon}</div>`)
  7457. .css({
  7458. left: $($this).outerWidth(true) + $($this).position().left + 10 + 'px',
  7459. });
  7460. $this.before(menu);
  7461.  
  7462. $("#translateButton_selected_" + id).click(async function () {
  7463. // 处理旧的结果
  7464. if ($this.attr('translated')) {
  7465. let result = $this.data("resultData");
  7466. if (OJBetter.translation.retransAction == "0") {
  7467. result.translateDiv.close();
  7468. } else {
  7469. result.translateDiv.foldMainDiv();
  7470. }
  7471. }
  7472. // 翻译
  7473. let target = $this.eq(0).clone();
  7474. let result = await blockProcessing(OJBetter.translation.choice, target, $this.eq(0), $("#translateButton_selected_" + id), false);
  7475. $this.data("resultData", result);
  7476. $this.removeClass('block_selected');
  7477. // 移除对应的按钮
  7478. $('.OJBetter_MiniTranslateButton').remove("#translateButton_selected_" + id);
  7479. $this.attr('translated', '1'); // 标记已翻译
  7480. });
  7481. }
  7482. });
  7483. }
  7484.  
  7485. /**
  7486. * 添加MD/复制/翻译按钮
  7487. */
  7488. async function addConversionButton() {
  7489. // 基本添加
  7490. if (!OJBetter.typeOfPage.is_homepage) {
  7491. $('section').each(function () {
  7492. let id = "_" + OJB_getRandomNumber(8);
  7493. let panel = addButtonPanel(this, id, "this_level");
  7494. addButtonWithHTML2MD(panel.viewButton, this, id, "this_level");
  7495. addButtonWithCopy(panel.copyButton, this, id, "this_level");
  7496. addButtonWithTranslation(panel.translateButton, this, id, "this_level");
  7497. });
  7498. }
  7499.  
  7500. // 添加按钮到题解部分
  7501. if (window.location.href.includes("editorial")) {
  7502. let contestNavTabs = $("#contest-nav-tabs");
  7503. let nextElement = contestNavTabs.next();
  7504. let id = "_editorial_" + OJB_getRandomNumber(8);
  7505. let panel = addButtonPanel(nextElement, id, "child_level");
  7506. addButtonWithHTML2MD(panel.viewButton, nextElement, id, "child_level");
  7507. addButtonWithCopy(panel.copyButton, nextElement, id, "child_level");
  7508. addButtonWithTranslation(panel.translateButton, nextElement, id, "child_level");
  7509. }
  7510. if (window.location.href.includes("editorial")) {
  7511. let contestNavTabs = $("#contest-nav-tabs");
  7512. let nextElement = contestNavTabs.next().children().eq(-2);
  7513. let id = "_editorial_" + OJB_getRandomNumber(8);
  7514. let panel = addButtonPanel(nextElement, id, "child_level");
  7515. addButtonWithHTML2MD(panel.viewButton, nextElement, id, "child_level");
  7516. addButtonWithCopy(panel.copyButton, nextElement, id, "child_level");
  7517. addButtonWithTranslation(panel.translateButton, nextElement, id, "child_level");
  7518. }
  7519.  
  7520. // 添加按钮到折叠块部分
  7521. $('details').each(function () {
  7522. // 自定义测试样例折叠块不添加
  7523. if ($(this).attr('id') !== "customTestBlock") {
  7524. let id = "_details_" + OJB_getRandomNumber(8);
  7525. let panel = addButtonPanel(this, id, "child_level");
  7526. addButtonWithHTML2MD(panel.viewButton, this, id, "child_level");
  7527. addButtonWithCopy(panel.copyButton, this, id, "child_level");
  7528. addButtonWithTranslation(panel.translateButton, this, id, "child_level");
  7529. }
  7530. });
  7531.  
  7532. // 添加到contest-statement部分
  7533. $('#contest-statement').each(function () {
  7534. let id = "_contest-statement_" + OJB_getRandomNumber(8);
  7535. let panel = addButtonPanel(this, id, "this_level");
  7536. addButtonWithHTML2MD(panel.viewButton, this, id, "this_level");
  7537. addButtonWithCopy(panel.copyButton, this, id, "this_level");
  7538. addButtonWithTranslation(panel.translateButton, this, id, "this_level");
  7539. });
  7540.  
  7541. // 添加到blog-post部分
  7542. $('.blog-post').each(function () {
  7543. let id = "_blog-post_" + OJB_getRandomNumber(8);
  7544. let panel = addButtonPanel(this, id, "this_level");
  7545. addButtonWithHTML2MD(panel.viewButton, this, id, "this_level");
  7546. addButtonWithCopy(panel.copyButton, this, id, "this_level");
  7547. addButtonWithTranslation(panel.translateButton, this, id, "this_level");
  7548. });
  7549. };
  7550.  
  7551. /**
  7552. * 等待LaTeX渲染队列全部完成
  7553. * @returns {Promise} 完成渲染
  7554. */
  7555. function waitForMathJaxIdle() {
  7556. return true;
  7557. // return new Promise((resolve, reject) => {
  7558. // // 检查MathJax对象是否存在
  7559. // const checkMathJaxExists = () => {
  7560. // if (typeof MathJax === 'undefined') {
  7561. // // 如果MathJax不存在,稍后再次检查
  7562. // OJB_delay(100).then(checkMathJaxExists);
  7563. // } else {
  7564. // // MathJax存在,开始监视渲染队列
  7565. // startMonitoringQueue();
  7566. // }
  7567. // };
  7568.  
  7569. // // 开始监视MathJax渲染队列
  7570. // const startMonitoringQueue = () => {
  7571. // const intervalId = setInterval(() => {
  7572. // const queue = MathJax.Hub.queue;
  7573. // if (queue.pending === 0 && queue.running === 0) {
  7574. // clearInterval(intervalId);
  7575. // resolve();
  7576. // }
  7577. // }, 100);
  7578. // };
  7579.  
  7580. // // 开始检查MathJax对象
  7581. // checkMathJaxExists();
  7582. // });
  7583. }
  7584.  
  7585. /**
  7586. * 翻译结果面板
  7587. */
  7588. class TranslateDiv {
  7589. /**
  7590. * 构造函数
  7591. * @param {string} id 指定翻译框的id
  7592. */
  7593. constructor(id) {
  7594. this.id = id;
  7595. this.div = $('<div>').attr('id', id).addClass('translateDiv bounce-in');
  7596. if (!OJBetter.typeOfPage.is_completeProblemset) {
  7597. this.div.addClass('input-output-copier');
  7598. }
  7599. this.panelDiv = $('<div>').addClass('translate-problem-statement-panel');
  7600. this.div.append(this.panelDiv);
  7601.  
  7602. // 主要信息
  7603. this.mainDiv = $('<div>').addClass('translate-problem-statement');
  7604. this.span = $('<span>');
  7605. this.mainDiv.append(this.span);
  7606. this.div.append(this.mainDiv);
  7607. this.mainDivState = {
  7608. current: 'transHTML',
  7609. transHTML: '',
  7610. rawDataHTML: ''
  7611. };
  7612.  
  7613. // 顶栏信息
  7614. this.topText = $('<div>').addClass('topText');
  7615. this.panelDiv.append(this.topText);
  7616.  
  7617. // 右侧
  7618. this.rightDiv = $('<div>').css('display', 'flex');
  7619. this.panelDiv.append(this.rightDiv);
  7620. this.debugButton = OJB_safeCreateJQElement(`
  7621. <button class='ojb_btn ojb_btn_popover top'>
  7622. <i class="iconfont">&#xe641;</i>
  7623. <span class="popover_content">${i18next.t('rawData.normal', { ns: 'button' })}</span>
  7624. </button>`).hide();
  7625. this.rightDiv.append(this.debugButton);
  7626. this.queryBalanceButton = OJB_safeCreateJQElement(`
  7627. <button class='ojb_btn ojb_btn_popover top'>
  7628. <i class="iconfont">&#xe6ae;</i>
  7629. <span class="popover_content">${i18next.t('queryBalance.normal', { ns: 'button' })}</span>
  7630. </button>`).hide();
  7631. this.rightDiv.append(this.queryBalanceButton);
  7632. this.copyButton = OJB_safeCreateJQElement(`
  7633. <button class='ojb_btn ojb_btn_popover top'>
  7634. <i class="iconfont">&#xe608;</i>
  7635. <span class="popover_content">${i18next.t('copy.normal', { ns: 'button' })}</span>
  7636. </button>`);
  7637. this.rightDiv.append(this.copyButton);
  7638. this.upButton = OJB_safeCreateJQElement(`
  7639. <button class='ojb_btn ojb_btn_popover top'>
  7640. <i class="iconfont">&#xe601;</i>
  7641. <span class="popover_content">${i18next.t('fold.normal', { ns: 'button' })}</span>
  7642. </button>`);
  7643. this.rightDiv.append(this.upButton);
  7644. this.closeButton = OJB_safeCreateJQElement(`
  7645. <button class='ojb_btn ojb_btn_popover top'>
  7646. <i class="iconfont">&#xe614;</i>
  7647. <span class="popover_content">${i18next.t('close.normal', { ns: 'button' })}</span>
  7648. </button>`);
  7649. this.rightDiv.append(this.closeButton);
  7650. }
  7651.  
  7652. /**
  7653. * 获取翻译框
  7654. * @returns {JQuery<HTMLElement>} 返回翻译框
  7655. */
  7656. getDiv() {
  7657. return this.div;
  7658. }
  7659.  
  7660. /**
  7661. * 设置翻译框顶部的文本
  7662. * @param {string} text 翻译框顶部的文本
  7663. */
  7664. setTopText(text) {
  7665. this.div.attr("data-topText", text);
  7666. this.topText.text(text);
  7667. }
  7668.  
  7669. /**
  7670. * 获取翻译框顶部的文本
  7671. * @returns {string} 返回翻译框顶部的文本
  7672. */
  7673. getTopText() {
  7674. return this.topText.text();
  7675. }
  7676.  
  7677. /**
  7678. * 渲染一个元素内的LaTeX公式
  7679. * @param {*} element
  7680. */
  7681. renderLaTeX(element) {
  7682. const latexRenderOptions = {
  7683. delimiters: [
  7684. { left: "$$", right: "$$", display: true },
  7685. { left: "\$$", right: "\\$$", display: true },
  7686. { left: "$", right: "$", display: false },
  7687. { left: "\$$", right: "\\$$", display: false }
  7688. ]
  7689. };
  7690.  
  7691. if (typeof renderMathInElement === 'function') {
  7692. renderMathInElement(element, latexRenderOptions);
  7693. }
  7694. }
  7695.  
  7696. /**
  7697. * 更新翻译框内容
  7698. * @param {string} text 文本内容
  7699. * @param {boolean} is_escapeHTML 是否转义HTML标签,为true则HTML标签将作为普通文本处理,默认为true
  7700. * @param {boolean} is_renderLaTeX 是否渲染LaTeX,为true则会渲染LaTeX,默认为true
  7701. */
  7702. updateTranslateDiv(text, is_escapeHTML = true, is_renderLaTeX = true,) {
  7703. // 渲染MarkDown
  7704. let md = window.markdownit({
  7705. html: !is_escapeHTML,
  7706. });
  7707. if (!text) text = "";
  7708. let html = md.render(text);
  7709. this.mainDiv.html(html);
  7710.  
  7711. // 渲染Latex
  7712. if (is_renderLaTeX) {
  7713. // MathJax.Hub.Queue(["Typeset", MathJax.Hub, this.mainDiv.get(0)]);
  7714. this.renderLaTeX(this.mainDiv.get(0));
  7715. }
  7716. // 渲染代码块中的公式 (AtCoder)
  7717. this.mainDiv.find('pre code').each((index, element) => {
  7718. const codeText = $(element).text();
  7719. const latexPattern = /\$\$(\\.|[^\$])*?\$\$|\$(\\.|[^\$])*?\$/;
  7720. if (latexPattern.test(codeText)) {
  7721. this.renderLaTeX(element);
  7722. }
  7723. });
  7724. }
  7725.  
  7726. /**
  7727. * 关闭元素
  7728. */
  7729. close() {
  7730. this.closeButton.click();
  7731. }
  7732.  
  7733. /**
  7734. * 注册收起按钮事件
  7735. */
  7736. registerUpButtonEvent() {
  7737. this.upButton.on("click", () => {
  7738. // 如果没有reverse类,说明是展开状态
  7739. if (!this.upButton.hasClass("reverse")) {
  7740. // 执行收起操作
  7741. this.upButton.addClass("reverse");
  7742. this.upButton.setButtonState('initial', i18next.t('fold.unfold', { ns: 'button' }));
  7743. OJB_toggleCollapseExpand(this.mainDiv.get(0));
  7744. } else {
  7745. // 执行展开操作
  7746. this.upButton.removeClass("reverse");
  7747. this.upButton.setButtonState('initial', i18next.t('fold.normal', { ns: 'button' }));
  7748. OJB_toggleCollapseExpand(this.mainDiv.get(0));
  7749. }
  7750. });
  7751. }
  7752.  
  7753. /**
  7754. * 注册关闭按钮事件
  7755. */
  7756. registerCloseButtonEvent() {
  7757. this.closeButton.on("click", () => {
  7758. $(this.div).remove();
  7759. $(this.panelDiv).remove();
  7760. if (OJBetter.typeOfPage.is_problem && OJBetter.translation.memory.enabled) {
  7761. OJBetter.translation.memory.ttTree.rmTransResultMap(this.id); // 移除ttTree中的数据
  7762. OJBetter.translation.memory.ttTree.refreshNode("#task-statement");
  7763. updateTransDBData(OJBetter.translation.memory.ttTree.getNodeData(), OJBetter.translation.memory.ttTree.getTransResultMap()); // 更新DB中的数据
  7764. }
  7765. });
  7766. }
  7767.  
  7768. /**
  7769. * 注册复制按钮事件
  7770. * @param {string} text 复制的文本
  7771. */
  7772. registerCopyButtonEvent(text) {
  7773. this.copyButton.on("click", () => {
  7774. GM_setClipboard(text);
  7775. this.copyButton.setButtonState('success', i18next.t('copy.copied', { ns: 'button' }));
  7776. // 复制提示
  7777. setTimeout(() => {
  7778. this.copyButton.setButtonState('initial', i18next.t('copy.normal', { ns: 'button' }));
  7779. }, 2000);
  7780. });
  7781. }
  7782.  
  7783. /**
  7784. * 禁用复制按钮
  7785. */
  7786. disableCopyButton() {
  7787. this.copyButton.css({ 'fill': '#ccc' });
  7788. this.copyButton.off("click");
  7789. }
  7790.  
  7791. /**
  7792. * 设置面板为error状态
  7793. */
  7794. setError() {
  7795. this.div.addClass('error');
  7796. this.panelDiv.addClass('error');
  7797. this.mainDiv.addClass('error');
  7798. }
  7799.  
  7800. /**
  7801. * 设置原始数据数据
  7802. * @param {Object} Object 原始数据
  7803. */
  7804. setRawData(Object) {
  7805. this.mainDivState.rawDataHTML = $("<pre>").text(JSON.stringify(Object, null, 4)).get(0);
  7806. if (this.mainDivState.current === 'rawDataHTML') {
  7807. this.renderMainDiv();
  7808. }
  7809. }
  7810.  
  7811. /**
  7812. * 切换结果面板与原始数据面板
  7813. */
  7814. switchMainDiv() {
  7815. // 在切换之前,保存当前内容的状态
  7816. this.mainDivState[this.mainDivState.current] = this.mainDiv.html();
  7817. // 切换当前状态
  7818. this.debugButton.setButtonState(this.mainDivState.current === 'transHTML' ? 'enabled' : 'initial');
  7819. this.mainDivState.current = this.mainDivState.current === 'transHTML' ? 'rawDataHTML' : 'transHTML';
  7820. // 渲染新的当前状态
  7821. this.renderMainDiv();
  7822. }
  7823.  
  7824. // 渲染当前内容到 mainDiv
  7825. renderMainDiv() {
  7826. requestAnimationFrame(() => {
  7827. this.mainDiv.html(this.mainDivState[this.mainDivState.current]);
  7828. });
  7829. }
  7830.  
  7831. /**
  7832. * 注册debug按钮事件
  7833. */
  7834. registerDebugButtonEvent() {
  7835. this.debugButton.on("click", () => {
  7836. this.switchMainDiv();
  7837. });
  7838. }
  7839.  
  7840. /**
  7841. * 显示debug按钮
  7842. */
  7843. showDebugButton() {
  7844. this.debugButton.show();
  7845. this.registerDebugButtonEvent();
  7846. }
  7847.  
  7848. /**
  7849. * 注册查询余额按钮事件
  7850. * @param {function} callback 查询回调函数
  7851. */
  7852. registerQueryBalanceButtonEvent(callback) {
  7853. this.queryBalanceButton.on("click", async () => {
  7854. this.queryBalanceButton.setButtonState('loading', i18next.t('queryBalance.loading', { ns: 'button' }));
  7855. try {
  7856. const balance = await callback();
  7857. this.queryBalanceButton.setButtonState('success', `${i18next.t('queryBalance.success', { ns: 'button' })} ${balance}`);
  7858. } catch (error) {
  7859. this.queryBalanceButton.setButtonState('error', `${i18next.t('queryBalance.error', { ns: 'button' })} ${error.message}`);
  7860. }
  7861. });
  7862. }
  7863.  
  7864. /**
  7865. * 显示余额查询按钮
  7866. * @param {string} server 服务名称
  7867. */
  7868. showQueryBalanceButton(server) {
  7869. if (server == 'deepl') {
  7870. const quotaConfig = OJBetter.deepl.config.quota;
  7871. if (quotaConfig.url && quotaConfig.surplus && quotaConfig.header) {
  7872. this.queryBalanceButton.show();
  7873. this.registerQueryBalanceButtonEvent(() => {
  7874. return queryServerBalance(OJBetter.deepl.config.quota);
  7875. });
  7876. }
  7877. } else if (server == 'openai') {
  7878. const quotaConfig = OJBetter.chatgpt.config.quota;
  7879. if (quotaConfig.url && quotaConfig.surplus && quotaConfig.header) {
  7880. this.queryBalanceButton.show();
  7881. this.registerQueryBalanceButtonEvent(() => {
  7882. return queryServerBalance(OJBetter.chatgpt.config.quota);
  7883. });
  7884. }
  7885. }
  7886. }
  7887. }
  7888.  
  7889. // 元素关系树
  7890. class ElementsTree {
  7891. constructor(elements) {
  7892. this.node = [];
  7893. this.transResultMap = {};
  7894. this.index = 0;
  7895. // this.tagNames = ["DIV", "P", "UL", "LI"]
  7896. this.tagNames = ["DIV", "P", "UL", "LI", "SECTION", "SPAN"]
  7897. this.init($(elements));
  7898. }
  7899.  
  7900. // Iterate through all elements, because there may be multiple ttypography
  7901. init(elements) {
  7902. elements.each((i, e) => {
  7903. this.node.push({}); // add one element
  7904. this.index = 0; // reset index
  7905. this.create(i, $(e));
  7906. });
  7907. }
  7908.  
  7909. // 刷新关系树
  7910. refreshNode(elements) {
  7911. this.node = [];
  7912. this.index = 0;
  7913. this.init($(elements));
  7914. }
  7915.  
  7916. // 创建节点间的关系树
  7917. create(i_, element) {
  7918. var prev = null;
  7919. var node = this.node[i_];
  7920. element.children().each((i, e) => {
  7921. // only add element with tagNames
  7922. if (this.tagNames.includes($(e).prop("tagName"))) {
  7923. prev = this.addNode(i_, prev, e);
  7924. }
  7925. // recursively child element
  7926. if ($(e).children().length > 0 && prev !== null) {
  7927. node[prev].firstChild = this.index;
  7928. this.create(i_, $(e));
  7929. }
  7930. });
  7931. }
  7932.  
  7933. // 向树中添加一个节点
  7934. addNode(i_, prev, e) {
  7935. let node = this.node[i_];
  7936. node[this.index] = {
  7937. prev: prev,
  7938. next: null,
  7939. firstChild: null,
  7940. type: $(e).prop("tagName"),
  7941. isTranslateDiv: $(e).hasClass("translateDiv"),
  7942. topText: $(e).attr("data-topText"),
  7943. id: $(e).attr("id"),
  7944. };
  7945.  
  7946. if (prev !== null) {
  7947. node[prev].next = this.index;
  7948. }
  7949.  
  7950. prev = this.index;
  7951.  
  7952. this.index++;
  7953. return prev;
  7954. }
  7955.  
  7956. getNodeData() {
  7957. return this.node;
  7958. }
  7959.  
  7960. setNodeData(node) {
  7961. this.node = node;
  7962. }
  7963.  
  7964. getTransResultMap() {
  7965. return this.transResultMap;
  7966. }
  7967.  
  7968. setTransResultMap(transResultMap) {
  7969. this.transResultMap = transResultMap;
  7970. }
  7971.  
  7972. rmTransResultMap(id) {
  7973. delete this.transResultMap[id];
  7974. }
  7975.  
  7976. addTransResultMap(id, text) {
  7977. this.transResultMap[id] = text;
  7978. }
  7979.  
  7980. getTranslateDivNum(ttTree) {
  7981. var num = 0;
  7982. for (var i in ttTree) {
  7983. if (ttTree[i].isTranslateDiv) {
  7984. num++;
  7985. }
  7986. }
  7987. return num;
  7988. }
  7989.  
  7990. // 恢复目标元素中的translateDiv
  7991. recover(elements) {
  7992. elements.each((i, e) => {
  7993. var ttTreeNode = this.node[i];
  7994. var missingTranslateDivs = this.getTranslateDivNum(ttTreeNode);
  7995. if (missingTranslateDivs > 0) {
  7996. this.recoverOneElement($(e), ttTreeNode);
  7997. }
  7998. });
  7999. }
  8000.  
  8001. recoverOneElement(element, ttTreeNode) {
  8002. this.recoverOneFork(element.children().eq(0), ttTreeNode, 0);
  8003. }
  8004.  
  8005. // 恢复一个分支
  8006. recoverOneFork(pElement, ttTreeNode, index) {
  8007. do {
  8008. // only recover element with tagNames
  8009. if (!this.tagNames.includes(pElement.prop("tagName"))) {
  8010. if (pElement.next().length > 0) {
  8011. pElement = pElement.next();
  8012. } else {
  8013. return;
  8014. }
  8015. }
  8016. if (!ttTreeNode[index] || pElement.prop("tagName") !== ttTreeNode[index].type) {
  8017. // console.warn(`元素不存在或类型不同, 元素结构可能已经发生了变化: \nindex: ${index}`, pElement);
  8018. return;
  8019. } else {
  8020. // recursively child element
  8021. var node = ttTreeNode[index];
  8022. if (node.firstChild !== null) {
  8023. this.recoverOneFork(
  8024. pElement.children().eq(0),
  8025. ttTreeNode,
  8026. node.firstChild
  8027. );
  8028. }
  8029. // check if next node is translateDiv
  8030. if (node.next !== null) {
  8031. index = node.next;
  8032.  
  8033. var ne_node = ttTreeNode[index];
  8034. if (ne_node.isTranslateDiv) {
  8035. var id = ne_node.id;
  8036. var topText = ne_node.topText;
  8037. var text = this.transResultMap[id];
  8038. // create element after pElement
  8039. this.reCreateTransDiv(pElement, id, text, topText);
  8040. }
  8041. pElement = pElement.next(); // go to next element
  8042. }
  8043. }
  8044. } while (node.next !== null);
  8045. }
  8046.  
  8047. // 重新创建translateDiv
  8048. reCreateTransDiv(pElement, id, translatedText, topText) {
  8049. const translateDiv = new TranslateDiv(id);
  8050. pElement.after(translateDiv.getDiv());
  8051. translateDiv.setTopText(topText);
  8052. translateDiv.registerUpButtonEvent();
  8053. translateDiv.registerCloseButtonEvent();
  8054. if (!OJBetter.typeOfPage.is_oldLatex && !OJBetter.typeOfPage.is_acmsguru) {
  8055. translateDiv.registerCopyButtonEvent(translatedText);
  8056. } else {
  8057. translateDiv.disableCopyButton();
  8058. }
  8059. translateDiv.updateTranslateDiv(translatedText, !(OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru));
  8060. // 标记已翻译并添加到翻译按钮的结果栈中
  8061. let transButton = pElement.prev('.html2md-panel').find('.translateButton');
  8062. if (transButton.length == 0) {
  8063. // 如果没有找到,则应该是得在父元素中找到
  8064. transButton = pElement.parent().prev('.html2md-panel').find('.translateButton');
  8065. }
  8066. transButton.pushResultToTransButton({
  8067. translateDiv: translateDiv,
  8068. status: 0
  8069. });
  8070. transButton.setTransButtonState('success');
  8071. }
  8072. }
  8073.  
  8074. // 更新TransDB中的翻译数据
  8075. async function updateTransDBData(nodeDate, transResultMap) {
  8076. var url = window.location.href.replace(/#/, "");
  8077. try {
  8078. await OJBetter.common.database.translateData.put({ url, transResultMap, nodeDate });
  8079. return 'translateData saved successfully';
  8080. } catch (error) {
  8081. throw new Error(`Failed to save translateData: ${error}`);
  8082. }
  8083. }
  8084.  
  8085. // 获取TransDB中保存的翻译数据
  8086. async function getTransDBData() {
  8087. var url = window.location.href.replace(/#/, "");
  8088. try {
  8089. const result = await OJBetter.common.database.translateData.get(url);
  8090. return result;
  8091. } catch (error) {
  8092. throw new Error(`Failed to get translateData: ${error}`);
  8093. }
  8094. }
  8095.  
  8096. /**
  8097. * 翻译结果恢复功能初始化
  8098. * @returns
  8099. */
  8100. async function initTransResultsRecover() {
  8101. OJBetter.translation.memory.ttTree = new ElementsTree("#task-statement"); // 初始化当前页面#task-statement元素的结构树
  8102. let result = await getTransDBData();
  8103. if (!result) return;
  8104. OJBetter.translation.memory.ttTree.setNodeData(result.nodeDate);
  8105. OJBetter.translation.memory.ttTree.setTransResultMap(result.transResultMap);
  8106. OJBetter.translation.memory.ttTree.recover($("#task-statement"));
  8107. }
  8108.  
  8109. /**
  8110. * 自动翻译
  8111. */
  8112. async function initTransWhenViewable() {
  8113. await waitForMathJaxIdle();
  8114.  
  8115. // const elements = $('.ttypography, .comments').find('.translateButton');
  8116. const elements = $('#task-statement').find('.translateButton');
  8117. const observers = [];
  8118.  
  8119. // Use a single Intersection Observer for all elements
  8120. const observer = new IntersectionObserver((entries, obs) => {
  8121. entries.forEach((entry) => {
  8122. if (entry.isIntersecting) {
  8123. const button = $(entry.target);
  8124. const state = button.getButtonState();
  8125. const notAutoTranslate = button.getNotAutoTranslate();
  8126. // Check if the button meets the criteria
  8127. if (state === 'normal' && !notAutoTranslate) {
  8128. let trans = OJBetter.translation.choice;
  8129.  
  8130. if (OJBetter.translation.auto.mixTrans.enabled && button.IsCommentButton() && OJBetter.translation.auto.mixTrans.servers.length > 0) {
  8131. const randomIndex = Math.floor(Math.random() * OJBetter.translation.auto.mixTrans.servers.length);
  8132. trans = OJBetter.translation.auto.mixTrans.servers[randomIndex];
  8133. }
  8134. button.data("translatedItBy")(trans);
  8135. }
  8136.  
  8137. // Stop observing the element
  8138. obs.unobserve(entry.target);
  8139. }
  8140. });
  8141. });
  8142.  
  8143. // Observe each element
  8144. elements.each((i, e) => {
  8145. observer.observe(e);
  8146. });
  8147.  
  8148. // Store the observer in case you need to disconnect it later
  8149. observers.push(observer);
  8150. }
  8151.  
  8152. /**
  8153. * 翻译返回结果结构体
  8154. * @typedef {Object} TranslateResult
  8155. * @property {string} status 翻译状态
  8156. * @property {TranslateDiv} translateDiv 翻译结果面板
  8157. * @property {TransRawData} rawData 原始翻译数据
  8158. */
  8159.  
  8160. /**
  8161. * 翻译主方法
  8162. * @param {string} text 待翻译文本
  8163. * @param {HTMLElement} element_node 元素节点
  8164. * @param {Boolean} is_comment 是否为评论区文本
  8165. * @param {string} overrideTrans 覆盖全局翻译服务设定
  8166. * @returns {TranslateResult} 翻译结果对象
  8167. */
  8168. async function translateProblemStatement(text, element_node, is_comment, overrideTrans) {
  8169. /** @type {number} 翻译结果的ID*/
  8170. const id = OJB_getRandomNumber(8);
  8171. /** @type {TextBlockReplacer} 文本块替换/恢复实例*/
  8172. const textBlockReplacer = new TextBlockReplacer();
  8173. /** @type {string} 翻译结果文本*/
  8174. let translatedText = "";
  8175.  
  8176. /** @type {string} 当前实际应用的翻译服务 */
  8177. const realTransServer = overrideTrans ||
  8178. (is_comment && OJBetter.translation.comment.choice != "0" ?
  8179. OJBetter.translation.comment.choice :
  8180. OJBetter.translation.choice);
  8181.  
  8182. /** @type {TranslateResult} 翻译结果对象 */
  8183. const translateResult = {
  8184. status: "ok",
  8185. rawData: {
  8186. done: false
  8187. }
  8188. }
  8189.  
  8190. /**
  8191. * LaTeX替换
  8192. * @param {string} text 待翻译文本
  8193. * @returns {string} 处理后的文本
  8194. */
  8195. const replaceLatex = function (text) {
  8196. if (OJBetter.typeOfPage.is_oldLatex) {
  8197. const regex = /<span\s+class="tex-span">.*?<\/span>/gi;
  8198. text = textBlockReplacer.replace(text, regex);
  8199. text = text.replace(/<p>(.*?)<\/p>/g, "$1\n\n"); // <p/>标签换为换行
  8200. } else if (OJBetter.typeOfPage.is_acmsguru) {
  8201. const regex = /<i>.*?<\/i>|<sub>.*?<\/sub>|<sup>.*?<\/sup>|<pre>.*?<\/pre>/gi;
  8202. text = textBlockReplacer.replace(text, regex);
  8203. } else if (realTransServer != "openai") {
  8204. // 使用GPT翻译时不必替换latex公式
  8205. const regex = /\$\$(\\.|[^\$])*?\$\$|\$(\\.|[^\$])*?\$/g;
  8206. text = textBlockReplacer.replace(text, regex);
  8207.  
  8208. // 替换行间代码块```
  8209. const regex2 = /```[\s\S]*?```/g;
  8210. text = textBlockReplacer.replace(text, regex2);
  8211. }
  8212. return text;
  8213. }
  8214.  
  8215. /**
  8216. * LaTeX恢复
  8217. * @param {string} text 已翻译的文本
  8218. * @returns {string} 恢复后的文本
  8219. */
  8220. const recoverLatex = function (text) {
  8221. // 两个公式之间加个空格,防止有些LaTeX解析器解析错误
  8222. let resultText = text
  8223. .replace(/】【/g, '】 【')
  8224. .replace(/\]\[/g, '] [')
  8225. .replace(/\}\{/g, '} {');
  8226.  
  8227. if (OJBetter.typeOfPage.is_oldLatex) {
  8228. resultText = resultText.replace(/(.+?)(\n\n|$)/g, "<p>$1</p>"); // 换行符还原为<p/>标签
  8229. resultText = textBlockReplacer.recover(resultText);
  8230. } else if (OJBetter.typeOfPage.is_acmsguru) {
  8231. resultText = textBlockReplacer.recover(resultText);
  8232. } else if (realTransServer != "openai") {
  8233. resultText = textBlockReplacer.recover(resultText);
  8234. }
  8235. return resultText;
  8236. }
  8237.  
  8238. /**
  8239. * 格式化翻译结果
  8240. * @param {string} text
  8241. * @returns {string} 处理后的翻译结果
  8242. */
  8243. const formatText = function (text) {
  8244. // 转义LaTex中的特殊符号
  8245. if (!OJBetter.typeOfPage.is_oldLatex && !OJBetter.typeOfPage.is_acmsguru) {
  8246.  
  8247. // 先替换掉行间代码块
  8248. const replacer = new TextBlockReplacer();
  8249. text = replacer.replace(text, /```[\s\S]*?```/g);
  8250.  
  8251. // 处理LaTeX公式
  8252. const escapeRules = [
  8253. { pattern: /(?<!\\)>(?!\s)/g, replacement: " &gt; " }, // >符号
  8254. { pattern: /(?<!\\)</g, replacement: " &lt; " }, // <符号
  8255. { pattern: /(?<!\\)\*/g, replacement: " &#42; " }, // *符号
  8256. { pattern: /(?<!\\)_/g, replacement: " &#95; " }, // _符号
  8257. { pattern: /(?<!\\)\\\\(?=\s)/g, replacement: "\\\\\\\\" }, // \\符号
  8258. { pattern: /(?<!\\)\\(?![\\a-zA-Z0-9])/g, replacement: "\\\\" }, // \符号
  8259. ];
  8260.  
  8261. let latexMatches = [...text.matchAll(/\$\$([\s\S]*?)\$\$|\$(.*?)\$|\$([\s\S]*?)\$/g)];
  8262. for (const match of latexMatches) {
  8263. const matchedText = match[0];
  8264. let escapedText = matchedText;
  8265.  
  8266. for (const rule of escapeRules) {
  8267. escapedText = escapedText.replaceAll(rule.pattern, rule.replacement);
  8268. }
  8269. escapedText = escapedText.replace(/\$\$/g, "$$$$$$$$");// $$符号(因为后面需要作为replacement,双倍消耗)
  8270. text = text.replace(matchedText, escapedText);
  8271. }
  8272.  
  8273. // 恢复行间代码块
  8274. text = replacer.recover(text);
  8275. }
  8276.  
  8277. // // 使符合mathjx的转换语法
  8278. // const mathjaxRuleMap = [
  8279. // { pattern: /\$/g, replacement: "$$$$$$" }, // $$ 行间
  8280. // ];
  8281. // mathjaxRuleMap.forEach(({ pattern, replacement }) => {
  8282. // text = text.replace(pattern, replacement);
  8283. // });
  8284.  
  8285. // markdown修正
  8286. const mdRuleMap = [
  8287. { pattern: /(\s_[\u4e00-\u9fa5]+_)([\u4e00-\u9fa5]+)/g, replacement: "$1 $2" }, // 斜体
  8288. { pattern: /(_[\u4e00-\u9fa5]+_\s)([\u4e00-\u9fa5]+)/g, replacement: " $1$2" },
  8289. { pattern: /(_[\u4e00-\u9fa5]+_)([\u4e00-\u9fa5]+)/g, replacement: " $1 $2" },
  8290. { pattern: /(([\s\S]*?))/g, replacement: "($1)" }, // 中文()
  8291. // { pattern: /:/g, replacement: ":" }, // 中文:
  8292. { pattern: /\*\* (.*?) \*\*/g, replacement: "\*\*$1\*\*" } // 加粗
  8293. ];
  8294. mdRuleMap.forEach(({ pattern, replacement }) => {
  8295. text = text.replace(pattern, replacement);
  8296. });
  8297.  
  8298. return text;
  8299. }
  8300.  
  8301. // 创建翻译结果元素并放在element_node的后面
  8302. translateResult.translateDiv = new TranslateDiv(id);
  8303. $(element_node).after(translateResult.translateDiv.getDiv());
  8304.  
  8305. // 顶栏左侧信息
  8306. translateResult.translateDiv.setTopText(i18next.t('servers.' + realTransServer, { ns: 'translator' }) +
  8307. i18next.t('translateDiv.topTextSuffix', { ns: 'translator' }));
  8308.  
  8309. // 注册按钮
  8310. translateResult.translateDiv.registerUpButtonEvent();
  8311. translateResult.translateDiv.registerCloseButtonEvent();
  8312. if (OJBetter.translation.choice == 'openai' || OJBetter.translation.choice == 'deepl') {
  8313. translateResult.translateDiv.showQueryBalanceButton(OJBetter.translation.choice); // 显示额度查询
  8314. }
  8315.  
  8316. // 翻译内容是否可能为代码片段
  8317. if (isLikelyCodeSnippet(text)) {
  8318. const shouldContinue = await OJB_createDialog(
  8319. i18next.t('isLikelyCodeSnippet.title', { ns: 'dialog' }),
  8320. i18next.t('isLikelyCodeSnippet.content', { ns: 'dialog' }),
  8321. [
  8322. i18next.t('isLikelyCodeSnippet.buttons.0', { ns: 'dialog' }),
  8323. i18next.t('isLikelyCodeSnippet.buttons.1', { ns: 'dialog' })
  8324. ],
  8325. true
  8326. );
  8327. if (shouldContinue) {
  8328. translateResult.status = "skip";
  8329. return translateResult;
  8330. }
  8331. }
  8332.  
  8333. // 替换latex公式
  8334. text = replaceLatex(text);
  8335.  
  8336. // 过滤**号
  8337. if (OJBetter.translation.filterTextWithoutEmphasis && GM_getValue("translation") !== "openai") { // TODO
  8338. text = text.replace(/\*\*/g, "");
  8339. }
  8340.  
  8341. // 字符数上限
  8342. const translationLimits = {
  8343. deepl: 5000,
  8344. iflyrec: 2000,
  8345. youdao: 600,
  8346. google: 5000,
  8347. caiyun: 5000
  8348. };
  8349. if (translationLimits.hasOwnProperty(realTransServer) && text.length > translationLimits[realTransServer]) {
  8350. let textLength = translationLimits[realTransServer];
  8351. let realTextLength = text.length;
  8352. const shouldContinue = await OJB_createDialog(
  8353. i18next.t('transTextLimits.title', { ns: 'dialog' }),
  8354. i18next.t('transTextLimits.content', { ns: 'dialog', textLength: textLength, realTextLength: realTextLength }),
  8355. [
  8356. i18next.t('transTextLimits.buttons.0', { ns: 'dialog' }),
  8357. i18next.t('transTextLimits.buttons.1', { ns: 'dialog' })
  8358. ],
  8359. true
  8360. ); // 字数超限确认
  8361. if (shouldContinue) {
  8362. translateResult.status = "skip";
  8363. return translateResult;
  8364. }
  8365. }
  8366.  
  8367. /**
  8368. * 调用各个翻译服务
  8369. * @param {string} transServer 翻译服务
  8370. * @returns {TransRawData} 原始翻译数据
  8371. */
  8372. async function translate(transServer) {
  8373. const is_renderLaTeX = !(OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru);
  8374. const servername = i18next.t('servers.' + realTransServer, { ns: 'translator' });
  8375. /** @type {TransRawData} 原始翻译数据*/
  8376. let rawData = {};
  8377. try {
  8378. if (transServer == "deepl") {
  8379. if (OJBetter.deepl.config.type == 'free') {
  8380. translateResult.translateDiv.updateTranslateDiv(`${i18next.t('transingTip.basic', { ns: 'translator', server: servername })}`, is_renderLaTeX);
  8381. rawData = await translate_deepl(text);
  8382. } else if (OJBetter.deepl.config.type == 'api') {
  8383. translateResult.translateDiv.updateTranslateDiv(`${i18next.t('transingTip.deeplApi', { ns: 'translator', deepl_configName: OJBetter.deepl.config.name })}`, is_renderLaTeX);
  8384. if (OJBetter.deepl.config.apiGenre == 'deeplx') {
  8385. rawData = await translate_deeplx(text);
  8386. } else {
  8387. if (OJBetter.deepl.enableEmphasisProtection) text = convertBoldMarkdownToHTML(text);
  8388. if (OJBetter.deepl.enableLinkProtection) text = convertLinksMarkdownToHTML(text);
  8389. if (OJBetter.deepl.config.apiGenre == 'api-free') {
  8390. rawData = await translate_deepl_api_free(text);
  8391. } else if (OJBetter.deepl.config.apiGenre == 'api-pro') {
  8392. rawData = await translate_deepl_api_pro(text);
  8393. }
  8394. if (OJBetter.deepl.enableEmphasisProtection) rawData.text = convertBoldHTMLToMarkdown(rawData.text);
  8395. if (OJBetter.deepl.enableLinkProtection) rawData.text = convertLinksHTMLToMarkdown(rawData.text);
  8396. }
  8397. }
  8398. } else if (transServer == "iflyrec") {
  8399. translateResult.translateDiv.updateTranslateDiv(`${i18next.t('transingTip.basic', { ns: 'translator', server: servername })}`, is_renderLaTeX);
  8400. rawData = await translate_iflyrec(text);
  8401. } else if (transServer == "youdao") {
  8402. translateResult.translateDiv.updateTranslateDiv(`${i18next.t('transingTip.basic', { ns: 'translator', server: servername })}`, is_renderLaTeX);
  8403. rawData = await translate_youdao_mobile(text);
  8404. } else if (transServer == "google") {
  8405. translateResult.translateDiv.updateTranslateDiv(`${i18next.t('transingTip.basic', { ns: 'translator', server: servername })}`, is_renderLaTeX);
  8406. rawData = await translate_gg(text);
  8407. } else if (transServer == "caiyun") {
  8408. translateResult.translateDiv.updateTranslateDiv(`${i18next.t('transingTip.basic', { ns: 'translator', server: servername })}`, is_renderLaTeX);
  8409. rawData = await translate_caiyun(text);
  8410. } else if (transServer == "openai") {
  8411. translateResult.translateDiv.updateTranslateDiv(`${i18next.t('transingTip.openai', { ns: 'translator', openai_name: OJBetter.chatgpt.config.name })}${!OJBetter.chatgpt.isStream
  8412. ? i18next.t('transingTip.openai_isStream', { ns: 'translator' }) : ""}`,
  8413. is_renderLaTeX);
  8414. if (OJBetter.chatgpt.isStream) {
  8415. // 流式传输
  8416. rawData = await translate_openai_stream(text, translateResult.translateDiv);
  8417. } else {
  8418. // 普通模式
  8419. rawData = await translate_openai(text);
  8420. }
  8421. }
  8422. translatedText = rawData.text;
  8423. if (!rawData.done) {
  8424. translateResult.status = "error";
  8425. }
  8426. } catch (e) {
  8427. translateResult.status = "error";
  8428. rawData.message = i18next.t('error.unexpected', { ns: 'translator' });
  8429. console.warn(e);
  8430. }
  8431. return rawData;
  8432. }
  8433. translateResult.rawData = await translate(realTransServer);
  8434.  
  8435. if (translateResult.status == "error") {
  8436. translateResult.translateDiv.updateTranslateDiv(translateResult.rawData.message);
  8437. return translateResult;
  8438. }
  8439.  
  8440. // 还原latex公式
  8441. translatedText = recoverLatex(translatedText);
  8442.  
  8443. // 注册结果复制按钮
  8444. if (!OJBetter.typeOfPage.is_oldLatex && !OJBetter.typeOfPage.is_acmsguru) {
  8445. translateResult.translateDiv.registerCopyButtonEvent(translatedText);
  8446. } else {
  8447. translateResult.translateDiv.disableCopyButton();
  8448. }
  8449.  
  8450. // 翻译结果格式化
  8451. translatedText = formatText(translatedText);
  8452.  
  8453. // 保存翻译结果
  8454. if ((OJBetter.typeOfPage.is_problem || OJBetter.typeOfPage.is_completeProblemset) && OJBetter.translation.memory.enabled) {
  8455. // OJBetter.translation.memory.ttTree.refreshNode(".ttypography"); // 刷新当前页面.ttypography元素的结构树实例
  8456. OJBetter.translation.memory.ttTree.refreshNode("#task-statement"); // 刷新当前页面.ttypography元素的结构树实例
  8457. OJBetter.translation.memory.ttTree.addTransResultMap(id, translatedText);
  8458. updateTransDBData(OJBetter.translation.memory.ttTree.getNodeData(), OJBetter.translation.memory.ttTree.getTransResultMap()); // 更新翻译结果到transDB
  8459. }
  8460.  
  8461. // 翻译结果面板更新
  8462. translateResult.translateDiv.updateTranslateDiv(translatedText, !(OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru));
  8463.  
  8464. return translateResult;
  8465. }
  8466.  
  8467. /**
  8468. * 题目页相关链接栏
  8469. */
  8470. class ProblemPageLinkbar {
  8471. constructor() {
  8472. this.containerElement = this.createToolbar();
  8473. this.commandInvoker = new CommandInvoker();
  8474. }
  8475.  
  8476. /**
  8477. * 创建工具栏
  8478. */
  8479. createToolbar() {
  8480. // const toolbarElement = $("<div>").attr("id", "problemToolbar").insertBefore($(".problemindexholder"));
  8481. const toolbarElement = $("<div>").attr("id", "problemToolbar").insertBefore($(".h2"));
  8482. return new DOMContainer(toolbarElement);
  8483. }
  8484.  
  8485. /**
  8486. * 添加按钮
  8487. * @param {string} id 按钮id
  8488. * @param {string} url 按钮链接
  8489. * @param {string} text 按钮文字
  8490. * @param {JQueryObject} icon 按钮图标
  8491. * @param {string} iconHeight 图标高度
  8492. * @returns {object} 按钮对象
  8493. */
  8494. addLinkButton(id, url, text, icon = $('<div>'), iconHeight = "22px") {
  8495. const linkElement = $("<a>")
  8496. .attr("href", url)
  8497. .attr("target", "_blank")
  8498. .addClass("ojb_btn")
  8499. .attr("id", id);
  8500.  
  8501. linkElement.append(icon);
  8502. icon.css("height", iconHeight);
  8503.  
  8504. const textSpan = $("<span>").html(text);
  8505. linkElement.append(textSpan);
  8506.  
  8507. this.commandInvoker.execute(new AddElementCommand(this.containerElement, linkElement));
  8508. return {
  8509. element: linkElement,
  8510. text: textSpan,
  8511. icon: icon
  8512. };
  8513. }
  8514.  
  8515. /**
  8516. * 更新链接
  8517. * @param {object} button 按钮对象
  8518. * @param {string} url 按钮链接
  8519. */
  8520. updateUrl(button, url) {
  8521. button.element.attr("href", url);
  8522. }
  8523.  
  8524. /**
  8525. * 更新文字
  8526. * @param {object} button 按钮对象
  8527. * @param {string} text 按钮文字
  8528. */
  8529. updateText(button, text) {
  8530. button.text.html(text);
  8531. }
  8532.  
  8533. /**
  8534. * 设置文字为粗体
  8535. * @param {object} button 按钮对象
  8536. */
  8537. setBold(button) {
  8538. button.text.css("font-weight", "bold");
  8539. }
  8540.  
  8541. /**
  8542. * 更新图标
  8543. * @param {object} button 按钮对象
  8544. * @param {JQueryObject} icon 按钮图标
  8545. * @param {string} iconHeight 图标高度
  8546. */
  8547. updateIcon(button, icon, iconHeight = "16px") {
  8548. button.icon.remove();
  8549. button.text.prepend(icon);
  8550. icon.css("height", iconHeight);
  8551. button.icon = icon;
  8552. }
  8553.  
  8554. /**
  8555. * 添加类
  8556. * @param {object} button 按钮对象
  8557. * @param {string} className 类名
  8558. */
  8559. addClass(button, className) {
  8560. button.element.addClass(className);
  8561. }
  8562.  
  8563. /**
  8564. * 禁用链接按钮
  8565. * @param {object} button 按钮对象
  8566. */
  8567. disableButton(button) {
  8568. button.element.addClass("disabled");
  8569. }
  8570.  
  8571. /**
  8572. * 启用链接按钮
  8573. * @param {object} button 按钮对象
  8574. */
  8575. enableButton(button) {
  8576. button.element.removeClass("disabled");
  8577. }
  8578. }
  8579.  
  8580. /**
  8581. * 获取题目的id
  8582. * @param {String} url 题目的链接
  8583. * @returns 题目的id,形如2000A
  8584. */
  8585. function getProblemId(url) {
  8586. const regex = /\/contests\/([A-Za-z\d]+)\/tasks\/([A-Za-z\d\_]+)/;
  8587. const matchResult = url.match(regex);
  8588. return matchResult && matchResult.length >= 3
  8589. ? `${matchResult[2]}`
  8590. : '';
  8591. };
  8592.  
  8593. /**
  8594. * 跳转到洛谷
  8595. * @param {ProblemPageLinkbar} problemToolbar
  8596. */
  8597. async function CF2luogu(problemToolbar) {
  8598. const url = window.location.href;
  8599. const problemId = getProblemId(url);
  8600. const luoguButton = problemToolbar.addLinkButton(
  8601. "luoguButton",
  8602. "https://www.luogu.com.cn/",
  8603. i18next.t('state.loading', { ns: 'button' }),
  8604. $("<img>").attr("src", "https://cdn.luogu.com.cn/fe/logo.png")
  8605. );
  8606.  
  8607. const checkLinkExistence = async (url) => {
  8608. return OJB_promiseRetryWrapper(async () => {
  8609. const response = await OJB_GMRequest({
  8610. method: "GET",
  8611. url
  8612. });
  8613. return !response.responseText.match(/出错了/g);
  8614. }, {
  8615. maxRetries: 3,
  8616. retryInterval: 1000
  8617. });
  8618. };
  8619.  
  8620. const LuoguUrl = `https://www.luogu.com.cn/problem/AT_${problemId}`;
  8621. try {
  8622. const result = await checkLinkExistence(LuoguUrl);
  8623. if (problemId && result) {
  8624. problemToolbar.updateText(luoguButton, "");
  8625. problemToolbar.updateUrl(luoguButton, LuoguUrl);
  8626. } else {
  8627. problemToolbar.updateText(luoguButton, i18next.t('state.404', { ns: 'button' }));
  8628. problemToolbar.disableButton(luoguButton);
  8629. }
  8630. } catch (error) {
  8631. if (error instanceof OJB_GMError && error.type == "error") {
  8632. problemToolbar.updateText(luoguButton, i18next.t('state.netError', { ns: 'button' }));
  8633. problemToolbar.disableButton(luoguButton);
  8634. }
  8635. }
  8636. }
  8637.  
  8638. /**
  8639. * 跳转到 Virtual Judge
  8640. * @param {ProblemPageLinkbar} problemToolbar
  8641. */
  8642. async function CF2vjudge(problemToolbar) {
  8643. const url = window.location.href;
  8644. const problemId = getProblemId(url);
  8645. const vjudgeButton = problemToolbar.addLinkButton(
  8646. "vjudgeButton",
  8647. "https://vjudge.net/",
  8648. i18next.t('state.loading', { ns: 'button' }),
  8649. $("<img>").attr("src", "https://aowuucdn.oss-accelerate.aliyuncs.com/vjudge.ico")
  8650. );
  8651.  
  8652. const checkLinkExistence = async (url) => {
  8653. return OJB_promiseRetryWrapper(async () => {
  8654. const response = await OJB_GMRequest({
  8655. method: "HEAD",
  8656. url: url,
  8657. });
  8658. if (response.status >= 200 && response.status < 300) return true;
  8659. else if (response.status == 404) return false;
  8660. else throw new OJB_GMError('network', 'An unknown network error occurred!', response);
  8661. }, {
  8662. maxRetries: 3,
  8663. retryInterval: 1000
  8664. });
  8665. };
  8666.  
  8667. const VjudgeUrl = `https://vjudge.net/problem/AtCoder-${problemId}`;
  8668. try {
  8669. const result = await checkLinkExistence(VjudgeUrl);
  8670. if (problemId && result) {
  8671. problemToolbar.updateText(vjudgeButton, "VJudge");
  8672. problemToolbar.updateUrl(vjudgeButton, VjudgeUrl);
  8673. } else {
  8674. problemToolbar.updateText(vjudgeButton, i18next.t('state.404', { ns: 'button' }));
  8675. problemToolbar.disableButton(vjudgeButton);
  8676. }
  8677. } catch (error) {
  8678. if (error instanceof OJB_GMError && error.type == "error") {
  8679. problemToolbar.updateText(vjudgeButton, i18next.t('state.netError', { ns: 'button' }));
  8680. problemToolbar.disableButton(vjudgeButton);
  8681. }
  8682. }
  8683. }
  8684.  
  8685. // RatingClass
  8686. const ratingClassMap = {
  8687. NaN: "rating_by_clist_colorNaN",
  8688. 0: "rating_by_clist_color0",
  8689. 1200: "rating_by_clist_color1",
  8690. 1400: "rating_by_clist_color2",
  8691. 1600: "rating_by_clist_color3",
  8692. 1900: "rating_by_clist_color4",
  8693. 2100: "rating_by_clist_color5",
  8694. 2300: "rating_by_clist_color6",
  8695. 2400: "rating_by_clist_color7",
  8696. 2600: "rating_by_clist_color8",
  8697. 3000: "rating_by_clist_color9"
  8698. };
  8699. const cssMap = {
  8700. "rating_by_clist_colorNaN": "#cccccc",
  8701. "rating_by_clist_color0": "#808080",
  8702. "rating_by_clist_color1": "#73e473",
  8703. "rating_by_clist_color2": "#77ddbb",
  8704. "rating_by_clist_color3": "#aaaaff",
  8705. "rating_by_clist_color4": "#ff88ff",
  8706. "rating_by_clist_color5": "#ffcc88",
  8707. "rating_by_clist_color6": "#ffbb55",
  8708. "rating_by_clist_color7": "#ff7777",
  8709. "rating_by_clist_color8": "#ff3333",
  8710. "rating_by_clist_color9": "#aa0000"
  8711. };
  8712. // TODO 7
  8713. /**
  8714. * clist 访问有效性检查
  8715. * @param {boolean} onlyCookie 是否只检查Cookie
  8716. * @returns {Promise<boolean>} 是否有效
  8717. */
  8718. async function validateClistConnection(onlyCookie = false) {
  8719. const clistApiUrl = "https://clist.by:443/api/v4/contest/?limit=1&resource_id=1";
  8720. const requestOptions = {
  8721. method: "GET",
  8722. url: clistApiUrl,
  8723. timeout: 5000,
  8724. };
  8725.  
  8726. // 尝试发送请求
  8727. async function tryRequest(options) {
  8728. try {
  8729. const response = await OJB_GMRequest(options);
  8730. if (response.status === 200) {
  8731. return { ok: true };
  8732. } else if (response.status === 401) {
  8733. throw new Error('unauthorized');
  8734. } else if (response.status === 404) {
  8735. throw new Error('not_found');
  8736. } else {
  8737. throw new Error('other_error');
  8738. }
  8739. } catch (error) {
  8740. console.warn(`Error accessing clist.by: ${error.message}`);
  8741. return { ok: false, error: error.message };
  8742. }
  8743. }
  8744.  
  8745. // 尝试携带Key发送请求
  8746. let result = await tryRequest(requestOptions);
  8747. if (!onlyCookie && !result.ok) {
  8748. requestOptions.headers = { "Authorization": OJBetter.clist.authorization };
  8749. result = await tryRequest(requestOptions);
  8750. }
  8751.  
  8752. // 根据结果显示错误信息
  8753. if (!result.ok) {
  8754. let errorType = result.error;
  8755. const loadingMessage = new LoadingMessage();
  8756. let state;
  8757. if (errorType === 'not_found') {
  8758. state = i18next.t('error.clist.404', { ns: 'alert' });
  8759. } else if (errorType === 'unauthorized') {
  8760. state = i18next.t('error.clist.cookie', { ns: 'alert' });
  8761. } else {
  8762. state = i18next.t('error.clist.other', { ns: 'alert' });
  8763. }
  8764. loadingMessage.updateStatus(`${OJBetter.state.name} —— ${state}`, 'error');
  8765. }
  8766. return result.ok;
  8767. }
  8768.  
  8769. /**
  8770. * 创建Rating相关css
  8771. * @param {boolean} [hasBorder=true] 是否有边框
  8772. */
  8773. function creatRatingCss(hasBorder = true) {
  8774. const defaultBorderColor = '#dcdfe6';
  8775. let dynamicCss = "";
  8776. let hoverSelector = OJBetter.clist.ratingHidden ? ":hover" : "";
  8777. for (let cssClass in cssMap) {
  8778. dynamicCss += `a.${cssClass}${hoverSelector}, a.${cssClass}${hoverSelector}:link {\n`;
  8779. let borderColor = hasBorder ? cssMap[cssClass] : defaultBorderColor;
  8780. dynamicCss += ` color: ${cssMap[cssClass]} ${OJBetter.clist.ratingHidden ? "!important" : ""};\n`;
  8781. dynamicCss += `}\n`;
  8782. }
  8783. GM_addStyle(dynamicCss);
  8784. if (OJBetter.clist.ratingHidden) {
  8785. GM_addStyle(`
  8786. #clistButton {
  8787. color: #ffffff00;
  8788. }
  8789. `);
  8790. }
  8791. }
  8792.  
  8793. /**
  8794. * 模拟clist网页访问获取rating
  8795. * @param {string} problem 题目名称
  8796. * @param {string} problem_url 题目链接
  8797. * @param {string} contest 比赛名称
  8798. * @returns {Promise<{rating: number, problem: string}>} 题目难度
  8799. */
  8800. async function getRatingFromHTML(problem, problem_url, contest = null) {
  8801. // 去除题目名称中的括号,以及首尾的空白符
  8802. problem = problem.replace(/\([\s\S]*?\)/g, '').trim();
  8803.  
  8804. return OJB_promiseRetryWrapper(async () => {
  8805. const queryString = `search=${encodeURIComponent(problem)}&resource=1`;
  8806. const response = await OJB_GMRequest({
  8807. method: 'GET',
  8808. url: `https://clist.by/problems/?${queryString}`,
  8809. });
  8810.  
  8811. if (!response.responseText) throw new OJB_GMError('network', 'An unknown network error occurred!', response);
  8812. const html = response.responseText;
  8813. const cleanedHtml = html.replace(/src=(.|\s)*?"/g, '');
  8814. const parser = new DOMParser();
  8815. const doc = parser.parseFromString(cleanedHtml, 'text/html');
  8816. const trs = doc.querySelectorAll('table tbody tr');
  8817.  
  8818. for (let tr of trs) {
  8819. const rating = tr.querySelector('.problem-rating-column').textContent.trim();
  8820. const linkElement = tr.querySelector('.problem-name-column a:nth-of-type(2)');
  8821. let link = linkElement ? OJB_cleanLink(linkElement) : null;
  8822.  
  8823. if (link === problem_url || link === problem_url + '/') {
  8824. return {
  8825. rating: parseInt(rating),
  8826. problem: problem
  8827. };
  8828. } else if (contest !== null) {
  8829. const contestTitles = [...tr.querySelectorAll('.problem-name-column .pull-right a[title], .problem-name-column .pull-right span[title]')].map(el => el.title);
  8830. if (contestTitles.includes(contest)) {
  8831. return {
  8832. rating: parseInt(rating),
  8833. problem: problem
  8834. };
  8835. }
  8836. }
  8837. }
  8838. console.warn(`No data found for the question: ${problem}`);
  8839. }, {
  8840. maxRetries: 3,
  8841. retryInterval: 500
  8842. });
  8843. }
  8844.  
  8845. /**
  8846. * 从clist API获取题目的rating
  8847. * @param {string} problem_name 题目名
  8848. * @param {string} problem_url 题目链接
  8849. * @returns {Promise<number>} 题目rating
  8850. *
  8851. * 使用两个Map对象来存储和快速访问题目信息:
  8852. * - problemsMap: 通过题目的URL作为键来存储题目信息。
  8853. * - nameMap: 通过题目的名称作为键来存储题目信息。
  8854. *
  8855. * 每个题目信息是一个对象,包含以下属性:
  8856. * @typedef {Object} ProblemInfo
  8857. * @property {string} name 题目名称
  8858. * @property {string} url 题目URL
  8859. * @property {number} rating 题目评分,如果没有评分信息则为NaN
  8860. */
  8861. async function getRatingFromApi_problem(problem_name, problem_url) {
  8862. return OJB_promiseRetryWrapper(async () => {
  8863. const response = await OJB_GMRequest({
  8864. method: "GET",
  8865. // url: `https://clist.by:443/api/v4/problem/?name=${encodeURIComponent(problem_name)}&resource__regex=codeforces.com`,
  8866. url: `https://clist.by:443/api/v4/problem/?url__regex=${encodeURIComponent(problem_name)}&resource__regex=atcoder.jp`,
  8867. headers: { "Authorization": OJBetter.clist.authorization }
  8868. });
  8869.  
  8870. if (!response.responseText) throw new OJB_GMError('network', 'An unknown network error occurred!', response);
  8871. let data = JSON.parse(response.responseText);
  8872. /**
  8873. * 使用题目的URL作为键来存储题目信息。
  8874. * @type {Map<string, ProblemInfo>}
  8875. */
  8876. let problemsMap = new Map();
  8877.  
  8878. /**
  8879. * 使用题目的名称作为键来存储题目信息。
  8880. * @type {Map<string, ProblemInfo>}
  8881. */
  8882. let nameMap = new Map();
  8883.  
  8884. data.objects.forEach(problem => {
  8885. /** @type {ProblemInfo} 题目信息*/
  8886. let problemInfo = {
  8887. name: problem.name,
  8888. url: problem.url,
  8889. rating: problem.rating ? problem.rating : NaN
  8890. };
  8891. problemsMap.set(OJB_cleanLink(problem.url), problemInfo);
  8892. nameMap.set(problem.name, problemInfo);
  8893. });
  8894.  
  8895. if (problemsMap.has(problem_url)) {
  8896. return problemsMap.get(problem_url).rating;
  8897. } else if (nameMap.has(problem_name)) {
  8898. return nameMap.get(problem_name).rating;
  8899. } else {
  8900. console.warn('Problem not found in the response');
  8901. }
  8902. }, {
  8903. maxRetries: 5,
  8904. retryInterval: 1000
  8905. });
  8906. }
  8907.  
  8908. /**
  8909. * 获取字符串中的关键词列表
  8910. * @param {string} text 字符串文本
  8911. * @returns {array<string>} 返回关键词列表
  8912. */
  8913. function getKeywords(text) {
  8914. // 定义要过滤掉的高频词
  8915. const highFrequencyWords = ['Educational', 'Codeforces', 'Round', 'Div'];
  8916.  
  8917. // 使用正则表达式替换掉特殊符号(保留空格以便分词)
  8918. const sanitizedText = text.replace(/[^\w\s]|_/g, '').replace(/\s+/g, ' ');
  8919.  
  8920. // 将字符串拆分为单词数组
  8921. const words = sanitizedText.split(' ');
  8922.  
  8923. // 过滤掉高频词和空字符串
  8924. const filteredWords = words.filter(word => {
  8925. return word && highFrequencyWords.indexOf(word) === -1;
  8926. });
  8927.  
  8928. // 返回关键词列表
  8929. return filteredWords;
  8930. }
  8931.  
  8932. /**
  8933. * 根据关键词从 Clist API 中获取实际比赛名称
  8934. * @param {string} contestName 比赛名
  8935. * @param {string} contestUrl 比赛链接
  8936. * @returns {string|null} 该比赛在Clist中的实际名字
  8937. */
  8938. async function getContestNameFromApi(contestName, contestUrl) {
  8939. return OJB_promiseRetryWrapper(async () => {
  8940. const options = {
  8941. method: "GET",
  8942. // url: `https://clist.by:443/api/v4/contest/?resource_id=1&event__regex=${encodeURIComponent(contestName)}`,
  8943. url: `https://clist.by:443/api/v4/contest/?resource_id=93&event__regex=${encodeURIComponent(contestName)}`,
  8944. headers: {
  8945. "Authorization": OJBetter.clist.authorization
  8946. }
  8947. };
  8948.  
  8949. let response = await OJB_GMRequest(options);
  8950.  
  8951. if (!response.responseText) throw new OJB_GMError('network', 'An unknown network error occurred!', response);
  8952.  
  8953. let data = JSON.parse(response.responseText);
  8954. let objects = data.objects;
  8955.  
  8956. if (objects.length > 0) {
  8957. for (const contest of objects) {
  8958. // const href = contest.href.replace(/\/contests\//i, '/contest/'); // 链接可能是contests而不是contest,换回来
  8959. const href = contest.href;
  8960. if (OJB_cleanLink(href) == contestUrl) {
  8961. return contest.event;
  8962. }
  8963. }
  8964. }
  8965. return null;
  8966. }, {
  8967. maxRetries: 5,
  8968. retryInterval: 1000
  8969. });
  8970. }
  8971.  
  8972. /**
  8973. * 获取在clist中的实际比赛名称
  8974. * @param {string} contestName 待搜索的比赛名称
  8975. * @param {string} contestUrl 比赛的url
  8976. * @returns {Promise<string|null>} 在clist中的实际比赛名称,如果没有找到,则返回null
  8977. */
  8978. async function getActualContestName(contestName, contestUrl) {
  8979. // 首先尝试使用完整的比赛名称进行搜索
  8980. let actualContestName = await getContestNameFromApi(contestName, contestUrl);
  8981. if (actualContestName) {
  8982. return actualContestName;
  8983. }
  8984.  
  8985. // 如果使用完整名称没有找到,则尝试使用关键词进行搜索
  8986. const keywords = getKeywords(contestName);
  8987. const maxKeywordAttempts = 1; // 最多尝试到第几个关键词(因为Clist API有频率限制)
  8988. for (let i = 0; i < Math.min(keywords.length, maxKeywordAttempts); i++) {
  8989. actualContestName = await getContestNameFromApi(keywords[i], contestUrl);
  8990. if (actualContestName) {
  8991. return actualContestName;
  8992. }
  8993. }
  8994.  
  8995. // 如果全部尝试后仍没有找到,返回null
  8996. return null;
  8997. }
  8998.  
  8999. /**
  9000. * 从clist API获取比赛题目集的rating
  9001. * @param {string} contestName 比赛名
  9002. * @returns {Promise<Map<string, number>>} 题目rating
  9003. */
  9004. async function getRatingFromApi_contest(contestName, contestUrl) {
  9005. const actualContestName = await getActualContestName(contestName, contestUrl);
  9006. return OJB_promiseRetryWrapper(async () => {
  9007. const options = {
  9008. method: "GET",
  9009. url: `https://clist.by:443/api/v4/contest/?resource_id=93&with_problems=true&event=${encodeURIComponent(actualContestName)}`,
  9010. headers: {
  9011. "Authorization": OJBetter.clist.authorization
  9012. }
  9013. };
  9014.  
  9015. let response = await OJB_GMRequest(options);
  9016.  
  9017. if (!response.responseText) throw new OJB_GMError('network', 'An unknown network error occurred!', response);
  9018.  
  9019. let data = JSON.parse(response.responseText);
  9020. let objects = data.objects;
  9021. let problemsMap = new Map();
  9022.  
  9023. if (objects.length > 0 && objects[0].problems) {
  9024. objects[0].problems.forEach(problem => {
  9025. problemsMap.set(OJB_cleanLink(problem.url), problem.rating ? problem.rating : NaN);
  9026. });
  9027. }
  9028.  
  9029. return problemsMap;
  9030. }, {
  9031. maxRetries: 5,
  9032. retryInterval: 1000
  9033. });
  9034. }
  9035.  
  9036. /**
  9037. * 根据rating获取对应的颜色class名
  9038. * @param {number} rating 题目rating
  9039. * @returns {string} 颜色class名
  9040. */
  9041. function getClassNameByRating(rating) {
  9042. let className = "rating_by_clist_color9";
  9043. if (Number.isNaN(rating)) {
  9044. className = "rating_by_clist_colorNaN";
  9045. } else {
  9046. let keys = Object.keys(ratingClassMap);
  9047. for (let i = 0; i < keys.length; i++) {
  9048. if (rating < keys[i]) {
  9049. className = ratingClassMap[keys[i - 1]];
  9050. break;
  9051. }
  9052. }
  9053. }
  9054. return className;
  9055. }
  9056.  
  9057. /**
  9058. * problem题目页显示Rating
  9059. * @param {ProblemPageLinkbar} problemToolbar
  9060. * @returns {Promise<void>}
  9061. */
  9062. async function showRatingByClist_problem(problemToolbar) {
  9063. // 题目名
  9064. // const problem = $('.header .title').eq(0).text().replace(/[\s\S]*?. /, '');
  9065. // if (OJBetter.typeOfPage.is_acmsguru) problem = $('h4').eq(0).text().replace(/[\s\S]*?. /, '');
  9066. const url = window.location.href;
  9067. const problemId = getProblemId(url);
  9068.  
  9069. // 创建Rating按钮元素
  9070. creatRatingCss(false);
  9071. // TODO
  9072. // const clistButton = problemToolbar.addLinkButton(
  9073. // 'clistButton',
  9074. // `https://clist.by/problems/?search=${problem}&resource=1`,
  9075. // i18next.t('state.wait', { ns: 'button' }),
  9076. // $("<img>").attr("src", "https://clist.by/static/img/logo-48.png"),
  9077. // "15px"
  9078. // );
  9079. const clistButton = problemToolbar.addLinkButton(
  9080. 'clistButton',
  9081. `https://clist.by/problems/?search=${problemId}&resource=93`,
  9082. i18next.t('state.wait', { ns: 'button' }),
  9083. $("<img>").attr("src", "https://clist.by/static/img/logo-48.png"),
  9084. "15px"
  9085. );
  9086.  
  9087. // 检测clist连接
  9088. if (!await validateClistConnection()) {
  9089. problemToolbar.updateText(clistButton, i18next.t('state.netError', { ns: 'button' }));
  9090. return;
  9091. }
  9092.  
  9093. // 题目链接
  9094. let problem_url = window.location.href;
  9095. if (problem_url.includes('/contest/')) {
  9096. problem_url = problem_url.replace(/\/contest\/(\d+)\/problem\/(\w+)[^\w]*/, '/contest/$1/problem/$2');
  9097. } else {
  9098. problem_url = problem_url.replace(/\/problemset\/problem\/(\d+)\/(\w+)/, '/contest/$1/problem/$2');
  9099. }
  9100. if (OJBetter.typeOfPage.is_mSite) problem_url = problem_url.replace(/\/\/(\w+).codeforces.com/, '//codeforces.com'); // 轻量站
  9101.  
  9102. // 比赛名
  9103. // let contest = $('#sidebar').children().first().find('.rtable th').first().text();
  9104.  
  9105. // rating
  9106. problemToolbar.updateText(clistButton, i18next.t('state.loading', { ns: 'button' }));
  9107. let rating = await getRatingFromApi_problem(problemId, problem_url);
  9108. if (rating) {
  9109. let className = getClassNameByRating(rating);
  9110. problemToolbar.updateText(clistButton, rating);
  9111. problemToolbar.setBold(clistButton);
  9112. problemToolbar.addClass(clistButton, className);
  9113. } else {
  9114. problemToolbar.updateText(clistButton, i18next.t('state.404', { ns: 'button' }));
  9115. problemToolbar.disableButton(clistButton);
  9116. }
  9117. }
  9118.  
  9119. /**
  9120. * contest页显示Rating
  9121. * @returns {Promise<void>}
  9122. */
  9123. async function showRatingByClist_contest() {
  9124. // 创建Rating显示框
  9125. creatRatingCss();
  9126. let ratingBadges = {};
  9127. // $('.datatable .id.left').each(function () {
  9128. // let href = 'https://codeforces.com' + $(this).find('a').attr('href');
  9129. // let badge = OJB_safeCreateJQElement(`<a id="clistButton" class="ratingBadge">${i18next.t('state.wait', { ns: 'button' })}</a>`);
  9130. // $(this).find('a').after(badge);
  9131. // ratingBadges[href] = badge;
  9132. // });
  9133. $('table tbody tr').each(function () {
  9134. let href = 'https://atcoder.jp' + $(this).find('a').attr('href');
  9135. let badge = OJB_safeCreateJQElement(`<a id="clistButton" class="ratingBadge">${i18next.t('state.wait', { ns: 'button' })}</a>`);
  9136. $(this).find('a:first').after(badge);
  9137. ratingBadges[href] = badge;
  9138. });
  9139.  
  9140. // 检测clist连接
  9141. if (!await validateClistConnection()) {
  9142. for (let href in ratingBadges) {
  9143. ratingBadges[href].text('error').addClass('ratingBadge_error');
  9144. }
  9145. return;
  9146. }
  9147.  
  9148. // 显示loading
  9149. for (let href in ratingBadges) {
  9150. ratingBadges[href].text(i18next.t('state.loading', { ns: 'button' })).addClass('ratingBadge_loading');
  9151. }
  9152.  
  9153. // 获取Rating
  9154. // let contestName = $('#sidebar').children().first().find('.rtable th').first().text();
  9155. let contestName = window.location.href.match(/\/contests\/[^\/]*?(\d+)\/tasks/)?.[1];
  9156. // let contestUrl = OJB_cleanLink(window.location.href);
  9157. let contestUrl = OJB_cleanLink(window.location.href.replace(/\/tasks\/?.*$/, ''));
  9158. try {
  9159. let problemsMap = await getRatingFromApi_contest(contestName, contestUrl);
  9160.  
  9161. // 填充数据
  9162. for (let href in ratingBadges) {
  9163. if (problemsMap.has(href)) {
  9164. let rating = problemsMap.get(href);
  9165. let className = getClassNameByRating(rating);
  9166. ratingBadges[href].text(rating).addClass(className);
  9167. } else {
  9168. ratingBadges[href].text(i18next.t('state.404', { ns: 'button' })).addClass('ratingBadge_no');
  9169. }
  9170. }
  9171. } catch (error) {
  9172. // 填充数据
  9173. for (let href in ratingBadges) {
  9174. ratingBadges[href].text(i18next.t('state.netError', { ns: 'button' })).addClass('ratingBadge_no');
  9175. }
  9176. console.warn(error);
  9177. }
  9178. }
  9179.  
  9180. /**
  9181. * problemset页显示Rating
  9182. * @returns {Promise<void>}
  9183. */
  9184. async function showRatingByClist_problemset() {
  9185. creatRatingCss();
  9186. let ratingBadges = [];
  9187. const $problems = $('.problems');
  9188. const $trs = $problems.find('tbody tr:gt(0)');
  9189.  
  9190. // 先创建Rating显示框,并将关系存进数组ratingBadges
  9191. for (let i = 0; i < $trs.length; i++) {
  9192. const $tds = $($trs[i]).find('td');
  9193. const $firstDiv = $($tds[1]).find('div:first');
  9194. let problem = $firstDiv.text();
  9195. let problem_url = $firstDiv.find('a').attr('href');
  9196. problem_url = problem_url.replace(/^\/problemset\/problem\/(\d+)\/(\w+)/, 'https://codeforces.com/contest/$1/problem/$2');
  9197.  
  9198. const ratingBadge = OJB_safeCreateJQElement(`<a id="clistButton" class="ratingBadge"></a>`);
  9199. const rating = OJB_safeCreateJQElement(`<span class="rating">${i18next.t('state.wait', { ns: 'button' })}</span>`);
  9200. ratingBadge.append(rating);
  9201. $($tds[0]).find('a').after(ratingBadge);
  9202. ratingBadges.push({ ratingBadge, rating, problem, problem_url });
  9203. }
  9204.  
  9205. // 检测clist连接
  9206. if (!await validateClistConnection()) {
  9207. for (let i = 0; i < rating.length; i++) {
  9208. ratingBadges[i].rating.text(i18next.t('state.netError', { ns: 'button' }));
  9209. }
  9210. return;
  9211. }
  9212.  
  9213. // 每次只获取3个rating
  9214. for (let i = 0; i < ratingBadges.length; i += 3) {
  9215. const promises = [];
  9216. const endIndex = Math.min(i + 3, ratingBadges.length);
  9217.  
  9218. for (let j = i; j < endIndex; j++) {
  9219. const ratingBadge = ratingBadges[j];
  9220. // 显示请求中
  9221. ratingBadge.rating.text(i18next.t('state.loading', { ns: 'button' }));
  9222. promises.push(getRatingFromHTML(ratingBadge.problem, ratingBadge.problem_url).catch(error => console.warn(error)));
  9223. }
  9224.  
  9225. const results = await Promise.all(promises);
  9226.  
  9227. for (let j = i; j < endIndex; j++) {
  9228. const result = results[j - i];
  9229. const ratingBadge = ratingBadges[j];
  9230. if (result) {
  9231. let className = getClassNameByRating(result.rating);
  9232. ratingBadge.ratingBadge.addClass(className);
  9233. ratingBadge.rating.text(result.rating);
  9234. } else {
  9235. ratingBadge.rating.text(i18next.t('state.404', { ns: 'button' }));
  9236. }
  9237. }
  9238. }
  9239. }
  9240.  
  9241. /**
  9242. * 存放编辑器语言select的值与Monaco语言对应关系的map.
  9243. * @type {Object.<string, string>}
  9244. */
  9245. // const value_monacoLanguageMap = {
  9246. // "4": "pascal", "6": "php", "7": "python", "9": "csharp", "13": "perl", "20": "scala", "31": "python",
  9247. // "32": "go", "34": "javascript", "36": "java", "40": "python", "41": "python", "43": "cpp",
  9248. // "50": "cpp", "51": "pascal", "52": "cpp", "54": "cpp", "55": "javascript", "59": "cpp", "60": "java",
  9249. // "61": "cpp", "65": "csharp", "67": "ruby", "70": "python", "73": "cpp", "74": "java", "75": "rust",
  9250. // "77": "kotlin", "79": "csharp", "80": "cpp", "83": "kotlin", "87": "java"
  9251. // };
  9252. const value_monacoLanguageMap = {
  9253. "5001": "cpp", "5002": "go", "5003": "csharp", "5004": "kotlin", "5005": "java",
  9254. "5006": "nim", "5007": "text", "5008": "text", "5009": "javascript", "5010": "javascript",
  9255. "5011": "r", "5012": "d", "5013": "d", "5014": "swift", "5015": "dart",
  9256. "5016": "php", "5017": "cpp", "5018": "ruby", "5019": "crystal", "5020": "text",
  9257. "5021": "fsharp", "5022": "julia", "5023": "sh", "5024": "text", "5025": "haskell",
  9258. "5026": "fortran", "5027": "lua", "5028": "cpp", "5029": "lisp", "5030": "cobol",
  9259. "5031": "cpp", "5032": "sh", "5033": "python", "5034": "sh", "5035": "text",
  9260. "5036": "text", "5037": "perl", "5038": "sh", "5039": "text", "5040": "text",
  9261. "5041": "pascal", "5042": "csharp", "5043": "lua", "5044": "prolog", "5045": "sh",
  9262. "5046": "scheme", "5047": "scala", "5048": "vbscript", "5049": "text", "5050": "clojure",
  9263. "5051": "erlang", "5052": "typescript", "5053": "cpp", "5054": "rust", "5055": "python",
  9264. "5056": "scala", "5057": "text", "5058": "typescript", "5059": "ocaml", "5060": "raku",
  9265. "5061": "text", "5062": "lisp", "5063": "python", "5064": "clojure", "5065": "text",
  9266. "5066": "text", "5067": "text", "5068": "ada", "5069": "text", "5070": "text",
  9267. "5071": "clojure", "5072": "cpp", "5073": "cpp", "5074": "text", "5075": "lisp",
  9268. "5076": "text", "5077": "d", "5078": "python", "5079": "text", "5080": "text",
  9269. "5081": "ocaml", "5082": "python", "5083": "matlab", "5084": "haxe", "5085": "elixir",
  9270. "5086": "text", "5087": "text", "5088": "lisp", "5089": "text", "5090": "cobol"
  9271. };
  9272.  
  9273. /**
  9274. * 更新代码提交页的HTML
  9275. * @param {string} submitUrl 提交页面的URL
  9276. * @param {string} cacheKey 本地缓存的键名
  9277. * @returns {Promise<jQuery<HTMLElement>>} 返回 jQuery 包装的 HTML 元素
  9278. */
  9279. async function CloneOriginalHTML(submitUrl, cacheKey) {
  9280. return OJB_promiseRetryWrapper(async () => {
  9281. const response = await OJB_GMRequest({
  9282. method: 'GET',
  9283. url: submitUrl
  9284. });
  9285. const html = response.responseText;
  9286. const parser = new DOMParser();
  9287. const doc = parser.parseFromString(html, 'text/html');
  9288. const cloneHTML = $(doc.body).html();
  9289. localStorage.setItem(cacheKey, html);
  9290. return $(cloneHTML);
  9291. }, {
  9292. maxRetries: 5,
  9293. retryInterval: 1000,
  9294. errorHandler: (err) => {
  9295. console.error('A network error occurred while retrieving the HTML for the code submission page.', submitUrl);
  9296. }
  9297. });
  9298. }
  9299.  
  9300. /**
  9301. * 获取代码提交页的HTML元素
  9302. * @param {string} submitUrl
  9303. * @returns {Promise<jQuery>}
  9304. */
  9305. async function getSubmitHTML(submitUrl) {
  9306. const cacheKey = 'OJBetter_CloneOriginalHTML';
  9307. const cookieKey = 'OJBetter_CloneOriginalHTML_time';
  9308. if (OJB_getCookie(cookieKey) === '1') {
  9309. // 存在缓存
  9310. CloneOriginalHTML(submitUrl, cacheKey);
  9311. // 校验
  9312. let cloneHTML = $(localStorage.getItem(cacheKey));
  9313. if (cloneHTML.find('form.submit-form').length > 0) {
  9314. return cloneHTML;
  9315. } else {
  9316. // 存在错误,更新缓存
  9317. console.warn(`Cache error detected!\nattempting to update, cache destination submitUrl:\n${submitUrl}`);
  9318. return await CloneOriginalHTML(submitUrl, cacheKey);
  9319. }
  9320.  
  9321. } else {
  9322. // 没有缓存,更新
  9323. document.cookie = `${cookieKey}=1; path=/`;
  9324. return await CloneOriginalHTML(submitUrl, cacheKey);
  9325. }
  9326. }
  9327.  
  9328. // 代码自动保存
  9329. async function saveCode(url, code) {
  9330. try {
  9331. await OJBetter.common.database.editorCode.put({ url, code });
  9332. return 'Code saved successfully';
  9333. } catch (error) {
  9334. throw new Error('Failed to save code');
  9335. }
  9336. }
  9337.  
  9338. async function getCode(url) {
  9339. try {
  9340. const result = await OJBetter.common.database.editorCode.get(url);
  9341. return result ? result.code : null;
  9342. } catch (error) {
  9343. throw new Error('Failed to get code');
  9344. }
  9345. }
  9346.  
  9347. // 创建代码编辑调试表单元素
  9348. // async function createCodeEditorForm(submitUrl, cloneHTML) {
  9349. async function createCodeEditorForm(submitUrl) {
  9350. // 表单
  9351. let formDiv = $('<form method="post" id="OJBetter_SubmitForm" class="input-output-copier"></form>');
  9352. // $('.ttypography').after(formDiv);
  9353. $('#task-statement').after(formDiv);
  9354. // formDiv.attr('action', submitUrl + "?csrf_token=" + OJBetter.common.at_csrf_token);
  9355. formDiv.attr('action', submitUrl);
  9356. formDiv.attr('method', 'POST');
  9357.  
  9358. // 顶部区域
  9359. let topDiv = OJB_safeCreateJQElement(`<div class="topDiv"></div>`);
  9360. let selectLang = $('#select-lang').clone(); // 语言选择
  9361. // selectLang.css({ 'margin': '10px 0px' }).attr('id', 'programTypeId');
  9362. topDiv.append(selectLang);
  9363. let topRightDiv = OJB_safeCreateJQElement(`<div class="topRightDiv"></div>`);
  9364. topDiv.append(topRightDiv);
  9365. formDiv.append(topDiv);
  9366.  
  9367. // 问题选择/编号
  9368. // let selectProblem = $('<input name="submittedProblemIndex" style="display:none;"></input>');
  9369. // let problemCode;
  9370. // if (OJBetter.typeOfPage.is_acmsguru) {
  9371. // problemCode = $('h4').eq(0).text();
  9372. // let matchResult = problemCode.match(/([A-Z0-9]+)/);
  9373. // problemCode = matchResult[0];
  9374. // } else if (OJBetter.typeOfPage.is_problemset_problem) {
  9375. // let match = window.location.href.match(/\/problem\/([0-9]+?)\/([A-Z0-9]+?)(?!=[A-Z0-9])/);
  9376. // problemCode = match[1] + match[2];
  9377. // selectProblem.attr('name', 'submittedProblemCode');
  9378. // } else {
  9379. // problemCode = $('.header .title').eq(0).text();
  9380. // let matchResult = problemCode.match(/([A-Z0-9]+)/);
  9381. // problemCode = matchResult[0];
  9382. // }
  9383. // selectProblem.val(problemCode);
  9384. let selectProblem = $('input[name="data.TaskScreenName"]').clone();
  9385. formDiv.append(selectProblem);
  9386.  
  9387. // 隐藏的代码记录
  9388. // let sourceDiv = $('<textarea id="sourceCodeTextarea" name="source" style="display: none;"></textarea>');
  9389. let sourceDiv = $('<textarea id="plain-textarea" name="sourceCode" style="display: none;"></textarea>');
  9390. formDiv.append(sourceDiv);
  9391.  
  9392. // 隐藏的crsf token
  9393. let csrfDiv = $(`<input type="hidden" name="csrf_token" value=${OJBetter.common.at_csrf_token}>`);
  9394. formDiv.append(csrfDiv);
  9395.  
  9396. // 代码编辑器
  9397. let editorDiv = $('<div id="OJBetter_editor"></div>');
  9398. formDiv.append(editorDiv);
  9399.  
  9400. // monaco
  9401. let monaco = $('<div id="OJBetter_monaco"></div>');
  9402. editorDiv.append(monaco);
  9403.  
  9404. // 自定义调试
  9405. let customTestDiv = OJB_safeCreateJQElement(`
  9406. <details id="customTestBlock">
  9407. <summary >${i18next.t('customTestBlock.title', { ns: 'codeEditor' })}</summary>
  9408. <div id="customTests" style="min-height: 30px;"></div>
  9409. <div id="control" style="display:flex;">
  9410. <div style="display: flex;margin: 5px;">
  9411. <input type="checkbox" id="onlyCustomTest"}><label for="onlyCustomTest">
  9412. ${i18next.t('customTestBlock.onlyCustom', { ns: 'codeEditor' })}
  9413. </label>
  9414. </div>
  9415. <div style="display: flex;margin: 5px;">
  9416. <input type="checkbox" id="DontShowDiff"}>
  9417. <label for="DontShowDiff">
  9418. ${i18next.t('customTestBlock.DontShowDiff', { ns: 'codeEditor' })}
  9419. </label>
  9420. </div>
  9421. <button type="button" id="addCustomTest">${i18next.t('customTestBlock.add', { ns: 'codeEditor' })}</button>
  9422. </div>
  9423. </details>
  9424. `)
  9425. formDiv.append(customTestDiv);
  9426.  
  9427. // 调试/提交
  9428. let submitDiv = $('<div id="OJBetter_submitDiv"></div>');
  9429. let CompilerArgsInput = $('<input type="text" id="CompilerArgsInput">');
  9430. submitDiv.append(CompilerArgsInput);
  9431.  
  9432. let runButton = OJB_safeCreateJQElement(`
  9433. <button type="button" id="RunTestButton" class="ojb_btn ojb_btn_popover top">
  9434. <i class="iconfont">&#xe6c1;</i>
  9435. <span class="popover_content">${i18next.t('runTestButton.initial', { ns: 'codeEditor' })}</span>
  9436. </button>
  9437. `);
  9438. let submitButton = OJB_safeCreateJQElement(`
  9439. <button id="SubmitButton" class="ojb_btn ojb_btn_popover top" type="submit">
  9440. <i class="iconfont">&#xe633;</i>
  9441. <span class="popover_content">${i18next.t('submitButton', { ns: 'codeEditor' })}</span>
  9442. </button>
  9443. `);
  9444. if (OJBetter.monaco.setting.submitButtonPosition == "bottom") {
  9445. // 添加测试/提交按钮到底部
  9446. submitDiv.append(runButton);
  9447. submitDiv.append(submitButton);
  9448. }
  9449.  
  9450. formDiv.append(submitDiv);
  9451. let CompilerSetting = OJB_safeCreateJQElement(`
  9452. <div id="CompilerSetting"></div>
  9453. `);
  9454. formDiv.append(CompilerSetting);
  9455. let statePanel = OJB_safeCreateJQElement(`
  9456. <div id="statePanel"></div>
  9457. `);
  9458. formDiv.append(statePanel);
  9459.  
  9460. //==================================
  9461. // 去除原有的编辑器
  9462. //==================================
  9463. $('.form-code-submit').remove();
  9464.  
  9465. let from = {
  9466. formDiv: formDiv,
  9467. selectLang: selectLang.find('select:first'),
  9468. topRightDiv: topRightDiv,
  9469. sourceDiv: sourceDiv,
  9470. editorDiv: editorDiv,
  9471. monaco: monaco,
  9472. runButton: runButton,
  9473. submitButton: submitButton,
  9474. submitDiv: submitDiv,
  9475. CompilerSetting: CompilerSetting,
  9476. statePanel: statePanel
  9477. };
  9478. return from;
  9479. }
  9480.  
  9481. // 解析ace格式的补全规则(acwing)
  9482. function parseAceCompleter(rules, range) {
  9483. const suggestions = [];
  9484. if (rules && rules.templates && rules.templates.items) {
  9485. const items = rules.templates.items;
  9486. for (let i = 0; i < items.length; i++) {
  9487. const item = items[i];
  9488. const parts = item.caption.split(' ');
  9489. for (let i = 0; i < parts.length; i++) {
  9490. if (item.value.startsWith(parts[i])) {
  9491. item.value = item.value.replace(parts[i], parts.slice(0, i + 1).join(' '));
  9492. break;
  9493. }
  9494. }
  9495. const completionItem = {
  9496. label: item.caption,
  9497. kind: monaco.languages.CompletionItemKind.Function,
  9498. insertText: item.value,
  9499. range: range
  9500. };
  9501. suggestions.push(completionItem);
  9502. }
  9503. }
  9504. return { suggestions };
  9505. }
  9506.  
  9507. // 解析monaco格式的补全规则
  9508. function parseMonacoCompleter(rules, range) {
  9509. const suggestions_ = [];
  9510. if (rules && rules.suggestions) {
  9511. const suggestion = rules.suggestions;
  9512. for (let i = 0; i < rules.suggestions.length; i++) {
  9513. const item = suggestion[i];
  9514. const completionItem = {
  9515. ...item,
  9516. range: range
  9517. };
  9518. suggestions_.push(completionItem);
  9519. }
  9520. }
  9521. return { suggestions: suggestions_ };
  9522. }
  9523.  
  9524. /**
  9525. * 创建monaco编辑器的一个实例
  9526. */
  9527. async function createMonacoEditor(language, form, support) {
  9528. // 判断monacoLoader是否加载完毕
  9529. async function waitForMonacoLoaderOnload() {
  9530. return new Promise((resolve) => {
  9531. const checkInitialized = () => {
  9532. if (OJBetter.monaco.loaderOnload) {
  9533. resolve();
  9534. } else {
  9535. setTimeout(checkInitialized, 100); // 每100毫秒检查一次initialized的值
  9536. }
  9537. };
  9538. checkInitialized();
  9539. });
  9540. }
  9541. if (!OJBetter.monaco.loaderOnload) await waitForMonacoLoaderOnload();
  9542.  
  9543. /**
  9544. * 通用参数
  9545. */
  9546. var id = 0; // 协议中的id标识
  9547. var workspace = language + "_workspace";
  9548. var rootUri = OJBetter.monaco.lsp.workUri + "/" + workspace;
  9549. // 文件名
  9550. var InstanceID = OJB_getRandomNumber(8).toString();
  9551. var filename = language == "java" ? "hello/src/" + InstanceID : InstanceID;
  9552. // 后缀名
  9553. var fileExtension =
  9554. language === "cpp"
  9555. ? ".cpp"
  9556. : language === "python"
  9557. ? ".py"
  9558. : language === "java"
  9559. ? ".java"
  9560. : "";
  9561. var uri = rootUri + "/" + filename + fileExtension;
  9562. var initialized = false; // 是否已初始化
  9563. var serverInfo; // 服务器返回的支持信息
  9564. var model; // model
  9565. var OJBetter_monaco = {};
  9566. window.OJBetter_monaco = OJBetter_monaco; // 全局方法
  9567.  
  9568. /**
  9569. * 一些工具函数
  9570. */
  9571. // 将lsp格式的rang转换为Monaco格式
  9572. OJBetter_monaco.lspRangeToMonacoRange = function (range) {
  9573. const { start, end } = range;
  9574. return new monaco.Range(
  9575. start.line + 1,
  9576. start.character + 1,
  9577. end.line + 1,
  9578. end.character + 1
  9579. );
  9580. };
  9581. // 将Monaco格式的rang转为lsp格式
  9582. OJBetter_monaco.MonacoRangeTolspRange = function (range) {
  9583. return {
  9584. start: {
  9585. line: range.startLineNumber - 1,
  9586. character: range.startColumn - 1,
  9587. },
  9588. end: {
  9589. line: range.endLineNumber - 1,
  9590. character: range.endColumn - 1,
  9591. },
  9592. };
  9593. };
  9594. // 将Monaco格式的position转为lsp格式的
  9595. OJBetter_monaco.MonacoPositionTolspPosition = function (position) {
  9596. return {
  9597. line: position.lineNumber - 1,
  9598. character: position.column - 1,
  9599. };
  9600. };
  9601. // 将Monaco格式的severity转为lsp格式的
  9602. OJBetter_monaco.MonacoSeverityTolspSeverity = function (severity) {
  9603. switch (severity) {
  9604. case 8:
  9605. return 1;
  9606. case 1:
  9607. return 4;
  9608. case 2:
  9609. return 3;
  9610. case 4:
  9611. return 2;
  9612. default:
  9613. return severity;
  9614. }
  9615. };
  9616. // 将lsp格式的severity转为Monaco格式的
  9617. OJBetter_monaco.lspSeverityToMonacoSeverity = function (severity) {
  9618. switch (severity) {
  9619. case 1:
  9620. return 8;
  9621. case 4:
  9622. return 1;
  9623. case 3:
  9624. return 2;
  9625. case 2:
  9626. return 4;
  9627. default:
  9628. return severity;
  9629. }
  9630. };
  9631. // 收集Monaco数据中的rang数据
  9632. OJBetter_monaco.CollectRange = function (item) {
  9633. return {
  9634. startLineNumber: item.startLineNumber,
  9635. startColumn: item.startColumn,
  9636. endLineNumber: item.endLineNumber,
  9637. endColumn: item.endColumn,
  9638. };
  9639. };
  9640. // 收集Monaco position数据中的rang数据
  9641. OJBetter_monaco.CollectRangeByPosition = function (item) {
  9642. var word = model.getWordUntilPosition(item);
  9643. return {
  9644. startLineNumber: item.lineNumber,
  9645. endLineNumber: item.lineNumber,
  9646. startColumn: word.startColumn,
  9647. endColumn: word.endColumn,
  9648. };
  9649. };
  9650. // 将lsp格式的Edit转换为Monaco格式
  9651. OJBetter_monaco.lspEditToMonacoEdit = function (edit) {
  9652. const edits = [];
  9653.  
  9654. if (language == "python") {
  9655. for (const item1 of edit.documentChanges) {
  9656. for (const item2 of item1.edits) {
  9657. const newElement = {
  9658. textEdit: {
  9659. range: OJBetter_monaco.lspRangeToMonacoRange(item2.range),
  9660. text: item2.newText,
  9661. },
  9662. resource: monaco.Uri.parse(item1.textDocument.uri),
  9663. versionId: model.getVersionId(),
  9664. };
  9665. edits.push(newElement);
  9666. }
  9667. }
  9668. } else if (language == "java") {
  9669. for (const item1 in edit.changes) {
  9670. edit.changes[item1].forEach((item2) => {
  9671. const newElement = {
  9672. textEdit: {
  9673. range: OJBetter_monaco.lspRangeToMonacoRange(item2.range),
  9674. text: item2.newText,
  9675. },
  9676. resource: uri,
  9677. versionId: model.getVersionId(),
  9678. };
  9679. edits.push(newElement);
  9680. });
  9681. }
  9682. } else {
  9683. for (const key in edit.changes) {
  9684. const arr = edit.changes[key];
  9685. for (const item of arr) {
  9686. const newElement = {
  9687. textEdit: {
  9688. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  9689. text: item.newText,
  9690. },
  9691. resource: monaco.Uri.parse(key),
  9692. versionId: model.getVersionId(),
  9693. };
  9694. edits.push(newElement);
  9695. }
  9696. }
  9697. }
  9698. return { edits: edits };
  9699. };
  9700.  
  9701. /**
  9702. * 实例化一个editor
  9703. */
  9704. uri = monaco.Uri.file(uri);
  9705. model = monaco.editor.createModel('', language, uri);
  9706. OJBetter.monaco.editor = monaco.editor.create(document.getElementById("OJBetter_monaco"), {
  9707. model: model,
  9708. rootUri: rootUri,
  9709. fontSize: 15,
  9710. tabSize: 4,
  9711. theme: OJBetter.basic.darkMode == "dark" ? "vs-dark" : "vs",
  9712. bracketPairColorization: {
  9713. enabled: true,
  9714. independentColorPoolPerBracketType: true,
  9715. },
  9716. automaticLayout: true,
  9717. lineNumbersMinChars: 3,
  9718. matchOnWordStartOnly: false,
  9719. wordWrap: "on",
  9720. wrappingIndent: "same",
  9721. glyphMargin: true,
  9722. formatOnType: true,
  9723. scrollbar: {
  9724. verticalScrollbarSize: 10,
  9725. horizontalScrollbarSize: 10,
  9726. alwaysConsumeMouseWheel: OJBetter.monaco.setting.alwaysConsumeMouseWheel
  9727. },
  9728. suggest: {
  9729. selectionMode: 'never' // 代码建议不自动选择
  9730. }
  9731. });
  9732.  
  9733. /**
  9734. * 添加快捷功能
  9735. */
  9736. (OJBetter_monaco.addShortCuts = async () => {
  9737. // 从配置信息更新字体大小
  9738. OJBetter.monaco.editor.updateOptions({ fontSize: parseInt(OJBetter.monaco.setting.fontsize) });
  9739.  
  9740. // 调整字体大小
  9741. let changeSize = OJB_safeCreateJQElement(`
  9742. <div class="ojb_btn ojb_btn_popover top">
  9743. <input type="number" id="fontSizeInput" value="${OJBetter.monaco.setting.fontsize}">
  9744. <span class="popover_content">${i18next.t('fontSizeInput', { ns: 'codeEditor' })}</span>
  9745. </div>`)
  9746. form.topRightDiv.append(changeSize);
  9747. changeSize.find('input#fontSizeInput').on('input', function () {
  9748. var size = $(this).val();
  9749. OJBetter.monaco.editor.updateOptions({ fontSize: parseInt(size) });
  9750. GM_setValue('editorFontSize', size);
  9751. });
  9752.  
  9753. // 全屏按钮
  9754. let fullscreenButton = OJB_safeCreateJQElement(`
  9755. <button type="button" class="ojb_btn ojb_btn_popover top">
  9756. <i class="iconfont">&#xe606;</i>
  9757. <span class="popover_content">${i18next.t('fullscreenButton', { ns: 'codeEditor' })}</span>
  9758. </button>
  9759. `);
  9760. form.topRightDiv.append(fullscreenButton);
  9761. fullscreenButton.on('click', enterFullscreen);
  9762.  
  9763. // 固定到底部按钮
  9764. let fixToBottomButton = OJB_safeCreateJQElement(`
  9765. <button type="button" class="ojb_btn ojb_btn_popover top">
  9766. <i class="iconfont">&#xe607;</i>
  9767. <span class="popover_content">${i18next.t('fixToBottomButton', { ns: 'codeEditor' })}</span>
  9768. </button>
  9769. `);
  9770. form.topRightDiv.append(fixToBottomButton);
  9771. fixToBottomButton.on('click', fixToBottom);
  9772.  
  9773. // 固定到右侧按钮
  9774. let fixToRightButton = OJB_safeCreateJQElement(`
  9775. <button type="button" class="ojb_btn ojb_btn_popover top">
  9776. <i class="iconfont">&#xe605;</i>
  9777. <span class="popover_content">${i18next.t('fixToRightButton', { ns: 'codeEditor' })}</span>
  9778. </button>
  9779. `);
  9780. // form.topRightDiv.append(fixToRightButton);
  9781. fixToRightButton.on('click', fixToRight);
  9782.  
  9783. // 添加测试/提交按钮到顶部
  9784. if (OJBetter.monaco.setting.submitButtonPosition == "top") {
  9785. form.topRightDiv.append(form.runButton);
  9786. form.topRightDiv.append(form.submitButton);
  9787. }
  9788.  
  9789. // 选择记忆
  9790. if (!OJBetter.monaco.setting.position_initialized) {
  9791. OJBetter.monaco.setting.position_initialized = true; // 标记是否已经初始化过
  9792. if (OJBetter.monaco.setting.position == "full") {
  9793. fullscreenButton.click();
  9794. } else if (OJBetter.monaco.setting.position == "bottom") {
  9795. fixToBottomButton.click();
  9796. } else if (OJBetter.monaco.setting.position == "right") {
  9797. fixToRightButton.click();
  9798. }
  9799. }
  9800.  
  9801. // 禁用按钮
  9802. function disableButtons() {
  9803. fullscreenButton.prop("disabled", true);
  9804. fixToBottomButton.prop("disabled", true);
  9805. fixToRightButton.prop("disabled", true);
  9806. }
  9807.  
  9808. // 启用按钮
  9809. function enableButtons() {
  9810. fullscreenButton.prop("disabled", false);
  9811. fixToBottomButton.prop("disabled", false);
  9812. fixToRightButton.prop("disabled", false);
  9813. }
  9814.  
  9815. // 进入全屏
  9816. function enterFullscreen() {
  9817. let editor = $('#OJBetter_editor');
  9818. editor.addClass('fullscreen');
  9819.  
  9820. // 取消按钮
  9821. let cancelButton = OJB_safeCreateJQElement(`
  9822. <button type="button" class="ojb_btn ojb_btn_popover top primary exit_button_bottom">
  9823. <i class="iconfont">&#xe60b;</i>
  9824. <span class="popover_content">${i18next.t('exitFullscreenButton', { ns: 'codeEditor' })}</span>
  9825. </button>
  9826. `).on('click', () => exitFullscreen(cancelButton));
  9827. $('body').append(cancelButton);
  9828.  
  9829. disableButtons();
  9830. GM_setValue("monacoEditor_position", "full");
  9831. }
  9832.  
  9833. // 退出全屏
  9834. const exitFullscreen = (cancelButton) => {
  9835. let editor = $('#OJBetter_editor');
  9836. editor.removeClass('fullscreen');
  9837. cancelButton.remove();
  9838. enableButtons();
  9839. GM_setValue("monacoEditor_position", "initial");
  9840. };
  9841.  
  9842. // 固定到底部
  9843. function fixToBottom() {
  9844. let editor = $('#OJBetter_editor');
  9845. editor.addClass('bottom');
  9846.  
  9847. let halfHeight = $(window).height() * 0.5;
  9848. let blankSpace = $('<div>', {
  9849. 'class': 'blank-space',
  9850. 'style': 'height: ' + (halfHeight + 30) + 'px;'
  9851. });
  9852. $('body').append(blankSpace);
  9853.  
  9854. let cancelButton = OJB_safeCreateJQElement(`
  9855. <button type="button" class="ojb_btn ojb_btn_popover top enabled exit_button_bottom">
  9856. <i class="iconfont">&#xe625;</i>
  9857. <span class="popover_content">${i18next.t('cancelFixButton', { ns: 'codeEditor' })}</span>
  9858. </button>
  9859. `).on('click', () => cancelFixingToBottom(cancelButton, blankSpace));
  9860. $('body').append(cancelButton);
  9861.  
  9862. disableButtons();
  9863. GM_setValue("monacoEditor_position", "bottom");
  9864. }
  9865.  
  9866. // 取消固定到底部
  9867. const cancelFixingToBottom = (cancelButton, blankSpace) => {
  9868. let editor = $('#OJBetter_editor');
  9869. editor.removeClass('bottom');
  9870. cancelButton.remove();
  9871. blankSpace.remove();
  9872. enableButtons();
  9873. GM_setValue("monacoEditor_position", "initial");
  9874. };
  9875.  
  9876. // 固定到右侧边栏
  9877. function fixToRight() {
  9878. const sidebar = $('#sidebar').hide();
  9879.  
  9880. // 添加样式
  9881. const styleElement = GM_addStyle(`
  9882. #body {
  9883. min-width: 50vw;
  9884. max-width: 50vw;
  9885. max-height: 100vh;
  9886. overflow-x: hidden;
  9887. overflow-y: auto;
  9888. padding: 1rem;
  9889. box-sizing: border-box;
  9890. }
  9891. body {
  9892. margin: 0px;
  9893. }
  9894. .content-with-sidebar {
  9895. margin-right: 0px !important;
  9896. }
  9897. .menu-list li {
  9898. margin-right: 0.5em;
  9899. }
  9900. .menu-list li a {
  9901. font-size: 1.4rem;
  9902. }
  9903. #OJBetter_editor{
  9904. height: 100vh;
  9905. width: 50vw;
  9906. }
  9907. `);
  9908.  
  9909. // 包装一层div
  9910. $('#body').wrap('<div id="right-side-wrapper" style="display:flex; max-width: 100vw; overflow: hidden;"></div>');
  9911. const blankSpace = $('<div>').appendTo('#right-side-wrapper');
  9912.  
  9913. // 移动编辑器
  9914. const editor = $('#OJBetter_editor').prependTo(blankSpace).addClass('right-side');
  9915.  
  9916. // 取消按钮
  9917. const cancelButton = OJB_safeCreateJQElement(`
  9918. <button type="button" class="ojb_btn ojb_btn_popover top enabled exit_button_bottom">
  9919. <i class="iconfont">&#xe625;</i>
  9920. <span class="popover_content">${i18next.t('cancelFixButton', { ns: 'codeEditor' })}</span>
  9921. </button>
  9922. `).on('click', () => cancelFixingToRight(sidebar, styleElement, editor, cancelButton)).appendTo('body');
  9923.  
  9924. disableButtons();
  9925. GM_setValue("monacoEditor_position", "right");
  9926.  
  9927. // 补丁:修复固定到右侧导致的样例元素.sample-test相关代码重复执行的问题(具体原因未查)
  9928. $('.sample-test').find('.title').each((i, e) => {
  9929. if ($(e).find('.input-output-copier').length > 1) {
  9930. $(e).find('.input-output-copier').first().remove();
  9931. }
  9932. });
  9933. darkModeStyleAdjustment();
  9934. }
  9935.  
  9936. const cancelFixingToRight = (sidebar, styleElement, editor, cancelButton) => {
  9937. sidebar.show();
  9938. // 移回来
  9939. editor.insertAfter(form.sourceDiv).removeClass('right-side');
  9940.  
  9941. // 移除包装
  9942. $('#body').unwrap();
  9943. cancelButton.remove();
  9944. styleElement.remove(); // 移除添加的样式
  9945.  
  9946. enableButtons();
  9947. GM_setValue("monacoEditor_position", "initial");
  9948. }
  9949.  
  9950. // 代码同步与保存
  9951. var nowUrl = window.location.href;
  9952. nowUrl = nowUrl.replace(/#/, ""); // 当页面存在更改时url会多出一个#,去掉
  9953. const code = await getCode(nowUrl);
  9954. if (code) {
  9955. OJBetter.monaco.editor.setValue(code); // 恢复代码
  9956. form.sourceDiv.val(code);
  9957. }
  9958. OJBetter.monaco.editor.onDidChangeModelContent(async () => {
  9959. // 将monaco editor的内容同步到sourceDiv
  9960. const code = OJBetter.monaco.editor.getValue();
  9961. form.sourceDiv.val(code);
  9962. await saveCode(nowUrl, code);
  9963. });
  9964. })();
  9965.  
  9966. /**
  9967. * 注册本地自动补全
  9968. */
  9969. (OJBetter_monaco.RegisterLocalComplet = async () => {
  9970. // 补全器注册函数
  9971. function registMyCompletionItemProvider(language, genre, rule) {
  9972. if (genre == "monaco") {
  9973. monaco.languages.registerCompletionItemProvider(language, {
  9974. provideCompletionItems: function (model, position) {
  9975. return parseMonacoCompleter(rule, OJBetter_monaco.CollectRangeByPosition(position));
  9976. }
  9977. })
  9978. } else if (genre == "ace") {
  9979. monaco.languages.registerCompletionItemProvider(language, {
  9980. provideCompletionItems: function (model, position) {
  9981. return parseAceCompleter(rule, OJBetter_monaco.CollectRangeByPosition(position));
  9982. }
  9983. })
  9984. }
  9985. }
  9986.  
  9987. // 注册acwing cpp 模板
  9988. if (language == "cpp" && OJBetter.monaco.complet.cppCodeTemplate) {
  9989. try {
  9990. var acwing_cpp_code_completer = JSON.parse(GM_getResourceText("acwing_cpp_code_completer"));
  9991. registMyCompletionItemProvider('cpp', 'ace', acwing_cpp_code_completer);
  9992. } catch (error) {
  9993. console.error("Error registering acwing cpp template:", error);
  9994. }
  9995. }
  9996.  
  9997. // 注册自定义的补全
  9998. let complet_length = OJBetter.monaco.complet.customConfig.configurations.length;
  9999. if (complet_length > 0) {
  10000. for (let i = 0; i < complet_length; i++) {
  10001. let item = OJBetter.monaco.complet.customConfig.configurations[i];
  10002. if (item.isChoose && item.language == language) {
  10003. try {
  10004. let rule = await OJB_getExternalJSON(item.jsonUrl);
  10005. registMyCompletionItemProvider(item.language, item.genre, rule);
  10006. } catch (error) {
  10007. console.error(`Error registering custom completer for ${item.language}:`, error);
  10008. }
  10009. }
  10010. }
  10011. }
  10012. })();
  10013.  
  10014. if (!support || !OJBetter.monaco.lsp.enabled) { return; } // 如果不支持lsp,则到此为止
  10015.  
  10016. /**
  10017. * LSP连接状态指示
  10018. */
  10019. const lspStateButton = OJB_safeCreateJQElement(`
  10020. <div id="lspStateDiv" class="ojb_btn ojb_btn_popover top loading">
  10021. <i class="iconfont">&#xe658;</i>
  10022. <span class="popover_content">${i18next.t('lsp.connect', { ns: 'codeEditor' })}</span>
  10023. </div>
  10024. `).on('click', () => {
  10025. OJB_showModal(LSPLogDiv);
  10026. LSPLogDiv.show();
  10027. });
  10028. form.topRightDiv.prepend(lspStateButton);
  10029.  
  10030. const LSPLogDiv = OJB_safeCreateJQElement(`
  10031. <dialog id="LSPLog" style="display: none;">
  10032. <button class="ojb_btn">${i18next.t('close', { ns: 'common' })}</button>
  10033. <div id="LSPLogList" style="overflow: auto;"></div>
  10034. <dialog>`);
  10035. $('body').append(LSPLogDiv);
  10036.  
  10037. const LSPLogList = $('<ul></ul>');
  10038. $('#LSPLogList').append(LSPLogList);
  10039.  
  10040. const closeButton = LSPLogDiv.find('button');
  10041. closeButton.on('click', function () {
  10042. OJB_closeModal(LSPLogDiv);
  10043. });
  10044.  
  10045. /**
  10046. * 推送新的消息到LSP日志中
  10047. * @param {'error' | 'warn' | 'info'} status
  10048. * @param {string} msg
  10049. * @param {boolean} data
  10050. */
  10051. function pushLSPLogMessage(status, msg, data) {
  10052. var li = $('<li>').text('[' + new Date().toLocaleString() + '] ' + msg);
  10053. if (status === 'error') {
  10054. li.attr('style', 'color: #f44336;');
  10055. } else if (status === 'warn') {
  10056. li.attr('style', 'color: #ff9800;');
  10057. } else if (status === 'info') {
  10058. li.attr('style', 'color: #616161;');
  10059. }
  10060. if (data) {
  10061. var jsonText = JSON.stringify(data, null, 2);
  10062. var details = $('<details>');
  10063. var summary = $('<summary>').text('Data');
  10064. var pre = $('<pre>').text(jsonText);
  10065. details.append(summary, pre);
  10066. li.append(details);
  10067. }
  10068. LSPLogList.append(li);
  10069. }
  10070.  
  10071. /**
  10072. * 添加状态底栏
  10073. */
  10074. var statusBar = $('<div id="OJBetter_statusBar">');
  10075. form.editorDiv.append(statusBar);
  10076.  
  10077. /**
  10078. * languageSocket
  10079. */
  10080. var url = OJBetter.monaco.lsp.socketUrl;
  10081. var languageSocket = new WebSocket(url + language);
  10082. OJBetter.monaco.lsp.socket.push(languageSocket);
  10083. var languageSocketState = false;
  10084. var responseHandlers = new Map(); // 映射表,需要等待返回数据的请求 -> 对应的事件触发函数
  10085.  
  10086. languageSocket.onopen = () => {
  10087. languageSocketState = true;
  10088. lspStateButton.setButtonPopover(i18next.t('lsp.waitingAnswer', { ns: 'codeEditor' }));
  10089. pushLSPLogMessage("info", `languageSocket ${i18next.t('lsp.socket.open', { ns: 'logMessage' })}`);
  10090. };
  10091. languageSocket.onmessage = (event) => {
  10092. const message = JSON.parse(event.data);
  10093. if (message.id === 0 && message.result) {
  10094. // 初始化完成
  10095. lspStateButton.setButtonState('success', i18next.t('lsp.connected', { ns: 'codeEditor' }));
  10096. pushLSPLogMessage("info", `Initialization ${i18next.t('lsp.state.finished', { ns: 'logMessage' })}`);
  10097. serverInfo = message.result; // 存下服务器支持信息
  10098. OJBetter_monaco.openDocRequest(); // 打开文档
  10099. if (!OJBetter.monaco.setting.language.includes(language)) {
  10100. OJBetter.monaco.setting.language.push(language);
  10101. OJBetter_monaco.RegistrationAfterInit(); // 注册语言及功能
  10102. } else {
  10103. location.reload(); // 这里有问题,先贴个补丁
  10104. }
  10105. OJBetter_monaco.PassiveReceiveHandler(); // 注册被动接收函数
  10106. } else if (message.id === 0 && message.error) {
  10107. pushLSPLogMessage("warn", `Initialization ${i18next.t('lsp.state.error', { ns: 'logMessage' })}`);
  10108. } else if (message.id !== undefined && responseHandlers.has(message.id)) {
  10109. // 如果收到带有id字段的消息,则回传给对应的事件触发函数
  10110. const handler = responseHandlers.get(message.id);
  10111. if (handler) {
  10112. handler(message);
  10113. responseHandlers.delete(message.id); // 删除已处理的事件触发函数
  10114. }
  10115. } else if (message.method == "textDocument/publishDiagnostics") {
  10116. // 接收代码诊断推送
  10117. OJBetter_monaco.updateMarkers(message);
  10118. } else if (message.method == "workspace/applyEdit") {
  10119. // 应用服务器推送的更改
  10120. OJBetter_monaco.applyEdit(message);
  10121. }
  10122. };
  10123. languageSocket.onerror = (error) => {
  10124. pushLSPLogMessage("error", `languageSocket ${i18next.t('lsp.state.error', { ns: 'logMessage' })}`, error);
  10125. console.warn(`Error connecting to languageSocket: ${error}`)
  10126. };
  10127. languageSocket.onclose = (event) => {
  10128. languageSocketState = false;
  10129. lspStateButton.setButtonState('error', i18next.t('lsp.error', { ns: 'codeEditor' }));
  10130. pushLSPLogMessage("warn", `languageSocket ${i18next.t('lsp.socket.close', { ns: 'logMessage' })}`);
  10131. };
  10132.  
  10133. /**
  10134. * 等待LanguageSocketState
  10135. */
  10136. async function waitForLanguageSocketState() {
  10137. return new Promise((resolve) => {
  10138. const checkInitialized = () => {
  10139. if (languageSocketState) {
  10140. resolve();
  10141. } else {
  10142. setTimeout(checkInitialized, 100); // 每100毫秒检查一次initialized的值
  10143. }
  10144. };
  10145. checkInitialized();
  10146. });
  10147. }
  10148.  
  10149. // 等待lsp响应初始化结果
  10150. async function waitForInitialized() {
  10151. return new Promise((resolve) => {
  10152. const checkInitialized = () => {
  10153. if (initialized) {
  10154. resolve();
  10155. } else {
  10156. setTimeout(checkInitialized, 100); // 每100毫秒检查一次initialized的值
  10157. }
  10158. };
  10159. checkInitialized();
  10160. });
  10161. }
  10162.  
  10163. /**
  10164. * 与languageSocket通信的包装方法
  10165. */
  10166. async function sendMessage(data, requiresResponse, callback) {
  10167. if (!initialized) {
  10168. await waitForInitialized(); // 等待initialized为真
  10169. }
  10170. if (requiresResponse) {
  10171. responseHandlers.set(data.id, callback) // 将事件触发函数与id关联起来
  10172. }
  10173. if (!languageSocketState) await waitForLanguageSocketState();
  10174. languageSocket.send(JSON.stringify(data));
  10175. }
  10176. // 发送消息并等待返回结果
  10177. function fetchData(params, callback) {
  10178. sendMessage(params, true, callback);
  10179. }
  10180. // 发送消息,不需要等待返回结果
  10181. function sendData(data) {
  10182. sendMessage(data, false);
  10183. }
  10184.  
  10185. /**
  10186. * 代码文件更新fileWebSocket
  10187. */
  10188. var fileWebSocket = new WebSocket(url + "file");
  10189. var fileWebSocketState = false;
  10190. OJBetter.monaco.lsp.socket.push(fileWebSocket);
  10191. fileWebSocket.onopen = () => {
  10192. fileWebSocketState = true;
  10193. pushLSPLogMessage("info", `fileWebSocket ${i18next.t('lsp.socket.open', { ns: 'logMessage' })}`);
  10194. };
  10195. fileWebSocket.onclose = (ev) => {
  10196. fileWebSocketState = false;
  10197. pushLSPLogMessage("warn", `fileWebSocket ${i18next.t('lsp.socket.close', { ns: 'logMessage' })}`, ev);
  10198. };
  10199. fileWebSocket.onmessage = (ev) => {
  10200. let message = JSON.parse(ev.data);
  10201. if (message.result !== "ok")
  10202. pushLSPLogMessage("error", `update file failed: ${ev}`);
  10203. };
  10204. fileWebSocket.onerror = (error) => {
  10205. console.warn(`Error connecting to fileWebSocket: ${error}`);
  10206. };
  10207. async function updateFile(workspace, filename, fileExtension, code) {
  10208. async function waitForfileWebSocketState() {
  10209. return new Promise((resolve) => {
  10210. const checkInitialized = () => {
  10211. if (fileWebSocketState) {
  10212. resolve();
  10213. } else {
  10214. setTimeout(checkInitialized, 100); // 每100毫秒检查一次initialized的值
  10215. }
  10216. };
  10217. checkInitialized();
  10218. });
  10219. }
  10220. if (!fileWebSocketState) await waitForfileWebSocketState();
  10221. fileWebSocket.send(
  10222. JSON.stringify({
  10223. type: "update",
  10224. workspace,
  10225. filename,
  10226. fileExtension,
  10227. code,
  10228. })
  10229. );
  10230. }
  10231.  
  10232. /**
  10233. * 发送初始化请求
  10234. */
  10235. OJBetter_monaco.Initialize = () => {
  10236. //初始化initialize
  10237. const capabilities = {
  10238. workspace: {
  10239. applyEdit: true,
  10240. },
  10241. textDocument: {
  10242. publishDiagnostics: {
  10243. relatedInformation: true,
  10244. versionSupport: false,
  10245. tagSupport: {
  10246. valueSet: [1, 2],
  10247. },
  10248. codeDescriptionSupport: true,
  10249. },
  10250. completion: {
  10251. contextSupport: true,
  10252. completionItem: {
  10253. snippetSupport: true,
  10254. commitCharactersSupport: true,
  10255. documentationFormat: ["markdown", "plaintext"],
  10256. deprecatedSupport: true,
  10257. preselectSupport: true,
  10258. tagSupport: {
  10259. valueSet: [1],
  10260. },
  10261. insertReplaceSupport: true,
  10262. resolveSupport: {
  10263. properties: [
  10264. "documentation",
  10265. "detail",
  10266. "additionalTextEdits",
  10267. ],
  10268. },
  10269. insertTextModeSupport: {
  10270. valueSet: [1, 2],
  10271. },
  10272. },
  10273. },
  10274. hover: {
  10275. dynamicRegistration: true,
  10276. contentFormat: ["markdown", "plaintext"],
  10277. },
  10278. signatureHelp: {
  10279. signatureInformation: {
  10280. documentationFormat: ["markdown", "plaintext"],
  10281. parameterInformation: {
  10282. labelOffsetSupport: true,
  10283. },
  10284. activeParameterSupport: true,
  10285. },
  10286. contextSupport: true,
  10287. },
  10288. definition: {
  10289. dynamicRegistration: true,
  10290. linkSupport: true,
  10291. },
  10292. references: {
  10293. dynamicRegistration: true,
  10294. },
  10295. documentHighlight: {
  10296. dynamicRegistration: true,
  10297. },
  10298. codeAction: {
  10299. codeActionLiteralSupport: {
  10300. codeActionKind: {
  10301. valueSet:
  10302. language == "java"
  10303. ? []
  10304. : [
  10305. "",
  10306. "quickfix",
  10307. "refactor",
  10308. "refactor.extract",
  10309. "refactor.inline",
  10310. "refactor.rewrite",
  10311. "source",
  10312. "source.organizeImports",
  10313. ],
  10314. },
  10315. },
  10316. },
  10317. rename: {
  10318. dynamicRegistration: true,
  10319. prepareSupport: true,
  10320. prepareSupportDefaultBehavior: 1,
  10321. honorsChangeAnnotations: true,
  10322. },
  10323. documentLink: {
  10324. tooltipSupport: true,
  10325. },
  10326. typeDefinition: {
  10327. dynamicRegistration: true,
  10328. linkSupport: true,
  10329. },
  10330. implementation: {
  10331. dynamicRegistration: true,
  10332. linkSupport: true,
  10333. },
  10334. colorProvider: {
  10335. dynamicRegistration: true,
  10336. },
  10337. foldingRange: {
  10338. dynamicRegistration: true,
  10339. rangeLimit: 5000,
  10340. lineFoldingOnly: true,
  10341. },
  10342. declaration: {
  10343. dynamicRegistration: true,
  10344. linkSupport: true,
  10345. },
  10346. semanticTokens: {
  10347. dynamicRegistration: true,
  10348. tokenTypes: [
  10349. "namespace",
  10350. "type",
  10351. "class",
  10352. "enum",
  10353. "interface",
  10354. "struct",
  10355. "typeParameter",
  10356. "parameter",
  10357. "variable",
  10358. "property",
  10359. "enumMember",
  10360. "event",
  10361. "function",
  10362. "method",
  10363. "macro",
  10364. "keyword",
  10365. "modifier",
  10366. "comment",
  10367. "string",
  10368. "number",
  10369. "regexp",
  10370. "operator",
  10371. ],
  10372. tokenModifiers: [
  10373. "declaration",
  10374. "definition",
  10375. "readonly",
  10376. "static",
  10377. "deprecated",
  10378. "abstract",
  10379. "async",
  10380. "modification",
  10381. "documentation",
  10382. "defaultLibrary",
  10383. ],
  10384. formats: ["relative"],
  10385. requests: {
  10386. range: true,
  10387. full: {
  10388. delta: true,
  10389. },
  10390. },
  10391. multilineTokenSupport: false,
  10392. overlappingTokenSupport: false,
  10393. },
  10394. callHierarchy: {
  10395. dynamicRegistration: true,
  10396. },
  10397. },
  10398. window: {
  10399. showMessage: {
  10400. messageActionItem: {
  10401. additionalPropertiesSupport: true,
  10402. },
  10403. },
  10404. showDocument: {
  10405. support: true,
  10406. },
  10407. workDoneProgress: true,
  10408. },
  10409. general: {
  10410. regularExpressions: {
  10411. engine: "ECMAScript",
  10412. version: "ES2020",
  10413. },
  10414. markdown: {
  10415. parser: "marked",
  10416. version: "1.1.0",
  10417. },
  10418. },
  10419. };
  10420.  
  10421. const initializeRequest = {
  10422. id: id++,
  10423. jsonrpc: "2.0",
  10424. method: "initialize",
  10425. params: {
  10426. processId: null,
  10427. clientInfo: {
  10428. name: "CFMonaco" + InstanceID,
  10429. },
  10430. locale: "zh-CN",
  10431. rootPath: null,
  10432. rootUri: null,
  10433. capabilities: capabilities,
  10434. trace: "off",
  10435. workspaceFolders: [
  10436. {
  10437. uri:
  10438. "file:///" + OJBetter.monaco.lsp.workUri + workspace,
  10439. name:
  10440. "file:///" + OJBetter.monaco.lsp.workUri + workspace,
  10441. },
  10442. ],
  10443. },
  10444. };
  10445. languageSocket.send(JSON.stringify(initializeRequest));
  10446.  
  10447. // 打开文档函数
  10448. OJBetter_monaco.openDocRequest = function () {
  10449. const initializ = {
  10450. jsonrpc: "2.0",
  10451. method: "initialized",
  10452. params: {},
  10453. };
  10454. languageSocket.send(JSON.stringify(initializ));
  10455. const openDocRequest = {
  10456. jsonrpc: "2.0",
  10457. method: "textDocument/didOpen",
  10458. params: {
  10459. textDocument: {
  10460. uri: model.uri.toString(),
  10461. languageId: language,
  10462. version: model.getVersionId(),
  10463. text: model.getValue(),
  10464. },
  10465. },
  10466. };
  10467. languageSocket.send(JSON.stringify(openDocRequest));
  10468. initialized = true; // 初始化完成,这里确认逻辑待完善
  10469. };
  10470.  
  10471. // 初始化更新文件
  10472. updateFile(workspace, filename, fileExtension, model.getValue());
  10473. }
  10474.  
  10475. /**
  10476. * 注册语言及功能
  10477. */
  10478. OJBetter_monaco.RegistrationAfterInit = () => {
  10479. // 注册语言
  10480. monaco.languages.register({ id: language });
  10481.  
  10482. // 注册"Command"
  10483. (function registerCommand() {
  10484. serverInfo.capabilities.executeCommandProvider.commands.forEach(
  10485. (item) => {
  10486. pushLSPLogMessage("info", `${i18next.t('lsp.server.regist', { ns: 'logMessage' })}`, item);
  10487. monaco.editor.registerCommand(item, (accessor, ...args) => {
  10488. sendData({
  10489. jsonrpc: "2.0",
  10490. id: id++,
  10491. method: "workspace/executeCommand",
  10492. params: {
  10493. command: item,
  10494. arguments: args,
  10495. },
  10496. });
  10497. });
  10498. }
  10499. );
  10500. })();
  10501.  
  10502. // 注册"增量更新"
  10503. model.onDidChangeContent((event) => {
  10504. updateFile(workspace, filename, fileExtension, model.getValue()); // 更新文件
  10505. const changeDocRequest = {
  10506. jsonrpc: "2.0",
  10507. method: "textDocument/didChange",
  10508. params: {
  10509. textDocument: {
  10510. uri: model.uri.toString(),
  10511. version: model.getVersionId(),
  10512. },
  10513. contentChanges: event.changes.map((change) => ({
  10514. range: OJBetter_monaco.MonacoRangeTolspRange(change.range),
  10515. rangeLength: change.rangeLength,
  10516. text: change.text,
  10517. })),
  10518. },
  10519. };
  10520. sendData(changeDocRequest);
  10521. });
  10522.  
  10523. //注册"自动补全"
  10524. monaco.languages.registerCompletionItemProvider(language, {
  10525. provideCompletionItems: (model, position, context) => {
  10526. const request = {
  10527. jsonrpc: "2.0",
  10528. id: id++,
  10529. method: "textDocument/completion",
  10530. params: {
  10531. textDocument: {
  10532. uri: model.uri.toString(),
  10533. },
  10534. position: OJBetter_monaco.MonacoPositionTolspPosition(position),
  10535. context: {
  10536. triggerKind: context.triggerKind + 1, // 这里要+1,两边的定义不一样。。。
  10537. triggerCharacter: context.triggerCharacter,
  10538. },
  10539. },
  10540. };
  10541. return new Promise((resolve, reject) => {
  10542. fetchData(request, (response) => {
  10543. const result = response.result;
  10544. pushLSPLogMessage("info", `completion ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10545. if (!result) return resolve(null);
  10546. const CompletionItems = {
  10547. suggestions: result.items.map(
  10548. ({
  10549. label,
  10550. kind,
  10551. filterText,
  10552. insertText,
  10553. insertTextFormat,
  10554. sortText,
  10555. textEdit,
  10556. documentation,
  10557. additionalTextEdits,
  10558. }) => ({
  10559. additionalTextEdits: additionalTextEdits
  10560. ? additionalTextEdits.map(({ newText, range }) => ({
  10561. text: newText,
  10562. range: OJBetter_monaco.lspRangeToMonacoRange(range),
  10563. }))
  10564. : [],
  10565. documentation: documentation ? documentation.value : "",
  10566. filterText,
  10567. insertText: insertText ? insertText : textEdit.newText,
  10568. insertTextRules:
  10569. insertTextFormat === 2
  10570. ? monaco.languages.CompletionItemInsertTextRule
  10571. .InsertAsSnippet
  10572. : monaco.languages.CompletionItemInsertTextRule
  10573. .KeepWhitespace,
  10574. kind,
  10575. label,
  10576. sortText,
  10577. range: textEdit
  10578. ? textEdit.range
  10579. ? OJBetter_monaco.lspRangeToMonacoRange(textEdit.range)
  10580. : OJBetter_monaco.lspRangeToMonacoRange(textEdit.insert)
  10581. : null,
  10582. })
  10583. ),
  10584. };
  10585. pushLSPLogMessage("info", `completion ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, CompletionItems);
  10586. resolve(CompletionItems);
  10587. });
  10588. });
  10589. },
  10590. });
  10591.  
  10592. // 注册"代码修复"
  10593. monaco.languages.registerCodeActionProvider(language, {
  10594. provideCodeActions: (model, range, context) => {
  10595. const request = {
  10596. id: id++,
  10597. jsonrpc: "2.0",
  10598. method: "textDocument/codeAction",
  10599. params: {
  10600. textDocument: {
  10601. uri: model.uri.toString(),
  10602. },
  10603. range: OJBetter_monaco.MonacoRangeTolspRange(range),
  10604. context: {
  10605. diagnostics: context.markers.map((item) => ({
  10606. range: OJBetter_monaco.MonacoRangeTolspRange({
  10607. startLineNumber: item.startLineNumber,
  10608. startColumn: item.startColumn,
  10609. endLineNumber: item.endLineNumber,
  10610. endColumn: item.endColumn,
  10611. }),
  10612. severity: OJBetter_monaco.MonacoSeverityTolspSeverity(
  10613. item.severity
  10614. ),
  10615. code: item.code,
  10616. source: item.source,
  10617. message: item.message,
  10618. tags: item.tags,
  10619. relatedInformation: item.relatedInformation
  10620. ? item.relatedInformation.map((item) => ({
  10621. location: {
  10622. uri: item.resource.toString(),
  10623. range: OJBetter_monaco.MonacoRangeTolspRange({
  10624. startLineNumber: item.startLineNumber,
  10625. startColumn: item.startColumn,
  10626. endLineNumber: item.endLineNumber,
  10627. endColumn: item.endColumn,
  10628. }),
  10629. },
  10630. message: item.message,
  10631. }))
  10632. : null,
  10633. })),
  10634. only: context.only ? [context.only] : [],
  10635. triggerKind: context.trigger,
  10636. },
  10637. },
  10638. };
  10639.  
  10640. return new Promise((resolve, reject) => {
  10641. fetchData(request, (response) => {
  10642. const result = response.result;
  10643. pushLSPLogMessage("info", `codeAction ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10644. if (!result) return resolve(null);
  10645. const codeAction = {
  10646. actions: result.map((item) => ({
  10647. title: item.title,
  10648. kind: item.kind ? item.kind : "quickfix",
  10649. command: item.command
  10650. ? item.command.command
  10651. ? {
  10652. id: item.command.command,
  10653. arguments: item.command.arguments,
  10654. title: item.command.title,
  10655. }
  10656. : null
  10657. : null,
  10658. diagnostics: item.diagnostics
  10659. ? item.diagnostics.map((item) => ({
  10660. code: item.code,
  10661. message: item.message,
  10662. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  10663. severity: OJBetter_monaco.lspSeverityToMonacoSeverity(
  10664. item.severity
  10665. ),
  10666. source: item.source,
  10667. }))
  10668. : null,
  10669. edit: item.edit
  10670. ? OJBetter_monaco.lspEditToMonacoEdit(item.edit)
  10671. : item.arguments
  10672. ? {
  10673. edits: item.arguments.flatMap(
  10674. (item1) => OJBetter_monaco.lspEditToMonacoEdit(item1).edits
  10675. ),
  10676. }
  10677. : null,
  10678. })),
  10679. dispose: () => { },
  10680. };
  10681. pushLSPLogMessage("info", `codeAction ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, codeAction);
  10682.  
  10683. resolve(codeAction);
  10684. });
  10685. });
  10686. },
  10687. });
  10688.  
  10689. // 注册"hover提示"
  10690. monaco.languages.registerHoverProvider(language, {
  10691. provideHover: (model, position) => {
  10692. const request = {
  10693. jsonrpc: "2.0",
  10694. id: id++,
  10695. method: "textDocument/hover",
  10696. params: {
  10697. textDocument: {
  10698. uri: model.uri.toString(),
  10699. },
  10700. position: OJBetter_monaco.MonacoPositionTolspPosition(position),
  10701. },
  10702. };
  10703.  
  10704. return new Promise((resolve, reject) => {
  10705. fetchData(request, (response) => {
  10706. pushLSPLogMessage("info", `Hover ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10707. const result = response.result;
  10708.  
  10709. if (!result) return resolve(null);
  10710. const Hover = {
  10711. range: result.range
  10712. ? OJBetter_monaco.lspRangeToMonacoRange(result.range)
  10713. : new monaco.Range(
  10714. position.lineNumber,
  10715. position.column,
  10716. position.lineNumber,
  10717. position.column
  10718. ),
  10719. contents: Array.isArray(result.contents)
  10720. ? result.contents.map((item) => ({
  10721. value: item.value ? item.value : item,
  10722. }))
  10723. : [
  10724. {
  10725. value: result.contents.value,
  10726. },
  10727. ],
  10728. };
  10729. pushLSPLogMessage("info", `Hover ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, Hover);
  10730. resolve(Hover);
  10731. });
  10732. });
  10733. },
  10734. });
  10735.  
  10736. // 注册"inlay提示"
  10737. if (language == "cpp" || language == "java")
  10738. monaco.languages.registerInlayHintsProvider(language, {
  10739. provideInlayHints: (model, range, token) => {
  10740. return new Promise((resolve, reject) => {
  10741. const request = {
  10742. jsonrpc: "2.0",
  10743. id: id++,
  10744. method: "textDocument/inlayHint",
  10745. params: {
  10746. textDocument: {
  10747. uri: model.uri.toString(),
  10748. },
  10749. range: OJBetter_monaco.MonacoRangeTolspRange(range),
  10750. },
  10751. };
  10752.  
  10753. fetchData(request, (response) => {
  10754. const result = response.result;
  10755. pushLSPLogMessage("info", `Inlay Hints ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10756.  
  10757. if (!result) return resolve(null);
  10758.  
  10759. const inlayHints = {
  10760. hints: result.map((item) => {
  10761. return {
  10762. kind: item.kind,
  10763. label: item.label,
  10764. paddingLeft: item.paddingLeft,
  10765. paddingRight: item.paddingRight,
  10766. position: {
  10767. lineNumber: item.position.line + 1,
  10768. column: item.position.character + 1,
  10769. },
  10770. };
  10771. }),
  10772. };
  10773. pushLSPLogMessage("info", `Inlay Hints ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, inlayHints);
  10774.  
  10775. resolve(inlayHints);
  10776. });
  10777. });
  10778. },
  10779. });
  10780.  
  10781. // 注册"转到定义"
  10782. monaco.languages.registerDefinitionProvider(language, {
  10783. provideDefinition: (model, position) => {
  10784. const request = {
  10785. jsonrpc: "2.0",
  10786. id: id++,
  10787. method: "textDocument/definition",
  10788. params: {
  10789. textDocument: {
  10790. uri: model.uri.toString(),
  10791. },
  10792. position: OJBetter_monaco.MonacoPositionTolspPosition(position),
  10793. },
  10794. };
  10795.  
  10796. return new Promise((resolve, reject) => {
  10797. fetchData(request, (response) => {
  10798. const result = response.result;
  10799. pushLSPLogMessage("info", `definition ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10800.  
  10801. if (result.length == 0) return resolve(null);
  10802. const definition = result.map((item) => ({
  10803. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  10804. uri: monaco.Uri.parse(item.uri), //
  10805. }));
  10806. pushLSPLogMessage("info", `definition ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, definition);
  10807.  
  10808. resolve(definition);
  10809. });
  10810. });
  10811.  
  10812. return null; // 如果没有内容,则返回null
  10813. },
  10814. });
  10815.  
  10816. // 注册"转到引用"
  10817. monaco.languages.registerReferenceProvider(language, {
  10818. provideReferences: (model, position, context) => {
  10819. const request = {
  10820. jsonrpc: "2.0",
  10821. id: id++,
  10822. method: "textDocument/references",
  10823. params: {
  10824. context: context,
  10825. textDocument: {
  10826. uri: model.uri.toString(),
  10827. },
  10828. position: OJBetter_monaco.MonacoPositionTolspPosition(position),
  10829. },
  10830. };
  10831.  
  10832. return new Promise((resolve, reject) => {
  10833. fetchData(request, (response) => {
  10834. const result = response.result;
  10835. pushLSPLogMessage("info", `references ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10836.  
  10837. if (result.length == 0) return resolve([]);
  10838.  
  10839. const references = result.map((item) => ({
  10840. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  10841. uri: monaco.Uri.parse(item.uri), //
  10842. }));
  10843. pushLSPLogMessage("info", `references ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, references);
  10844. resolve(references);
  10845. });
  10846. });
  10847. return []; // 如果没有内容,则返回空数组
  10848. },
  10849. });
  10850.  
  10851. // 注册"符号引用点击高亮"
  10852. monaco.languages.registerDocumentHighlightProvider(language, {
  10853. provideDocumentHighlights: (model, position) => {
  10854. const request = {
  10855. jsonrpc: "2.0",
  10856. id: id++,
  10857. method: "textDocument/documentHighlight",
  10858. params: {
  10859. textDocument: {
  10860. uri: model.uri.toString(),
  10861. },
  10862. position: OJBetter_monaco.MonacoPositionTolspPosition(position),
  10863. },
  10864. };
  10865.  
  10866. return new Promise((resolve, reject) => {
  10867. fetchData(request, (response) => {
  10868. const result = response.result;
  10869. pushLSPLogMessage("info", `documentHighlight ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10870.  
  10871. if (!result || result.length == 0) return resolve([]);
  10872. const highlights = result.map((item) => ({
  10873. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  10874. kind: item.kind,
  10875. }));
  10876. pushLSPLogMessage("info",
  10877. `documentHighlight ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`,
  10878. highlights
  10879. );
  10880.  
  10881. resolve(highlights);
  10882. });
  10883. });
  10884. return []; // 如果没有内容,则返回空数组
  10885. },
  10886. });
  10887.  
  10888. // 注册"文件链接"
  10889. if (language == "cpp" || language == "java")
  10890. monaco.languages.registerLinkProvider(language, {
  10891. provideLinks: (model) => {
  10892. const request = {
  10893. jsonrpc: "2.0",
  10894. id: id++,
  10895. method: "textDocument/documentLink",
  10896. params: {
  10897. textDocument: {
  10898. uri: model.uri.toString(),
  10899. },
  10900. },
  10901. };
  10902.  
  10903. return new Promise((resolve, reject) => {
  10904. fetchData(request, (response) => {
  10905. const result = response.result;
  10906. pushLSPLogMessage("info", `DocumentLink ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10907.  
  10908. if (!result) return resolve(null);
  10909. const links = {
  10910. links: result.map((item) => ({
  10911. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  10912. url: item.target.toString(),
  10913. tooltip: item.tooltip ? item.tooltip : null,
  10914. })),
  10915. };
  10916. pushLSPLogMessage("info", `DocumentLink ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, links);
  10917. resolve(links);
  10918. });
  10919. });
  10920. },
  10921. });
  10922.  
  10923. // 注册"格式化"
  10924. monaco.languages.registerDocumentFormattingEditProvider(language, {
  10925. provideDocumentFormattingEdits: (model, options, token) => {
  10926. const request = {
  10927. jsonrpc: "2.0",
  10928. id: id++,
  10929. method: "textDocument/formatting",
  10930. params: {
  10931. textDocument: {
  10932. uri: model.uri.toString(),
  10933. },
  10934. options: options,
  10935. },
  10936. };
  10937.  
  10938. return new Promise((resolve, reject) => {
  10939. fetchData(request, (response) => {
  10940. const result = response.result;
  10941. pushLSPLogMessage("info", `formatting ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10942.  
  10943. const TextEdit = result.map((edit) => ({
  10944. range: OJBetter_monaco.lspRangeToMonacoRange(edit.range),
  10945. text: edit.newText,
  10946. }));
  10947. pushLSPLogMessage("info", `formatting ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, TextEdit);
  10948. resolve(TextEdit);
  10949. });
  10950. });
  10951. },
  10952. });
  10953.  
  10954. // 注册"部分格式化"
  10955. monaco.languages.registerDocumentRangeFormattingEditProvider(language, {
  10956. provideDocumentRangeFormattingEdits: (model, range, options) => {
  10957. const request = {
  10958. jsonrpc: "2.0",
  10959. id: id++,
  10960. method: "textDocument/rangeFormatting",
  10961. params: {
  10962. textDocument: {
  10963. uri: model.uri.toString(),
  10964. },
  10965. range: OJBetter_monaco.MonacoRangeTolspRange(range),
  10966. options,
  10967. },
  10968. };
  10969.  
  10970. return new Promise((resolve, reject) => {
  10971. fetchData(request, (response) => {
  10972. const result = response.result;
  10973. pushLSPLogMessage("info", `rangeFormatting ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  10974.  
  10975. if (!result || result.length == 0) return resolve([]);
  10976. const edits = result.map((item) => ({
  10977. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  10978. text: item.newText,
  10979. }));
  10980. pushLSPLogMessage("info", `rangeFormatting ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, edits);
  10981. resolve(edits);
  10982. });
  10983. });
  10984. },
  10985. });
  10986.  
  10987. // 注册"重命名"
  10988. monaco.languages.registerRenameProvider(language, {
  10989. provideRenameEdits: (model, position, newName, token) => {
  10990. const request = {
  10991. jsonrpc: "2.0",
  10992. id: id++,
  10993. method: "textDocument/rename",
  10994. params: {
  10995. textDocument: {
  10996. uri: model.uri.toString(),
  10997. },
  10998. position: OJBetter_monaco.MonacoPositionTolspPosition(position),
  10999. newName: newName,
  11000. },
  11001. };
  11002.  
  11003. return new Promise((resolve, reject) => {
  11004. fetchData(request, (response) => {
  11005. const result = response.result;
  11006. pushLSPLogMessage("info", `rename ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  11007.  
  11008. const rename = OJBetter_monaco.lspEditToMonacoEdit(result);
  11009. pushLSPLogMessage("info", `rename ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, rename);
  11010. resolve(rename);
  11011. });
  11012. });
  11013. },
  11014. });
  11015.  
  11016. // 注册"折叠范围分析"
  11017. monaco.languages.registerFoldingRangeProvider(language, {
  11018. provideFoldingRanges: (model) => {
  11019. const request = {
  11020. jsonrpc: "2.0",
  11021. id: id++,
  11022. method: "textDocument/foldingRange",
  11023. params: {
  11024. textDocument: {
  11025. uri: model.uri.toString(),
  11026. },
  11027. },
  11028. };
  11029.  
  11030. return new Promise((resolve, reject) => {
  11031. fetchData(request, (response) => {
  11032. const result = response.result;
  11033. pushLSPLogMessage("info", `FoldingRange ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  11034.  
  11035. if (!result) return resolve([]);
  11036. const foldingRanges = result.map((item) => ({
  11037. start: item.startLine + 1,
  11038. end: item.endLine + 1,
  11039. kind: monaco.languages.FoldingRangeKind.fromValue(item.kind),
  11040. }));
  11041. pushLSPLogMessage("info", `FoldingRange ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, foldingRanges);
  11042. resolve(foldingRanges);
  11043. });
  11044. });
  11045. },
  11046. });
  11047.  
  11048. // 注册"方法签名提示"
  11049. monaco.languages.registerSignatureHelpProvider(language, {
  11050. signatureHelpTriggerCharacters:
  11051. serverInfo.capabilities.signatureHelpProvider.triggerCharacters,
  11052. provideSignatureHelp: (model, position, token, context) => {
  11053. const request = {
  11054. jsonrpc: "2.0",
  11055. id: id++,
  11056. method: "textDocument/signatureHelp",
  11057. params: {
  11058. textDocument: {
  11059. uri: model.uri.toString(),
  11060. },
  11061. position: {
  11062. line: position.lineNumber - 1,
  11063. character: position.column - 1,
  11064. },
  11065. context: {
  11066. triggerKind: context.triggerKind,
  11067. triggerCharacter: context.triggerCharacter,
  11068. isRetrigger: context.isRetrigger,
  11069. activeSignatureHelp: context.activeSignatureHelp,
  11070. },
  11071. },
  11072. };
  11073.  
  11074. return new Promise((resolve, reject) => {
  11075. fetchData(request, (response) => {
  11076. const result = response.result;
  11077.  
  11078. pushLSPLogMessage("info", `signatureHelp ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  11079.  
  11080. if (!result) return resolve(null);
  11081. const SignatureHelpResult = {
  11082. value: {
  11083. activeParameter: result.activeParameter,
  11084. activeSignature: result.activeSignature,
  11085. signatures: result.signatures,
  11086. },
  11087. dispose: () => { },
  11088. };
  11089.  
  11090. pushLSPLogMessage("info",
  11091. `signatureHelp ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`,
  11092. SignatureHelpResult
  11093. );
  11094. resolve(SignatureHelpResult);
  11095. });
  11096. });
  11097. },
  11098. });
  11099.  
  11100. // 注册"渐进式自动格式化" 如果server有这个
  11101. if (serverInfo.capabilities.documentOnTypeFormattingProvider)
  11102. monaco.languages.registerOnTypeFormattingEditProvider(language, {
  11103. autoFormatTriggerCharacters: [
  11104. serverInfo.capabilities.documentOnTypeFormattingProvider
  11105. .firstTriggerCharacter,
  11106. ],
  11107. provideOnTypeFormattingEdits: (model, position, ch, options) => {
  11108. const request = {
  11109. jsonrpc: "2.0",
  11110. id: id++,
  11111. method: "textDocument/onTypeFormatting",
  11112. params: {
  11113. textDocument: {
  11114. uri: model.uri.toString(),
  11115. },
  11116. position: OJBetter_monaco.MonacoPositionTolspPosition(position),
  11117. ch,
  11118. options,
  11119. },
  11120. };
  11121.  
  11122. return new Promise((resolve, reject) => {
  11123. fetchData(request, (response) => {
  11124. const result = response.result;
  11125. pushLSPLogMessage("info", `onTypeFormatting ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, response);
  11126.  
  11127. if (!result || result.length == 0) return resolve([]);
  11128.  
  11129. const edits = result.map((item) => ({
  11130. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  11131. text: item.newText,
  11132. }));
  11133. pushLSPLogMessage("info", `onTypeFormatting ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, edits);
  11134. resolve(edits);
  11135. });
  11136. });
  11137. },
  11138. });
  11139. };
  11140.  
  11141. /**
  11142. * 被动式接收处理
  11143. */
  11144. OJBetter_monaco.PassiveReceiveHandler = () => {
  11145.  
  11146. // "实时代码诊断"
  11147. OJBetter_monaco.updateMarkers = function (message) {
  11148. const params = message.params;
  11149. pushLSPLogMessage("info", `Markers ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, message);
  11150.  
  11151. if (!params) return;
  11152. const markers = params.diagnostics.map((item1) => ({
  11153. code: item1.code,
  11154. message: item1.message,
  11155. ...OJBetter_monaco.lspRangeToMonacoRange(item1.range),
  11156. relatedInformation: item1.relatedInformation
  11157. ? item1.relatedInformation.map((item2) => ({
  11158. ...(item2.location.range
  11159. ? OJBetter_monaco.lspRangeToMonacoRange(item2.location.range)
  11160. : OJBetter_monaco.lspRangeToMonacoRange(item2.location)),
  11161. message: item2.message,
  11162. resource: monaco.Uri.parse(item2.location.uri),
  11163. }))
  11164. : null,
  11165. severity: OJBetter_monaco.lspSeverityToMonacoSeverity(item1.severity),
  11166. source: item1.source,
  11167. }));
  11168.  
  11169. pushLSPLogMessage("info", `Markers ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, markers);
  11170. monaco.editor.setModelMarkers(model, "eslint", markers);
  11171.  
  11172. // 更新状态底栏信息
  11173. const nowMarks = monaco.editor.getModelMarkers();
  11174. warningCount = 0;
  11175. errorCount = 0;
  11176. for (const marker of nowMarks) {
  11177. if (marker.severity === monaco.MarkerSeverity.Warning) {
  11178. warningCount++;
  11179. } else if (marker.severity === monaco.MarkerSeverity.Error) {
  11180. errorCount++;
  11181. }
  11182. }
  11183. $('#OJBetter_statusBar').text(`Warnings: ${warningCount}, Errors: ${errorCount}`);
  11184. };
  11185.  
  11186. // "应用服务器推送的更改"(代码修复)
  11187. OJBetter_monaco.applyEdit = function (message) {
  11188. const params = message.params;
  11189. pushLSPLogMessage("info", `applyEdit ${i18next.t('lsp.server.receive', { ns: 'logMessage' })}`, message);
  11190.  
  11191. if (!params) return;
  11192. const operations = Object.values(params.edit.changes)
  11193. .flat()
  11194. .map((item) => ({
  11195. range: OJBetter_monaco.lspRangeToMonacoRange(item.range),
  11196. text: item.newText,
  11197. }));
  11198.  
  11199. pushLSPLogMessage("info", `applyEdit ${i18next.t('lsp.server.transmit', { ns: 'logMessage' })}`, operations);
  11200. model.pushEditOperations([], operations, () => null); // 入栈编辑操作
  11201. };
  11202. }
  11203.  
  11204. if (!languageSocketState) await waitForLanguageSocketState();
  11205. OJBetter_monaco.Initialize();
  11206. }
  11207.  
  11208. // 语言更改
  11209. function changeMonacoLanguage(form) {
  11210. let nowSelect = form.selectLang.val();
  11211. // 记忆更改
  11212. GM_setValue('compilerSelection', nowSelect);
  11213. // 销毁旧的编辑器
  11214. try {
  11215. if (OJBetter.monaco.editor) OJBetter.monaco.editor.dispose();
  11216. } catch (error) {
  11217. console.warn("Encountered an error while attempting to delete the old editor, but it should not affect your regular usage.", error)
  11218. }
  11219. // 关闭旧的socket
  11220. OJBetter.monaco.lsp.socket.forEach(socket => {
  11221. socket.close();
  11222. });
  11223. // 移除相关元素
  11224. form.topRightDiv.empty();
  11225. $('#LSPLog').remove();
  11226. $('#OJBetter_statusBar').remove();
  11227. // 创建新的编辑器
  11228. if (nowSelect in value_monacoLanguageMap) {
  11229. let language = value_monacoLanguageMap[nowSelect];
  11230. if (language == "python" || language == "cpp") {
  11231. createMonacoEditor(language, form, true);
  11232. } else {
  11233. createMonacoEditor(language, form, false);
  11234. }
  11235. } else {
  11236. createMonacoEditor(null, false);
  11237. }
  11238. // 更新在线编译器参数
  11239. changeCompilerArgs(nowSelect);
  11240. }
  11241.  
  11242. // 收集样例数据
  11243. function getTestData() {
  11244. let testData = {};
  11245.  
  11246. /**
  11247. * 从pre中获取文本信息
  11248. * @param {JQuery<HTMLElement>} node 元素
  11249. * @returns {string} 文本信息
  11250. */
  11251. function getTextFromPre(node) {
  11252. let text;
  11253. if (node.find("br").length > 0) {
  11254. text = node.html().replace(/<br>/g, "\n"); // <br>作换行符的情况
  11255. } else {
  11256. text = node.text();
  11257. }
  11258. return text;
  11259. }
  11260.  
  11261. // $('.input').each(function (index) {
  11262. // var inputText = '';
  11263. // if ($(this).find('pre').find('div').length > 0) {
  11264. // $(this).find('pre').find('div').each(function () {
  11265. // inputText += getTextFromPre($(this)) + '\n';
  11266. // });
  11267. // } else {
  11268. // inputText = getTextFromPre($(this).find('pre'));
  11269. // }
  11270. // var outputText = '';
  11271. // if ($('.output').eq(index).find('pre').find('div').length > 0) {
  11272. // $('.output').eq(index).find('pre').find('div').each(function () {
  11273. // inputText += getTextFromPre($(this)) + '\n';
  11274. // });
  11275. // } else {
  11276. // outputText = getTextFromPre($('.output').eq(index).find('pre'));
  11277. // }
  11278.  
  11279. // testData[index + 1] = {
  11280. // input: inputText.trim(),
  11281. // output: outputText.trim()
  11282. // };
  11283. // });
  11284.  
  11285. // 需要过滤重复的样例(因为有日文英文两个页面,样例元素重复了两遍)
  11286. let uniqueTestData = [];
  11287. const filteredPreElements = $('pre').clone().filter((index, element) => element.id.startsWith('pre-sample'));
  11288. for (let i = 0; i < filteredPreElements.length; i += 2) {
  11289. if (i + 1 < filteredPreElements.length) {
  11290. const inputElement = $(filteredPreElements[i]);
  11291. const outputElement = $(filteredPreElements[i + 1]);
  11292.  
  11293. const inputText = getTextFromPre(inputElement).trim();
  11294. const outputText = getTextFromPre(outputElement).trim();
  11295.  
  11296. // 检查是否已经存在相同的样例
  11297. let isDuplicate = uniqueTestData.some(testCase => testCase.input === inputText && testCase.output === outputText);
  11298. if (!isDuplicate) {
  11299. uniqueTestData.push({
  11300. input: inputText,
  11301. output: outputText
  11302. });
  11303. }
  11304. }
  11305. }
  11306.  
  11307. // 把唯一的测试数据赋值给testData,保持原有的索引风格
  11308. uniqueTestData.forEach((testCase, index) => {
  11309. testData[index + 1] = testCase;
  11310. });
  11311.  
  11312. return testData;
  11313. }
  11314.  
  11315. // 初始化自定义测试数据面板
  11316. function CustomTestInit() {
  11317. const url = window.location.href;
  11318.  
  11319. restoreText();
  11320.  
  11321. // 添加
  11322. $('#addCustomTest').click(function () {
  11323. var sampleDiv = $('<div class="sampleDiv">');
  11324. var inputTextarea = $('<p style="padding: 0px 5px;">input</p><textarea class="dynamicTextarea inputTextarea"></textarea>');
  11325. var outputTextarea = $('<p style="padding: 0px 5px;">output</p><textarea class="dynamicTextarea outputTextarea"></textarea>');
  11326. var deleteCustomTest = OJB_safeCreateJQElement(`<button type="button" class="deleteCustomTest">${closeIcon}</button>`);
  11327. sampleDiv.append(deleteCustomTest);
  11328. sampleDiv.append(inputTextarea);
  11329. sampleDiv.append(outputTextarea);
  11330. $('#customTests').append(sampleDiv);
  11331. });
  11332.  
  11333. // 实时保存文本内容到 IndexedDB 中
  11334. $(document).on('input', '.inputTextarea, .outputTextarea', function () {
  11335. OJBetter.common.database.transaction('rw', OJBetter.common.database.samplesData, function () {
  11336. var objectStore = OJBetter.common.database.samplesData;
  11337. var samples = {
  11338. url: url,
  11339. samples: []
  11340. };
  11341. var index = 0;
  11342. $('.sampleDiv').each(function () {
  11343. var $sampleDiv = $(this);
  11344. var inputTextarea = $sampleDiv.find('.inputTextarea');
  11345. var outputTextarea = $sampleDiv.find('.outputTextarea');
  11346. $sampleDiv.attr('data-index', index);
  11347. inputTextarea.attr('id', 'input' + index);
  11348. outputTextarea.attr('id', 'output' + index);
  11349. var sample = {
  11350. id: index,
  11351. input: inputTextarea.val(),
  11352. output: outputTextarea.val()
  11353. };
  11354. samples.samples.push(sample);
  11355. index++;
  11356. });
  11357. objectStore.put(samples);
  11358. });
  11359. });
  11360.  
  11361. // 删除
  11362. $(document).on('click', '.deleteCustomTest', function () {
  11363. var $sampleDiv = $(this).closest('.sampleDiv');
  11364. OJBetter.common.database.transaction('rw', OJBetter.common.database.samplesData, function () {
  11365. var objectStore = OJBetter.common.database.samplesData;
  11366. var index = parseInt($sampleDiv.attr('data-index'));
  11367. if (!isNaN(index)) {
  11368. objectStore.get(url).then(row => {
  11369. let samples = row.samples;
  11370. samples.splice(index, 1); // 移除第index个元素
  11371. objectStore.put({
  11372. url: url,
  11373. samples: samples
  11374. });
  11375. })
  11376. }
  11377. $sampleDiv.remove();
  11378. });
  11379. });
  11380.  
  11381. // 恢复保存的内容
  11382. function restoreText() {
  11383. OJBetter.common.database.transaction('r', OJBetter.common.database.samplesData, function () {
  11384. return OJBetter.common.database.samplesData.get(url);
  11385. }).then(function (data) {
  11386. if (data.samples && data.samples.length > 0) {
  11387. data.samples.forEach(function (item, index) {
  11388. var sampleDiv = $('<div class="sampleDiv">');
  11389. var inputTextarea = OJB_safeCreateJQElement(`<p style="padding: 0px 5px;">input</p><textarea id="input${index}" class="dynamicTextarea inputTextarea"></textarea>`);
  11390. var outputTextarea = OJB_safeCreateJQElement(`<p style="padding: 0px 5px;">output</p><textarea id="output${index}" class="dynamicTextarea outputTextarea"></textarea>`);
  11391. var deleteCustomTest = OJB_safeCreateJQElement(`<button type="button" class="deleteCustomTest">${closeIcon}</button>`);
  11392.  
  11393. inputTextarea.val(item.input);
  11394. outputTextarea.val(item.output);
  11395.  
  11396. sampleDiv.append(deleteCustomTest);
  11397. sampleDiv.append(inputTextarea);
  11398. sampleDiv.append(outputTextarea);
  11399. sampleDiv.attr('data-index', index)
  11400. $('#customTests').append(sampleDiv);
  11401. });
  11402. }
  11403. });
  11404. }
  11405. }
  11406.  
  11407. // 获取自定义测试数据
  11408. function getCustomTestData() {
  11409. const url = window.location.href;
  11410.  
  11411. return new Promise(function (resolve) {
  11412. var customTestData = {};
  11413. OJBetter.common.database.transaction('r', OJBetter.common.database.samplesData, function () {
  11414. return OJBetter.common.database.samplesData.get(url);
  11415. }).then(function (data) {
  11416. if (!data) resolve(customTestData);
  11417. if (data.samples && data.samples.length > 0) {
  11418. data.samples.forEach(function (item, index) {
  11419. customTestData[index + 1] = {
  11420. input: item.input,
  11421. output: item.output
  11422. };
  11423. });
  11424. }
  11425. resolve(customTestData);
  11426. });
  11427. });
  11428. }
  11429.  
  11430. // codeforces编译器参数列表
  11431. let officialLanguage = "";
  11432. function officialCompilerArgsChange(nowSelect) {
  11433. officialLanguage = nowSelect;
  11434. $('#CompilerArgsInput').prop("disabled", true);
  11435. }
  11436.  
  11437. // codeforces编译器通信
  11438. async function officialCompiler(code, input) {
  11439. // const data = new FormData();
  11440. // data.append('csrf_token', OJBetter.common.cf_csrf_token);
  11441. const data = new URLSearchParams();
  11442. data.append('csrf_token', OJBetter.common.at_csrf_token);
  11443. // data.append('source', code);
  11444. // data.append('tabSize', '4');
  11445. // data.append('programTypeId', officialLanguage);
  11446. data.append('data.LanguageId', officialLanguage);
  11447. data.append('input', input);
  11448. // data.append('output', '');
  11449. // data.append('communityCode', '');
  11450. // data.append('action', 'submitSourceCode');
  11451. // data.append('programTypeId', officialLanguage);
  11452. data.append('sourceCode', code);
  11453.  
  11454. const requestOptions = {
  11455. method: 'POST',
  11456. // url: `${OJBetter.common.hostAddress}/data/customtest`,
  11457. url: `${OJBetter.common.hostAddress}/contests/arc172/custom_test/submit/json`,
  11458. data: data,
  11459. headers: {
  11460. // 'X-Csrf-Token': OJBetter.common.cf_csrf_token
  11461. 'Content-Type': 'application/x-www-form-urlencoded'
  11462. }
  11463. };
  11464.  
  11465. const result = {
  11466. Errors: '',
  11467. Result: '',
  11468. Stats: ''
  11469. };
  11470.  
  11471. try {
  11472. const submitResponse = await OJB_GMRequest(requestOptions);
  11473. // if (submitResponse.status !== 200 || !submitResponse.response) {
  11474. // result.Errors = `${i18next.t('compiler.official.pushError', { ns: 'codeEditor' })}`;
  11475. // return result;
  11476. // }
  11477. if (submitResponse.status !== 200) {
  11478. result.Errors = `${i18next.t('compiler.official.pushError', { ns: 'codeEditor' })}`;
  11479. return result;
  11480. }
  11481.  
  11482. // const submitResult = JSON.parse(submitResponse.response);
  11483. // const customTestSubmitId = submitResult.customTestSubmitId;
  11484.  
  11485. const verdictResponse = await OJB_promiseRetryWrapper(
  11486. getOfficialCompilerVerdict,
  11487. {
  11488. maxRetries: 10,
  11489. retryInterval: 500
  11490. },
  11491. // customTestSubmitId
  11492. );
  11493. return verdictResponse;
  11494. } catch (error) {
  11495. result.Errors = error.message;
  11496. return result;
  11497. }
  11498. }
  11499.  
  11500. // 获取codeforces编译器的执行结果
  11501. // async function getOfficialCompilerVerdict(customTestSubmitId) {
  11502. async function getOfficialCompilerVerdict() {
  11503. // const newdata = new FormData();
  11504. // newdata.append('csrf_token', OJBetter.common.cf_csrf_token);
  11505. // newdata.append('action', 'getVerdict');
  11506. // newdata.append('customTestSubmitId', customTestSubmitId);
  11507.  
  11508. // const requestOptions = {
  11509. // method: 'POST',
  11510. // url: `${OJBetter.common.hostAddress}/data/customtest`,
  11511. // data: newdata,
  11512. // headers: {
  11513. // 'X-Csrf-Token': OJBetter.common.cf_csrf_token
  11514. // }
  11515. // };
  11516. const requestOptions = {
  11517. method: 'GET',
  11518. url: `https://atcoder.jp/contests/arc172/custom_test/json?reload=true`,
  11519. };
  11520.  
  11521. const responseDetails = await OJB_GMRequest(requestOptions);
  11522. if (responseDetails.status !== 200 || !responseDetails.response) {
  11523. throw new Error(`${i18next.t('compiler.official.getResultError', { ns: 'codeEditor' })}`);
  11524. }
  11525.  
  11526. const response = JSON.parse(responseDetails.response);
  11527. // if (!response.stat) {
  11528. // throw new Error('Verdict not ready, retrying...');
  11529. // }
  11530. if (response.Interval) {
  11531. throw new Error('Verdict not ready, retrying...');
  11532. }
  11533.  
  11534. // return {
  11535. // Errors: response.verdict === "OK" ? null : response.verdict + '<br>' + response.output,
  11536. // Result: response.output.replace(/\r\n/g, "\n"),
  11537. // Stats: `Status: ${response.stat}`
  11538. // };
  11539. return {
  11540. Errors: response.Result.ExitCode === "0" ? null : response.Stderr,
  11541. Result: response.Stdout.replace(/\r\n/g, "\n"),
  11542. Stats: `Status: ExitCode: ${response.Result.ExitCode} Exec Time: ${response.Result.TimeConsumption} ms Memory: ${response.Result.MemoryConsumption} KB`
  11543. };
  11544. }
  11545.  
  11546. // rextester编译器参数列表
  11547. let rextesterLanguage = "";
  11548. function rextesterCompilerArgsChange(nowSelect) {
  11549. // let LanguageChoiceList = {
  11550. // "4": "9", "6": "8", "7": "5", "9": "1", "13": "13", "19": "42", "20": "21", "28": "30", "31": "24", "32": "20",
  11551. // "34": "17", "36": "4", "43": "6", "45": "7", "46": "4", "50": "7", "51": "9", "52": "27", "54": "7", "55": "23", "60": "4",
  11552. // "61": "7", "65": "1", "67": "12", "70": "5", "73": "7", "74": "4", "75": "46", "77": "43", "79": "1", "80": "27", "83": "43", "87": "4"
  11553. // }
  11554. let LanguageChoiceList = {
  11555. "5001": "7", "5002": "20", "5003": "1", "5005": "4", "5009": "17", "5016": "8", "5037": "13", "5041": "9",
  11556. "5047": "21", "5055": "5", "5058": "17", "5063": "5", "5078": "5", "5082": "5"
  11557. }
  11558.  
  11559. let CompilerArgsList = {
  11560. "6": "-Wall -std=gnu99 -O2 -o a.out source_file.c",
  11561. "7": "-Wall -std=c++14 -O2 -o a.out source_file.cpp",
  11562. "20": "-o a.out source_file.go",
  11563. "27": "-Wall -std=c++14 -stdlib=libc++ -O2 -o a.out source_file.cpp",
  11564. "30": "source_file.d -ofa.out"
  11565. }
  11566. if (nowSelect in LanguageChoiceList) {
  11567. $('#RunTestButton').prop("disabled", false);
  11568. rextesterLanguage = LanguageChoiceList[nowSelect];
  11569. } else {
  11570. $('#RunTestButton').prop("disabled", true);
  11571. }
  11572. if (rextesterLanguage in CompilerArgsList) {
  11573. const rextesterCompilerArgs = CompilerArgsList[rextesterLanguage];
  11574. $('#CompilerArgsInput').val(rextesterCompilerArgs);
  11575. } else {
  11576. $('#CompilerArgsInput').val("");
  11577. }
  11578. }
  11579.  
  11580. // rextester编译器通信
  11581. async function rextesterCompiler(code, input) {
  11582. try {
  11583. const result = await OJB_promiseRetryWrapper(rextesterCompilerRequest, {
  11584. maxRetries: 5,
  11585. retryInterval: 500,
  11586. errorHandler: (err) => ({ Errors: err.message, Result: '', Stats: '' })
  11587. }, code, input);
  11588. return result;
  11589. } catch (error) {
  11590. return { Errors: error.message, Result: '', Stats: '' };
  11591. }
  11592. }
  11593.  
  11594. // rextester编译器请求方法
  11595. async function rextesterCompilerRequest(code, input) {
  11596. const data = new FormData();
  11597. data.append('LanguageChoiceWrapper', rextesterLanguage);
  11598. data.append('EditorChoiceWrapper', '1');
  11599. data.append('LayoutChoiceWrapper', '1');
  11600. data.append('Program', code);
  11601. data.append('CompilerArgs', $('#CompilerArgsInput').val());
  11602. data.append('Input', input);
  11603. data.append('ShowWarnings', 'false');
  11604. data.append('IsInEditMode', 'false');
  11605. data.append('IsLive', 'false');
  11606.  
  11607. const responseDetails = await OJB_GMRequest({
  11608. method: 'POST',
  11609. url: 'https://rextester.com/rundotnet/Run',
  11610. data: data
  11611. });
  11612.  
  11613. if (responseDetails.status !== 200 || !responseDetails.response) {
  11614. throw new Error(`${i18next.t('compiler.common.error', { ns: 'codeEditor' })}`);
  11615. }
  11616.  
  11617. const response = JSON.parse(responseDetails.response);
  11618. return {
  11619. Errors: response.Errors || '',
  11620. Result: response.Result || '',
  11621. Stats: response.Stats || ''
  11622. };
  11623. }
  11624.  
  11625. // wandbox编译器参数列表
  11626. var wandboxlist = JSON.parse(GM_getResourceText("wandboxlist"));
  11627. function wandboxCompilerArgsChange(nowSelect) {
  11628. // let LanguageChoiceList = {
  11629. // "6": "PHP", "7": "Python", "9": "C#", "12": "Haskell", "13": "Perl", "19": "OCaml",
  11630. // "20": "Scala", "28": "D", "31": "Python", "32": "Go", "34": "JavaScript", "36": "Java", "40": "Python", "41": "Python",
  11631. // "43": "C++", "50": "C++", "51": "Pascal", "52": "C++", "54": "C++", "60": "Java", "61": "C++", "65": "C#", "67": "Ruby",
  11632. // "70": "Python", "73": "C++", "74": "Java", "75": "Rust", "79": "C#", "80": "C++", "87": "Java"
  11633. // }
  11634. let LanguageChoiceList = {
  11635. "5001": "C++", "5002": "Go", "5003": "C#", "5005": "Java", "5009": "JavaScript", "5010": "JavaScript",
  11636. "5012": "D", "5013": "D", "5016": "PHP", "5017": "C++", "5018": "Ruby", "5025": "Haskell",
  11637. "5027": "Lua", "5028": "C++", "5031": "C++", "5037": "Perl", "5041": "Pascal", "5042": "C#",
  11638. "5043": "Lua", "5047": "Scala", "5055": "Python", "5056": "Scala", "5059": "OCaml", "5062": "Lisp",
  11639. "5063": "Python", "5077": "D", "5078": "Python", "5081": "OCaml", "5082": "Python"
  11640. }
  11641.  
  11642. // 移除旧的
  11643. $('#CompilerChange').remove();
  11644.  
  11645. if (nowSelect in LanguageChoiceList) {
  11646. $('#RunTestButton').prop("disabled", false);
  11647. const Languagefiltered = wandboxlist.filter(obj => obj.language === LanguageChoiceList[nowSelect]);
  11648.  
  11649. // 创建编译器下拉框
  11650. let CompilerChange = $('<select id="CompilerChange" style="width: 100%;"></select>');
  11651.  
  11652. $('#CompilerSetting').show().append(CompilerChange);
  11653. for (let i = 0; i < Languagefiltered.length; i++) {
  11654. let Compiler = Languagefiltered[i];
  11655. let op = $("<option></option>")
  11656. .val(Compiler.name)
  11657. .text(Compiler["display-name"] + " " + Compiler.version);
  11658. $("#CompilerChange").append(op);
  11659. }
  11660.  
  11661. // 编译器参数刷新
  11662. function refreshCompilerArgs() {
  11663. var flags = '';
  11664. $("#CompilerBox").find("*").each(function () {
  11665. if ($(this).is("input[type='checkbox']")) {
  11666. let flag = $(this).prop("checked") ? $(this).val() : '';
  11667. flags += flag + (flag ? ' ' : '');
  11668. } else if ($(this).is("select") || $(this).is("input") || $(this).is("textarea")) {
  11669. let flag = $(this).val();
  11670. flags += flag + (flag ? ' ' : '');
  11671. }
  11672. });
  11673. $("#CompilerArgsInput").val(flags);
  11674. $("#CompilerArgsInput").prop("readonly", true); // 只读
  11675. }
  11676.  
  11677. // 编译器切换监听
  11678. CompilerChange.change(function () {
  11679. let selectedName = CompilerChange.val();
  11680. let Compiler = Languagefiltered.find(
  11681. (obj) => obj.name === selectedName
  11682. );
  11683.  
  11684. $("#CompilerArgsInput").val(); // 初始化编译器输入框
  11685.  
  11686. $("#CompilerBox").remove();
  11687. let div = $("<div id='CompilerBox'></div>");
  11688.  
  11689. let display_compile_command = OJB_safeCreateJQElement(`<input id='${Compiler.name}' value='${Compiler['display-compile-command']}' style="display:none;"}></input>`);
  11690. div.append(display_compile_command);
  11691.  
  11692. let switches = Compiler.switches;
  11693. for (let i = 0; i < switches.length; i++) {
  11694. let switche = switches[i];
  11695.  
  11696. if (switche.type == "single") {
  11697. let single = OJB_safeCreateJQElement(`
  11698. <div>
  11699. <input type='checkbox' id='${switche.name}' value='${switche['display-flags']}' ${switche.default ? 'checked' : ''}></input>
  11700. <label for='${switche.name}'>${switche['display-name']}</label>
  11701. </div>
  11702. `);
  11703. div.append(single);
  11704. single.find("input").change(function () {
  11705. refreshCompilerArgs();
  11706. });
  11707. } else if (switche.type == "select") {
  11708. let select = OJB_safeCreateJQElement(`<select id='${switche.name}'></select>`);
  11709. select.data('previousValue', switche.options[0]['display-flags']);
  11710. div.append(select);
  11711. for (let i = 0; i < switche.options.length; i++) {
  11712. let option = switche.options[i];
  11713. let op = $("<option></option>")
  11714. .val(option['display-flags'])
  11715. .text(option['display-name']);
  11716. select.append(op);
  11717. }
  11718. select.change(function () {
  11719. refreshCompilerArgs();
  11720. });
  11721. }
  11722. }
  11723.  
  11724. if (Compiler['compiler-option-raw'] == true) {
  11725. let textarea = OJB_safeCreateJQElement(`<textarea id="compiler_option_raw" placeholder="Raw compiler options" style="resize: vertical;"></textarea>`);
  11726. div.append(textarea);
  11727. textarea.on('input', function () {
  11728. refreshCompilerArgs();
  11729. });
  11730. }
  11731. if (Compiler['runtime-option-raw'] == true) {
  11732. let textarea = OJB_safeCreateJQElement(`<textarea id="runtime_option_raw" placeholder="Raw runtime options" style="resize: vertical;"></textarea>`);
  11733. div.append(textarea);
  11734. textarea.on('input', function () {
  11735. refreshCompilerArgs();
  11736. });
  11737. }
  11738. $("#CompilerSetting").append(div);
  11739.  
  11740. refreshCompilerArgs(); // 初始化
  11741. });
  11742.  
  11743. CompilerChange.trigger("change"); // 初始化
  11744. } else {
  11745. $('#RunTestButton').prop("disabled", true);
  11746. }
  11747. }
  11748.  
  11749. // wandbox编译器通信
  11750. async function wandboxCompiler(code, input) {
  11751. try {
  11752. const result = await OJB_promiseRetryWrapper(wandboxCompilerRequest, {
  11753. maxRetries: 5,
  11754. retryInterval: 500,
  11755. errorHandler: (err) => ({ Errors: err.message, Result: '', Stats: '' })
  11756. }, code, input);
  11757. return result;
  11758. } catch (error) {
  11759. return { Errors: error.message, Result: '', Stats: '' };
  11760. }
  11761. }
  11762.  
  11763. // wandbox编译器请求方法
  11764. async function wandboxCompilerRequest(code, input) {
  11765. const data = {
  11766. code: code,
  11767. codes: [],
  11768. compiler: $('#CompilerChange').val().replace($('#compiler_option_raw').val(), '').replace($('#runtime_option_raw').val(), ''),
  11769. 'compiler-option-raw': $('#compiler_option_raw').val(),
  11770. 'runtime-option-raw': $('#runtime_option_raw').val(),
  11771. options: $("#CompilerArgsInput").val(),
  11772. description: '',
  11773. stdin: input,
  11774. title: ''
  11775. };
  11776.  
  11777. const responseDetails = await OJB_GMRequest({
  11778. method: 'POST',
  11779. url: 'https://wandbox.org/api/compile.json',
  11780. data: JSON.stringify(data),
  11781. headers: {
  11782. 'Content-Type': 'application/json'
  11783. }
  11784. });
  11785.  
  11786. if (responseDetails.status !== 200 || !responseDetails.response) {
  11787. throw new Error(`${i18next.t('compiler.common.error', { ns: 'codeEditor' })}`);
  11788. }
  11789.  
  11790. const response = JSON.parse(responseDetails.response);
  11791. return {
  11792. Errors: response.compiler_error === "" ? response.signal : response.compiler_error,
  11793. Result: response.program_output || '',
  11794. Stats: response.status === "0" ? "Finish" : "Error"
  11795. };
  11796. }
  11797.  
  11798. // 更改编译器参数
  11799. function changeCompilerArgs(nowSelect) {
  11800. if (OJBetter.monaco.onlineCompilerChoice == "official") {
  11801. officialCompilerArgsChange(nowSelect);
  11802. } else if (OJBetter.monaco.onlineCompilerChoice == "rextester") {
  11803. rextesterCompilerArgsChange(nowSelect);
  11804. } else if (OJBetter.monaco.onlineCompilerChoice == "wandbox") {
  11805. wandboxCompilerArgsChange(nowSelect);
  11806. }
  11807. }
  11808.  
  11809. // 在线编译器通信
  11810. async function onlineCompilerConnect(code, input) {
  11811. if (OJBetter.monaco.onlineCompilerChoice == "official") {
  11812. return await officialCompiler(code, input);
  11813. } else if (OJBetter.monaco.onlineCompilerChoice == "rextester") {
  11814. return await rextesterCompiler(code, input);
  11815. } else if (OJBetter.monaco.onlineCompilerChoice == "wandbox") {
  11816. return await wandboxCompiler(code, input);
  11817. }
  11818. }
  11819.  
  11820. // 差异对比
  11821. function codeDiff(expectedText, actualText) {
  11822. // 将文本按行拆分
  11823. const expectedLines = expectedText ? expectedText.split('\n') : [];
  11824. const actualLines = actualText ? actualText.split('\n') : [];
  11825.  
  11826. const output = document.createElement('div');
  11827.  
  11828. const createLineElement = (lineNo, contentElement) => {
  11829. const lineDiv = document.createElement('div');
  11830. lineDiv.className = 'diffLine';
  11831.  
  11832. const lineNoDiv = document.createElement('div');
  11833. lineNoDiv.className = 'lineNo';
  11834. lineNoDiv.textContent = lineNo;
  11835.  
  11836. lineDiv.appendChild(lineNoDiv);
  11837. lineDiv.appendChild(contentElement);
  11838.  
  11839. return lineDiv;
  11840. };
  11841.  
  11842. const createContentElement = (isEquals = true, expected = null, removed = null) => {
  11843. const contentDiv = document.createElement('div');
  11844. contentDiv.className = 'lineContent';
  11845.  
  11846. if (isEquals) {
  11847. const span = document.createElement('span');
  11848. span.textContent = expected;
  11849. contentDiv.appendChild(span);
  11850. } else {
  11851. if (removed != null) {
  11852. const removedSpan = document.createElement('span');
  11853. removedSpan.className = 'removed';
  11854. removedSpan.textContent = removed;
  11855. contentDiv.appendChild(removedSpan);
  11856. }
  11857. if (expected != null) {
  11858. const addedSpan = document.createElement('span');
  11859. addedSpan.className = 'added';
  11860. addedSpan.textContent = expected;
  11861. contentDiv.appendChild(addedSpan);
  11862. }
  11863. }
  11864.  
  11865. return contentDiv;
  11866. };
  11867.  
  11868. let index = 1;
  11869.  
  11870. expectedLines.forEach((expectedLine, i) => {
  11871. const actualLine = actualLines[i];
  11872. if (actualLine === undefined) {
  11873. output.appendChild(createLineElement(index++, createContentElement(false, expectedLine)));
  11874. } else if (expectedLine === actualLine) {
  11875. output.appendChild(createLineElement(index++, createContentElement(true, expectedLine)));
  11876. } else {
  11877. output.appendChild(createLineElement(index++, createContentElement(false, expectedLine, actualLine)));
  11878. }
  11879. });
  11880.  
  11881. // 处理多余的 actualLines
  11882. for (let i = expectedLines.length; i < actualLines.length; i++) {
  11883. output.appendChild(createLineElement(index++, createContentElement(false, null, actualLines[i])));
  11884. }
  11885.  
  11886. return output.innerHTML;
  11887. }
  11888.  
  11889. // 内容类型常量
  11890. const TestCaseContentType = {
  11891. TERMINAL: 'terminal',
  11892. DIFF: 'diff',
  11893. NO_DIFF: 'no_diff',
  11894. SUCCESS: 'success'
  11895. };
  11896.  
  11897. // 样例测试状态类
  11898. class TestCaseStatus {
  11899. constructor(item, prefix) {
  11900. this.testCase = OJB_safeCreateJQElement(`<div class="test-case"></div>`);
  11901. this.item = item;
  11902. this.prefix = prefix;
  11903. this.titleElement = OJB_safeCreateJQElement(`<div class="test-case-title">${this.prefix} ${this.item}</div>`);
  11904. this.statusElement = OJB_safeCreateJQElement(`<div class="test-case-status"></div>`);
  11905. this.contentElement = OJB_safeCreateJQElement(`<div class="test-case-content"></div>`);
  11906. this.judgeElement = OJB_safeCreateJQElement(`<div class="test-case-judge"></div>`);
  11907. this.testCase.append(this.titleElement, this.statusElement, this.contentElement, this.judgeElement);
  11908. $('#statePanel').append(this.testCase);
  11909. this.setStatus('Queued', 'queued');
  11910. }
  11911.  
  11912. setTitle(title) {
  11913. this.titleElement.text(title);
  11914. }
  11915.  
  11916. setStatus(text, status) {
  11917. this.statusElement.text(text).removeClass('queued running success error').addClass(status);
  11918. }
  11919.  
  11920. setContent(content, type) {
  11921. // 如果内容类型为SUCCESS,隐藏内容元素并提前返回
  11922. if (type === TestCaseContentType.SUCCESS) {
  11923. this.contentElement.hide();
  11924. return;
  11925. }
  11926.  
  11927. // 根据内容类型创建内容元素
  11928. const createContentElementByType = (content, type) => {
  11929. let contentElement;
  11930. switch (type) {
  11931. case TestCaseContentType.TERMINAL:
  11932. // 为TERMINAL类型创建一个新的终端容器
  11933. contentElement = OJB_safeCreateJQElement(`<div class="terminal-container" style="overflow: auto;"></div>`);
  11934. break;
  11935. case TestCaseContentType.DIFF:
  11936. case TestCaseContentType.NO_DIFF:
  11937. // 为DIFF和NO_DIFF类型创建相应的内容元素,并添加差异说明
  11938. const className = type === TestCaseContentType.DIFF ? "output_diff" : "output_no_diff";
  11939. contentElement = OJB_safeCreateJQElement(`<pre class="${className}">${content}</pre>`);
  11940. appendDiffNote();
  11941. break;
  11942. default:
  11943. throw new Error("Unsupported content type.");
  11944. }
  11945. return contentElement;
  11946. };
  11947.  
  11948. // 初始化终端
  11949. const initializeTerminal = (content, contentElement) => {
  11950. const term = new Terminal({ rows: 10, cols: 150 });
  11951. term.setOption('theme', { background: '#2d2e2c' });
  11952. term.setOption('convertEol', true); // 将换行符\n转换为\r\n
  11953. term.write(content);
  11954. term.open(contentElement.get(0));
  11955. };
  11956.  
  11957. // 添加差异说明
  11958. const appendDiffNote = () => {
  11959. const diffNote = OJB_safeCreateJQElement(`<div class="diff_note">${i18next.t('resultBlock.diffNote', { ns: 'codeEditor' })}</div>`);
  11960. this.testCase.append(diffNote);
  11961. };
  11962.  
  11963. // 创建并追加内容元素
  11964. const contentElement = createContentElementByType(content, type);
  11965. this.contentElement.append(contentElement);
  11966.  
  11967. // 如果内容类型为TERMINAL,初始化并打开终端
  11968. if (type === TestCaseContentType.TERMINAL) {
  11969. initializeTerminal(content, contentElement);
  11970. }
  11971. }
  11972.  
  11973. setJudge(judge) {
  11974. this.judgeElement.text(judge);
  11975. }
  11976. }
  11977.  
  11978. // 样例测试函数
  11979. async function runCode(event, runButton, sourceDiv, submitDiv) {
  11980. event.preventDefault();
  11981. const statePanel = $('#statePanel').show().empty();
  11982. const testData = getTestData();
  11983. const customTestData = await getCustomTestData();
  11984. const totalTests = Object.keys(customTestData).length + Object.keys(testData).length;
  11985.  
  11986. let passedTests = 0;
  11987. let failedTests = 0;
  11988. let hasError = false;
  11989.  
  11990. // 定义一个对象队列,包括创建的样例块实例和对应的样例数据
  11991. const queue = [];
  11992.  
  11993. // 先生成各个样例的块,并显示排队中,将创建的各个对象存到队列中,以便后面更新
  11994. for (const [item, data] of Object.entries(customTestData)) {
  11995. const testCase = new TestCaseStatus(item, i18next.t('resultBlock.title.custom', { ns: 'codeEditor' }));
  11996. queue.push({ testCase, data });
  11997. }
  11998.  
  11999. if (!$('#onlyCustomTest').prop('checked')) {
  12000. for (const [item, data] of Object.entries(testData)) {
  12001. const testCase = new TestCaseStatus(item, i18next.t('resultBlock.title.sample', { ns: 'codeEditor' }));
  12002. queue.push({ testCase, data });
  12003. }
  12004. }
  12005.  
  12006. // 测试函数
  12007. const runTest = async (testCase, data, index) => {
  12008. runButton.setButtonState('running', `${index}/${totalTests}`);
  12009.  
  12010. testCase.setStatus('Running', 'running');
  12011. const result = await onlineCompilerConnect(sourceDiv.val(), data.input);
  12012.  
  12013. if (result.Errors) {
  12014. testCase.setStatus('Compilation error or Time limit', 'error');
  12015. testCase.setContent(result.Errors, TestCaseContentType.TERMINAL);
  12016. hasError = true;
  12017. } else if (result.Result.trim() === data.output.trim()) {
  12018. testCase.setStatus('Accepted', 'success');
  12019. testCase.setContent('The output is correct.', TestCaseContentType.SUCCESS);
  12020. passedTests++;
  12021. } else {
  12022. testCase.setStatus('Wrong Answer', 'error');
  12023. const diffContent = $('#DontShowDiff').prop('checked') ? result.Result.trim() : codeDiff(data.output.trim(), result.Result.trim());
  12024. const contentType = $('#DontShowDiff').prop('checked') ? TestCaseContentType.NO_DIFF : TestCaseContentType.DIFF;
  12025. testCase.setContent(diffContent, contentType);
  12026. failedTests++;
  12027. }
  12028.  
  12029. const judgeStats = `${i18next.t('resultBlock.state', { ns: 'codeEditor' })}${result.Stats}`;
  12030. testCase.setJudge(judgeStats);
  12031.  
  12032. await OJB_delay(500); // 等待500毫秒
  12033. };
  12034.  
  12035. // 对队列中的对象进行测试
  12036. for (let i = 0; i < queue.length; i++) {
  12037. const { testCase, data } = queue[i];
  12038. await runTest(testCase, data, i + 1);
  12039. }
  12040.  
  12041. // 测试完成后更新按钮状态
  12042. if (hasError) {
  12043. runButton.setButtonState('error', i18next.t('runTestButton.error', { ns: 'codeEditor' }));
  12044. } else if (failedTests > 0) {
  12045. runButton.setButtonState('error', `${passedTests}/${totalTests} ` + i18next.t('runTestButton.partial', { ns: 'codeEditor' }));
  12046. } else {
  12047. runButton.setButtonState('success', i18next.t('runTestButton.success', { ns: 'codeEditor' }));
  12048. }
  12049. }
  12050.  
  12051. /**
  12052. * 添加题目页代码编辑器
  12053. * @returns
  12054. */
  12055. async function addProblemPageCodeEditor() {
  12056. // if (typeof ace === 'undefined') {
  12057. // const loadingMessage = new LoadingMessage();
  12058. // loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('error.codeEditor.load', { ns: 'alert' })}`, 'error');
  12059. // return; // 因为Codeforces设定的是未登录时不能访问提交页,也不会加载ace库
  12060. // }
  12061.  
  12062. // 获取提交页链接
  12063. const href = window.location.href;
  12064. let submitUrl = OJBetter.common.hostAddress + $('.form-code-submit').attr('action');
  12065. console.log(submitUrl);
  12066. // if (/\/problemset\//.test(href)) {
  12067. // // problemset
  12068. // submitUrl = OJBetter.common.hostAddress + '/problemset/submit';
  12069. // } else if (/\/gym\//.test(href)) {
  12070. // // gym 题目
  12071. // submitUrl = OJBetter.common.hostAddress + '/gym/' + ((href) => {
  12072. // const regex = /\/gym\/(?<num>[0-9a-zA-Z]*?)\/problem\//;
  12073. // const match = href.match(regex);
  12074. // return match && match.groups.num;
  12075. // })(href) + '/submit';
  12076. // } else if (OJBetter.typeOfPage.is_acmsguru) {
  12077. // // acmsguru 题目
  12078. // submitUrl = href.replace(/\/problemsets[A-Za-z0-9\/#]*/, "/problemsets/acmsguru/submit");
  12079. // } else {
  12080. // submitUrl = href.replace(/\/problem[A-Za-z0-9\/#]*/, "/submit");
  12081. // }
  12082.  
  12083. // // 获取提交页HTML
  12084. // let cloneHTML = await getSubmitHTML(submitUrl);
  12085.  
  12086. // 创建
  12087. // let form = await createCodeEditorForm(submitUrl, cloneHTML);
  12088. let form = await createCodeEditorForm(submitUrl);
  12089. let selectLang = form.selectLang;
  12090. let submitButton = form.submitButton;
  12091. let runButton = form.runButton;
  12092.  
  12093. // 初始化
  12094. CustomTestInit(); // 自定义测试数据面板
  12095. selectLang.val(OJBetter.monaco.compilerSelection);
  12096. changeMonacoLanguage(form);
  12097.  
  12098. // 这里由于Atcoder使用了Select2 ,其在初始化时会触发change事件,因此需要在初始化后再绑定事件
  12099. const observer = new MutationObserver((mutations) => {
  12100. mutations.forEach((mutation) => {
  12101. if (mutation.attributeName === "class" && $(mutation.target).hasClass("select2-hidden-accessible")) {
  12102. $(mutation.target).on('change', (e) => {
  12103. selectLang.on('change', () => changeMonacoLanguage(form)); // 编辑器语言切换监听
  12104. });
  12105. observer.disconnect();
  12106. }
  12107. });
  12108. });
  12109. observer.observe(selectLang[0], { attributes: true });
  12110.  
  12111. // 样例测试
  12112. runButton.on('click', (event) => runCode(event, runButton, form.sourceDiv, form.submitDiv))
  12113. .setHoverRedo();
  12114.  
  12115. // 提交
  12116. submitButton.on('click', async function (event) {
  12117. event.preventDefault();
  12118. if (OJBetter.monaco.setting.isCodeSubmitDoubleConfirm) {
  12119. const submit = await OJB_createDialog(
  12120. i18next.t('submitCode.title', { ns: 'dialog' }),
  12121. i18next.t('submitCode.content', { ns: 'dialog' }),
  12122. [
  12123. i18next.t('submitCode.buttons.0', { ns: 'dialog' }),
  12124. i18next.t('submitCode.buttons.1', { ns: 'dialog' })
  12125. ]
  12126. ); //提交确认
  12127. if (submit) {
  12128. submitButton.after(`<img class="OJBetter_loding" src="//codeforces.org/s/84141/images/ajax-loading-24x24.gif">`);
  12129. $('#OJBetter_SubmitForm').submit();
  12130. } else {
  12131. submitButton.addClass('disabled');
  12132. setTimeout(function () {
  12133. submitButton.removeClass('disabled');
  12134. }, 300);
  12135. }
  12136. } else {
  12137. $('#OJBetter_SubmitForm').submit();
  12138. }
  12139. });
  12140. }
  12141.  
  12142. /**
  12143. * 获取翻译服务目标语言的对应代码
  12144. * @param {string} serverName 服务名称
  12145. * @returns {string} 目标语言,如果没有对应代码则返回中文
  12146. */
  12147. function getTargetLanguage(serverName) {
  12148. let targetLanguage = OJBetter.supportList.translationSupport[serverName][OJBetter.translation.targetLang];
  12149. if (targetLanguage) return targetLanguage;
  12150. else return OJBetter.supportList.translationSupport[serverName]['zh'];
  12151. }
  12152.  
  12153. /**
  12154. * 将文本中Markdown格式的加粗**转换成HTML格式。
  12155. * @param {string} text 文本
  12156. * @returns {string} 替换后的字符串
  12157. */
  12158. function convertBoldMarkdownToHTML(text) {
  12159. return text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
  12160. }
  12161.  
  12162. /**
  12163. * 将文本中Markdown格式的链接文本转换成HTML格式。
  12164. * @param {string} text 文本
  12165. * @returns {string} 替换后的字符串
  12166. */
  12167. function convertLinksMarkdownToHTML(text) {
  12168. return text.replace(/(?<!!)\[(.*?)\]\(([^"]*?)("(.*?)")*\)/g, '<a href="$2" title="$4">$1</a>');
  12169. }
  12170.  
  12171. /**
  12172. * 将HTML格式的加粗文本转换回Markdown格式。
  12173. * @param {string} text 文本
  12174. * @returns {string} 替换后的字符串
  12175. */
  12176. function convertBoldHTMLToMarkdown(text) {
  12177. return text.replace(/<strong>(.*?)<\/strong>/g, '**$1**');
  12178. }
  12179.  
  12180. /**
  12181. * 将HTML格式的链接文本转换回Markdown格式。
  12182. * @param {string} html - 包含HTML链接标签<a>的字符串。
  12183. * @returns {string} 转换后的字符串,其中HTML链接标签被替换为Markdown的链接语法。
  12184. */
  12185. function convertLinksHTMLToMarkdown(html) {
  12186. return html.replace(/<a href="([^"]*)"( title="([^"]*)")*>([^<]+)<\/a>/g, '[$4]($1 "$3")');
  12187. }
  12188.  
  12189. /**
  12190. * DeepL翻译
  12191. * @param {string} raw 原文
  12192. * @returns {Promise<TransRawData>} 翻译结果对象
  12193. */
  12194. async function translate_deepl(raw) {
  12195. const id = (Math.floor(Math.random() * 99999) + 100000) * 1000;
  12196. const data = {
  12197. jsonrpc: '2.0',
  12198. method: 'LMT_handle_texts',
  12199. id,
  12200. params: {
  12201. splitting: 'newlines',
  12202. lang: {
  12203. source_lang_user_selected: 'auto',
  12204. target_lang: getTargetLanguage('deepl'),
  12205. },
  12206. texts: [{
  12207. text: raw,
  12208. requestAlternatives: 3
  12209. }],
  12210. timestamp: getTimeStamp(raw.split('i').length - 1)
  12211. }
  12212. }
  12213. let postData = JSON.stringify(data);
  12214. if ((id + 5) % 29 === 0 || (id + 3) % 13 === 0) {
  12215. postData = postData.replace('"method":"', '"method" : "');
  12216. } else {
  12217. postData = postData.replace('"method":"', '"method": "');
  12218. }
  12219. const options = {
  12220. method: 'POST',
  12221. url: 'https://www2.deepl.com/jsonrpc',
  12222. data: postData,
  12223. headers: {
  12224. 'Content-Type': 'application/json',
  12225. 'Host': 'www2.deepl.com',
  12226. 'Origin': 'https://www.deepl.com',
  12227. 'Referer': 'https://www.deepl.com/',
  12228. },
  12229. anonymous: true,
  12230. nocache: true,
  12231. }
  12232.  
  12233. return await BaseTranslate(options, res => JSON.parse(res)?.result?.texts?.[0]?.text || res, res => {
  12234. const resObj = {
  12235. status: true,
  12236. message: 'ok'
  12237. };
  12238. if (res.includes('"message":"Too many requests"')) {
  12239. resObj.status = false;
  12240. resObj.message = i18next.t('error.deepl429', { ns: 'translator' }); // Too many requests 提示
  12241. return resObj;
  12242. };
  12243. return resObj;
  12244. });
  12245. }
  12246.  
  12247. /**
  12248. * 使用 DeepL Free API 进行翻译
  12249. * @param {string} raw 原文
  12250. * @returns {Promise<TransRawData>} 翻译结果对象
  12251. */
  12252. async function translate_deepl_api_free(raw) {
  12253. const data = JSON.stringify({
  12254. text: [raw],
  12255. target_lang: getTargetLanguage('deepl'),
  12256. split_sentences: '1',
  12257. ...(OJBetter.deepl.enableEmphasisProtection || OJBetter.deepl.enableLinkProtection ? { tag_handling: 'html' } : {}),
  12258. ...Object.assign({}, ...OJBetter.deepl.config.data)
  12259. });
  12260.  
  12261. const options = {
  12262. method: "POST",
  12263. url: OJBetter.deepl.config.proxy || "https://api-free.deepl.com/v2/translate",
  12264. headers: {
  12265. "Authorization": `DeepL-Auth-Key ${OJBetter.deepl.config.key}`,
  12266. "Content-Type": "application/json",
  12267. ...Object.assign({}, ...OJBetter.deepl.config.header)
  12268. },
  12269. data: data,
  12270. onload: response => response.responseText,
  12271. onerror: error => console.error(error)
  12272. };
  12273.  
  12274. return await BaseTranslate(options, res => JSON.parse(res).translations[0].text);
  12275. }
  12276.  
  12277. /**
  12278. * 使用 DeepL Pro API 进行翻译
  12279. * @param {string} raw 原文
  12280. * @returns {Promise<TransRawData>} 翻译结果对象
  12281. */
  12282. async function translate_deepl_api_pro(raw) {
  12283. const data = JSON.stringify({
  12284. text: [raw],
  12285. target_lang: getTargetLanguage('deepl'),
  12286. split_sentences: '1',
  12287. ...(OJBetter.deepl.enableEmphasisProtection || OJBetter.deepl.enableLinkProtection ? { tag_handling: 'html' } : {}),
  12288. ...Object.assign({}, ...OJBetter.deepl.config.data)
  12289. });
  12290.  
  12291. const options = {
  12292. method: "POST",
  12293. url: OJBetter.deepl.config.proxy || "https://api.deepl.com/v2/translate",
  12294. headers: {
  12295. "Authorization": `DeepL-Auth-Key ${OJBetter.deepl.config.key}`,
  12296. "Content-Type": "application/json",
  12297. ...Object.assign({}, ...OJBetter.deepl.config.header)
  12298. },
  12299. data: data,
  12300. onload: response => response.responseText,
  12301. onerror: error => console.error(error)
  12302. };
  12303.  
  12304. return await BaseTranslate(options, res => JSON.parse(res).translations[0].text);
  12305. }
  12306.  
  12307. /**
  12308. * 使用 DeepLX 进行翻译
  12309. * @param {String} text 原文
  12310. * @returns {Promise<TransRawData>} 翻译结果对象
  12311. */
  12312. async function translate_deeplx(text) {
  12313. const options = {
  12314. method: "POST",
  12315. url: OJBetter.deepl.config.proxy || 'https://api.deeplx.org/translate',
  12316. data: JSON.stringify({
  12317. "text": text,
  12318. "source_lang": "EN",
  12319. "target_lang": getTargetLanguage('deepl'),
  12320. }),
  12321. headers: {
  12322. 'Content-Type': 'application/json',
  12323. ...(OJBetter.deepl.config.key ? { Authorization: `Bearer ${OJBetter.deepl.config.key}` } : {})
  12324. },
  12325. responseType: "json",
  12326. };
  12327.  
  12328. return await BaseTranslate(options, res => {
  12329. const parsedResponse = JSON.parse(res);
  12330. if (parsedResponse.code === 200 && parsedResponse.data) {
  12331. return parsedResponse.data;
  12332. } else {
  12333. throw new Error('Translation failed or invalid response format.');
  12334. }
  12335. });
  12336. }
  12337.  
  12338. function getTimeStamp(iCount) {
  12339. const ts = Date.now();
  12340. if (iCount !== 0) {
  12341. iCount = iCount + 1;
  12342. return ts - (ts % iCount) + iCount;
  12343. } else {
  12344. return ts;
  12345. }
  12346. }
  12347.  
  12348. /**
  12349. * 讯飞听见翻译
  12350. * @param {String} text 要翻译的文本
  12351. * @returns {Promise<TransRawData>} 翻译结果对象
  12352. */
  12353. async function translate_iflyrec(text) {
  12354. const options = {
  12355. method: "POST",
  12356. url: 'https://www.iflyrec.com/TranslationService/v1/textTranslation',
  12357. data: JSON.stringify({
  12358. "from": "2",
  12359. "to": getTargetLanguage('iflyrec'),
  12360. "contents": [{
  12361. "text": text,
  12362. "frontBlankLine": 0
  12363. }]
  12364. }),
  12365. anonymous: true,
  12366. headers: {
  12367. 'Content-Type': 'application/json',
  12368. 'Origin': 'https://www.iflyrec.com',
  12369. },
  12370. responseType: "json",
  12371. };
  12372. return await BaseTranslate(options, res => JSON.parse(res).biz[0].translateResult.replace(/\\n/g, "\n\n"));
  12373. }
  12374.  
  12375. /**
  12376. * 有道翻译
  12377. * @param {string} raw 原文
  12378. * @returns {Promise<TransRawData>} 翻译结果对象
  12379. */
  12380. async function translate_youdao_mobile(raw) {
  12381. const options = {
  12382. method: "POST",
  12383. url: 'http://m.youdao.com/translate',
  12384. data: "inputtext=" + encodeURIComponent(raw) + "&type=" + getTargetLanguage('youdao'),
  12385. anonymous: true,
  12386. headers: {
  12387. "Content-Type": "application/x-www-form-urlencoded",
  12388. 'Host': 'm.youdao.com',
  12389. 'Origin': 'http://m.youdao.com',
  12390. 'Referer': 'http://m.youdao.com/translate',
  12391. }
  12392. }
  12393. return await BaseTranslate(options,
  12394. res => {
  12395. const array = /id="translateResult">\s*?<li>([\s\S]*?)<\/li>\s*?<\/ul/.exec(res);
  12396. if (array && array.length > 1) {
  12397. return array[1];
  12398. } else {
  12399. return res;
  12400. }
  12401. },
  12402. res => {
  12403. const resObj = {
  12404. status: true,
  12405. message: 'ok'
  12406. };
  12407. if (res.includes('<title>413 Request Entity Too Large</title>')) {
  12408. resObj.status = false;
  12409. resObj.message = i18next.t('error.youdao413', { ns: 'translator' }); // Request Entity Too Large 提示
  12410. return resObj;
  12411. };
  12412. return resObj;
  12413. })
  12414. }
  12415.  
  12416. /**
  12417. * google翻译
  12418. * @param {string} raw 原文
  12419. * @returns {Promise<TransRawData>} 翻译结果对象
  12420. */
  12421. async function translate_gg(raw) {
  12422. const params = `tl=${getTargetLanguage('google')}&q=${encodeURIComponent(raw)}`;
  12423. const options = {
  12424. method: "GET",
  12425. url: `https://translate.google.com/m?${params}`,
  12426. }
  12427. return await BaseTranslate(options,
  12428. res => $(res).filter('.result-container').text() || $(res).find('.result-container').text());
  12429. }
  12430.  
  12431. /**
  12432. * 彩云翻译
  12433. * @param {string} raw 原文
  12434. * @returns {Promise<TransRawData>} 翻译结果对象
  12435. */
  12436. async function translate_caiyun(raw) {
  12437. const source = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm";
  12438. const dic = [..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"].reduce((dic, current, index) => { dic[current] = source[index]; return dic }, {});
  12439. const browser_id = CryptoJS.MD5(Math.random().toString()).toString();
  12440. const caiyun_jwt = await (async () => {
  12441. const options = {
  12442. method: "POST",
  12443. url: 'https://api.interpreter.caiyunai.com/v1/user/jwt/generate',
  12444. headers: {
  12445. "content-type": "application/json",
  12446. "x-authorization": "token:qgemv4jr1y38jyq6vhvi",
  12447. "origin": "https://fanyi.caiyunapp.com",
  12448. },
  12449. data: JSON.stringify({ browser_id }),
  12450. }
  12451. const res = await OJB_GMRequest(options);
  12452. return JSON.parse(res.responseText).jwt;
  12453. })();
  12454.  
  12455. // 解码
  12456. const decodeUnicode = str => {
  12457. const decoder = new TextDecoder();
  12458. const data = Uint8Array.from(atob(str), c => c.charCodeAt(0));
  12459. return decoder.decode(data);
  12460. };
  12461. const decoder = line => decodeUnicode([...line].map(i => dic[i] || i).join(""));
  12462.  
  12463. const options = {
  12464. method: "POST",
  12465. url: 'https://api.interpreter.caiyunai.com/v1/translator',
  12466. data: JSON.stringify({
  12467. "source": raw.split('\n'),
  12468. "browser_id": browser_id,
  12469. "trans_type": getTargetLanguage('caiyun'),
  12470. "request_id": "web_fanyi",
  12471. "media": "text",
  12472. "os_type": "web",
  12473. "dict": true,
  12474. "cached": true,
  12475. "replaced": true,
  12476. "style": "formal",
  12477. "model": "",
  12478. "detect": true,
  12479. }),
  12480. headers: {
  12481. "content-type": "application/json;charset=UTF-8",
  12482. "x-authorization": "token:qgemv4jr1y38jyq6vhvi",
  12483. "t-authorization": caiyun_jwt
  12484. }
  12485. }
  12486. return await BaseTranslate(options, res => JSON.parse(res).target.map(decoder).join('\n'))
  12487. }
  12488.  
  12489. /**
  12490. * ChatGPT
  12491. * @param {string} raw 原文
  12492. * @returns {Promise<TransRawData>} 翻译结果对象
  12493. */
  12494. async function translate_openai(raw) {
  12495. const modelDefault = 'gpt-3.5-turbo';
  12496. const lang = getTargetLanguage('openai');
  12497. const prompt = `
  12498. As a professional English translator, your task is to accurately translate a segment of an algorithm programming competition question into ${lang}.
  12499. The translation should use professional terms and maintain the text format, including ${OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru
  12500. ? "keeping the LaTeX equations unchanged."
  12501. : "keeping the brackets【】, HTML tags, and their content unchanged."
  12502. }
  12503. After translation, please ensure that the ${lang} version conforms to normal expression habits.
  12504. What I need is a carefully polished ${lang} translation of my question segment, The segment to be translated is as follows: "
  12505. ${raw}
  12506. "`;
  12507. const data = {
  12508. model: OJBetter.chatgpt.config.model || modelDefault,
  12509. messages: [{
  12510. role: "assistant",
  12511. content: prompt
  12512. }],
  12513. temperature: 0.7,
  12514. ...Object.assign({}, ...OJBetter.chatgpt.config.data)
  12515. }
  12516. const options = {
  12517. method: "POST",
  12518. url: OJBetter.chatgpt.config.proxy || 'https://api.openai.com/v1/chat/completions',
  12519. data: JSON.stringify(data),
  12520. responseType: 'json',
  12521. headers: {
  12522. 'Content-Type': 'application/json',
  12523. 'Authorization': 'Bearer ' + OJBetter.chatgpt.config.key,
  12524. ...Object.assign({}, ...OJBetter.chatgpt.config.header)
  12525. }
  12526. }
  12527. return await BaseTranslate(options,
  12528. res => res,
  12529. undefined,
  12530. response => response.response.choices[0].message.content);
  12531. }
  12532.  
  12533. /**
  12534. * ChatGPT 流式传输
  12535. * @param {string} raw 原文
  12536. * @param {TranslateDiv} translateDiv 翻译结果面板
  12537. * @returns {Promise<TransRawData>} 翻译结果对象
  12538. */
  12539. async function translate_openai_stream(raw, translateDiv) {
  12540. const result = {
  12541. done: true,
  12542. checkPassed: null,
  12543. response: null,
  12544. responseText: null,
  12545. text: "",
  12546. error: null,
  12547. message: null
  12548. };
  12549. const helpText = i18next.t('error.basic', { ns: 'translator' }); // 基本帮助提示信息
  12550. try {
  12551. for await (const delta of openai_stream(raw)) {
  12552. result.text += delta;
  12553. // 翻译结果面板更新
  12554. translateDiv.updateTranslateDiv(result.text, !(OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru), false);
  12555. }
  12556. return result;
  12557. } catch (err) {
  12558. console.warn(err);
  12559. result.error = {
  12560. message: err.message || null,
  12561. stack: err.stack ? err.stack.replace(/\n/g, '<br>').replace(/\s/g, '&nbsp;') : null,
  12562. enumerable: err,
  12563. source: 'openai_stream'
  12564. };
  12565. result.message = `${i18next.t('error.GMRequest', { ns: 'translator' })}${helpText}`;
  12566. }
  12567.  
  12568. return result;
  12569. }
  12570.  
  12571. /**
  12572. * 流式传输
  12573. * @param {string} raw 原文
  12574. * @returns {AsyncGenerator<string>} 返回 AsyncGenerator
  12575. */
  12576. async function* openai_stream(raw) {
  12577. const modelDefault = 'gpt-3.5-turbo';
  12578. const lang = getTargetLanguage('openai');
  12579. const prompt = `
  12580. I hope you can act as a professional English translator to help me translate a segment of an algorithm programming competition question into ${lang}.
  12581. During the translation process, I would like you to use more professional terms and maintain the text format, ${OJBetter.typeOfPage.is_oldLatex || OJBetter.typeOfPage.is_acmsguru
  12582. ? "keeping the LaTeX equations unchanged."
  12583. : "keeping the brackets【】, HTML tags, and their content unchanged."
  12584. }
  12585. After completing the translation, please polish the ${lang} version to ensure it conforms to normal expression habits.
  12586. What I need is a carefully polished ${lang} translation of my question segment, which is as follows:
  12587. "
  12588. ${raw}
  12589. "`;
  12590. const data = {
  12591. model: OJBetter.chatgpt.config.model || modelDefault,
  12592. messages: [{
  12593. role: "assistant",
  12594. content: prompt
  12595. }],
  12596. temperature: 0.7,
  12597. stream: true,
  12598. ...Object.assign({}, ...OJBetter.chatgpt.config.data)
  12599. }
  12600. const options = {
  12601. method: "POST",
  12602. url: OJBetter.chatgpt.config.proxy || 'https://api.openai.com/v1/chat/completions',
  12603. data: JSON.stringify(data),
  12604. responseType: 'stream',
  12605. headers: {
  12606. 'Content-Type': 'application/json',
  12607. 'Authorization': 'Bearer ' + OJBetter.chatgpt.config.key,
  12608. ...Object.assign({}, ...OJBetter.chatgpt.config.header)
  12609. }
  12610. }
  12611. const response = await OJB_GMRequest(options, true);
  12612. const reader = response.response.getReader();
  12613. const decoder = new TextDecoder();
  12614. let buffer = ''; // 用于累积数据片段的缓冲区
  12615.  
  12616. while (true) {
  12617. const { done, value } = await reader.read();
  12618. if (done) break;
  12619. buffer += decoder.decode(value, { stream: true }); // 将新的数据片段追加到缓冲区
  12620. let lines = buffer.split("\n\n"); // 处理累积的数据
  12621.  
  12622. // 缓冲区的最后一行可能还未完整接收,保留在缓冲区中,-1
  12623. for (let i = 0; i < lines.length - 1; i++) {
  12624. let line = lines[i];
  12625. line = line.substring(5); // 移除 'data:' 前缀
  12626. if (line.includes('[DONE]')) {
  12627. return; // End
  12628. }
  12629. try {
  12630. let data = JSON.parse(line);
  12631. let delta = data['choices'][0]['delta'];
  12632. let content = delta['content'] ? delta['content'] : "";
  12633. yield content; // 传递数据给调用者
  12634. } catch (error) {
  12635. console.warn(`Error parsing JSON: ${error}\n\nError data: ${line}`);
  12636. }
  12637. }
  12638.  
  12639. // 保留最后一行在缓冲区中
  12640. buffer = lines.slice(-1);
  12641. }
  12642.  
  12643. return buffer;
  12644. }
  12645.  
  12646. /**
  12647. * @typedef {Object} CheckResponseResult
  12648. * @property {boolean} status 检查是否通过
  12649. * @property {string} message 检查失败时的消息
  12650. */
  12651.  
  12652. /**
  12653. * @typedef {Object} ErrorResponse
  12654. * @property {Object} message 错误消息
  12655. * @property {Object} stack 错误堆栈
  12656. * @property {Object} enumerable 可枚举的错误属性
  12657. * @property {string} source 错误来源
  12658. */
  12659.  
  12660. /**
  12661. * @typedef {Object} TransRawData
  12662. * @property {boolean} done 操作是否完成
  12663. * @property {CheckResponseResult|null} checkPassed 检查是否通过的结果
  12664. * @property {Object|null} response 响应对象
  12665. * @property {string|null} text 处理后的文本
  12666. * @property {ErrorResponse} error 错误列表
  12667. * @property {string|null} message 可能的消息
  12668. */
  12669.  
  12670. /**
  12671. * 通用翻译函数
  12672. * @param {Object} options GM_xmlhttpRequest 的参数
  12673. * @param {Function} processer 响应再处理函数,它接收响应文本,并应返回处理后的文本。
  12674. * @param {Function} checkResponse 检查文本是否符合预期的函数,它接收文本,并返回一个Object,包含状态和信息。默认为返回 { status: true, message: 'ok' }
  12675. * @param {Function} getResponseText 重写响应文本获取函数,它接收response,并返回响应文本。 默认为 response.responseText
  12676. * @returns {Promise<TransRawData>} 返回 Promise,其解析值为翻译结果对象
  12677. */
  12678. async function BaseTranslate(options, processer, checkResponse = () => { return { status: true, message: 'ok' } }, getResponseText = (response) => response.responseText) {
  12679. const result = {
  12680. done: false,
  12681. checkPassed: null,
  12682. response: null,
  12683. responseText: null,
  12684. text: "",
  12685. error: null,
  12686. message: null
  12687. };
  12688. const helpText = i18next.t('error.basic', { ns: 'translator' }); // 基本帮助提示信息
  12689. const toDo = async () => {
  12690. try {
  12691. result.response = await OJB_GMRequest(options);
  12692. result.responseText = result.response.responseText;
  12693. result.text = getResponseText(result.response);
  12694. } catch (err) {
  12695. console.warn(err);
  12696. result.error = {
  12697. message: err.message || null,
  12698. stack: err.stack ? err.stack.replace(/\n/g, '<br>').replace(/\s/g, '&nbsp;') : null,
  12699. enumerable: err,
  12700. source: 'GMRequest'
  12701. };
  12702. result.message = `${i18next.t('error.GMRequest', { ns: 'translator' })}${helpText}`;
  12703. throw result;
  12704. }
  12705. try {
  12706. result.text = processer(result.text);
  12707. } catch (err) {
  12708. console.warn(err);
  12709. result.error = {
  12710. message: err.message || null,
  12711. stack: err.stack ? err.stack.replace(/\n/g, '<br>').replace(/\s/g, '&nbsp;') : null,
  12712. enumerable: err,
  12713. source: 'processer'
  12714. };
  12715. result.message = `${i18next.t('error.processer', { ns: 'translator' })}${helpText}`;
  12716. throw result;
  12717. }
  12718. try {
  12719. result.checkPassed = checkResponse(result.text);
  12720. if (result.checkPassed.status) result.done = true;
  12721. else result.message = result.checkPassed.message;
  12722. return result;
  12723. } catch (err) {
  12724. console.warn(err);
  12725. result.error = {
  12726. message: err.message || null,
  12727. stack: err.stack ? err.stack.replace(/\n/g, '<br>').replace(/\s/g, '&nbsp;') : null,
  12728. enumerable: err,
  12729. source: 'checkResponse'
  12730. };
  12731. result.message = `${i18next.t('error.checkResponse', { ns: 'translator' })}${helpText}`;
  12732. throw result;
  12733. }
  12734. };
  12735.  
  12736. return await OJB_promiseRetryWrapper(toDo, {
  12737. maxRetries: 3,
  12738. errorHandler: (err, maxRetries, attemptsLeft) => {
  12739. const detailedError = {
  12740. maxRetries: maxRetries,
  12741. attemptsLeft: attemptsLeft,
  12742. ...err
  12743. };
  12744. return detailedError;
  12745. }
  12746. });
  12747. }
  12748.  
  12749. /**
  12750. * 查询服务余额
  12751. * @param {Object} quotaConfig - 配额配置对象
  12752. * @returns {Promise} 返回包含余额信息的 Promise
  12753. */
  12754. async function queryServerBalance(quotaConfig) {
  12755. // 确保传入了有效的配置对象
  12756. if (!quotaConfig || !quotaConfig.url) {
  12757. return Promise.reject(new Error('Quota configuration is missing.'));
  12758. }
  12759.  
  12760. // 准备请求选项
  12761. const requestOptions = {
  12762. method: quotaConfig.method || 'GET',
  12763. url: quotaConfig.url,
  12764. headers: {
  12765. ...Object.assign({}, ...quotaConfig.header)
  12766. },
  12767. data: JSON.stringify({ ...Object.assign({}, ...quotaConfig.data) })
  12768. };
  12769.  
  12770. // 发送请求并返回 Promise
  12771. return OJB_GMRequest(requestOptions).then(response => {
  12772. try {
  12773. const responseData = JSON.parse(response.responseText);
  12774. // 从响应数据中提取余额
  12775. const surplusPath = quotaConfig.surplus;
  12776. const surplusValue = OJB_evaluatePathOrExpression(responseData, surplusPath);
  12777. return surplusValue;
  12778. } catch (error) {
  12779. return Promise.reject(new Error('Failed to parse balance response.'));
  12780. }
  12781. }).catch(error => {
  12782. console.warn('Error querying balance:', error);
  12783. return Promise.reject(error);
  12784. });
  12785. }
  12786.  
  12787. /**
  12788. * 确认 jQuery 已加载
  12789. * @param {number} retryDelay 重试延迟(毫秒)
  12790. * @returns {Promise<void>}
  12791. */
  12792. async function ensureJQueryIsLoaded(retryDelay = 50) {
  12793. while (typeof jQuery === 'undefined') {
  12794. console.warn(`JQuery is not loaded. Retry after ${retryDelay} ms.`);
  12795. await OJB_delay(retryDelay);
  12796. retryDelay = Math.min(retryDelay * 2, 2000);
  12797. }
  12798. }
  12799.  
  12800. /**
  12801. * 加载必须的函数
  12802. * @returns {Promise} 加载提示信息
  12803. */
  12804. async function loadRequiredFunctions() {
  12805. await initVar();// 初始化全局变量
  12806. return Promise.allSettled([
  12807. initDB(), // 连接数据库
  12808. initI18next(), // i18next初始化
  12809. initButtonFunc(), // 加载按钮相关函数
  12810. checkScriptVersion(), // 更新检查
  12811. // ...(OJBetter.typeOfPage.is_acmsguru ? [acmsguruReblock()] : []) // 为acmsguru题面重新划分div
  12812. ]);
  12813. }
  12814.  
  12815. /**
  12816. * DOM加载后即可执行
  12817. */
  12818. function initOnDOMReady() {
  12819. showAnnounce(); // 显示公告
  12820. showWarnMessage(); // 显示警告消息
  12821. initSettingsPanel(); // 加载设置按钮面板
  12822. localizeWebsite(); // 网站本地化替换
  12823. addDependencyStyles(); // 添加一些依赖库的样式
  12824. addI18nStyles(); // 添加包含i18n内容的样式
  12825. // if (OJBetter.basic.expandFoldingblocks) ExpandFoldingblocks(); // 折叠块展开
  12826. // if (OJBetter.basic.renderPerfOpt) RenderPerfOpt(); // 折叠块渲染优化
  12827. if (OJBetter.typeOfPage.is_problem) {
  12828. const problemPageLinkbar = new ProblemPageLinkbar(); // 创建题目页相关链接栏
  12829. if (OJBetter.basic.showCF2vjudge) CF2vjudge(problemPageLinkbar); // 跳转到Vjudge按钮
  12830. if (OJBetter.basic.showJumpToLuogu) CF2luogu(problemPageLinkbar); // 跳转到洛谷按钮
  12831. if (OJBetter.clist.enabled.problem) showRatingByClist_problem(problemPageLinkbar); // problem页显示Rating
  12832. }
  12833. if (OJBetter.typeOfPage.is_contest) {
  12834. if (OJBetter.clist.enabled.contest) showRatingByClist_contest(); // contest页显示Rating
  12835. }
  12836. // if (OJBetter.typeOfPage.is_problemset) {
  12837. // if (OJBetter.clist.enabled.problemset) showRatingByClist_problemset(); // problemset页显示Rating
  12838. // }
  12839. if (OJBetter.typeOfPage.is_problem && OJBetter.monaco.enableOnProblemPage) {
  12840. addProblemPageCodeEditor(); // 添加题目页代码编辑器
  12841. }
  12842. }
  12843.  
  12844. /**
  12845. * 需要在页面资源完全加载后执行的函数
  12846. */
  12847. function onResourcesReady(loadingMessage) {
  12848. if (OJBetter.preference.showLoading) loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('loadFunc', { ns: 'alert' })}`);
  12849. initializeInParallel(loadingMessage);
  12850. initializeSequentially(loadingMessage);
  12851. }
  12852.  
  12853. /**
  12854. * 可以异步并行的函数
  12855. */
  12856. function initializeInParallel(loadingMessage) {
  12857. if (OJBetter.basic.darkMode == "dark") darkModeStyleAdjustment(); // 黑暗模式额外的处理事件
  12858. // if (OJBetter.basic.commentPaging) CommentPagination(); // 评论区分页
  12859. if (OJBetter.translation.comment.transMode == "2") multiChoiceTranslation(); // 选段翻译支持
  12860. if (OJBetter.monaco.beautifyPreBlocks) beautifyPreBlocksWithMonaco(); // 美化Pre代码块
  12861. }
  12862.  
  12863. /**
  12864. * 必须按序执行的函数
  12865. */
  12866. async function initializeSequentially(loadingMessage) {
  12867. await addConversionButton(); // 添加MD/复制/翻译按钮
  12868. if ((OJBetter.typeOfPage.is_problem || OJBetter.typeOfPage.is_completeProblemset) && OJBetter.translation.memory.enabled) {
  12869. await initTransResultsRecover(); // 翻译结果恢复功能初始化
  12870. }
  12871. // if (OJBetter.translation.auto.enabled) {
  12872. // await initTransWhenViewable(); // 自动翻译
  12873. // }
  12874. // if (OJBetter.basic.standingsRecolor && OJBetter.typeOfPage.is_cfStandings) {
  12875. // await recolorStandings(); // cf赛制榜单重新着色
  12876. // }
  12877. if (OJBetter.preference.showLoading) loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('loadSuccess', { ns: 'alert' })}`, 'success', 3000);
  12878. }
  12879.  
  12880. /**
  12881. * 主方法
  12882. */
  12883. async function main() {
  12884. await ensureJQueryIsLoaded(); // 等待jQuery加载
  12885. const loadingMessage = new LoadingMessage();
  12886. await loadRequiredFunctions(); // 加载必须的函数
  12887. initOnDOMReady(); // DOM加载后即可执行的函数
  12888. if (OJBetter.preference.showLoading) loadingMessage.updateStatus(`${OJBetter.state.name} —— ${i18next.t('onload', { ns: 'alert' })}`);
  12889.  
  12890. // 检查页面资源是否已经完全加载
  12891. if (OJBetter.state.notWaiteLoaded) {
  12892. onResourcesReady(loadingMessage);
  12893. } else {
  12894. if (document.readyState === 'complete') {
  12895. onResourcesReady(loadingMessage);
  12896. } else {
  12897. window.addEventListener('load', () => onResourcesReady(loadingMessage));
  12898. }
  12899. }
  12900. };
  12901.  
  12902. // ------------------------------
  12903. // 脚本加载入口
  12904. if (document.readyState === 'loading') {
  12905. document.addEventListener("DOMContentLoaded", main);
  12906. } else {
  12907. main(); // 如果DOMContentLoaded已经触发,立即执行
  12908. }
  12909. // ------------------------------
  12910.  
  12911. // ------------------------------
  12912. // 配置自动迁移代码(将在10个小版本后移除-1.19)
  12913. // ------------------------------
  12914.  
  12915. if (GM_getValue("openai_key") || GM_getValue("api2d_key")) {
  12916. const newConfig = { "choice": -1, "configurations": [] };
  12917. if (GM_getValue("openai_key")) {
  12918. let config1 = {
  12919. "note": "我的配置1",
  12920. "model": GM_getValue("openai_model"),
  12921. "key": GM_getValue("openai_key"),
  12922. "proxy": GM_getValue("openai_proxy"),
  12923. "_header": "",
  12924. "_data": ""
  12925. }
  12926. if (GM_getValue("translation") === "openai") newConfig.choice = 0;
  12927. newConfig.configurations.push(config1);
  12928. }
  12929. if (GM_getValue("api2d_key")) {
  12930. let config2 = {
  12931. "note": "api2d",
  12932. "model": GM_getValue("api2d_model"),
  12933. "key": GM_getValue("api2d_key"),
  12934. "proxy": GM_getValue("api2d_request_entry") + '/v1/chat/completions',
  12935. "_header": GM_getValue("x_api2d_no_cache") ? "" : " x-api2d-no-cache : 1",
  12936. "_data": ""
  12937. }
  12938. if (GM_getValue("translation") === "api2d") {
  12939. if (GM_getValue("openai_key")) newConfig.choice = 1;
  12940. else newConfig.choice = 0;
  12941. }
  12942. newConfig.configurations.push(config2);
  12943. }
  12944. GM_setValue("chatgpt-config", newConfig);
  12945. const keysToDelete = ["openai_key", "openai_model", "openai_proxy", "api2d_key", "api2d_model", "api2d_request_entry", "x_api2d_no_cache", "showOpneAiAdvanced"];
  12946. keysToDelete.forEach(key => {
  12947. if (GM_getValue(key) != undefined) GM_deleteValue(key);
  12948. });
  12949. if (GM_getValue("translation") === "api2d") GM_setValue("translation", "openai");
  12950. location.reload();
  12951. }
  12952.  
  12953.  
  12954. // ------------------------------
  12955. // 配置自动迁移代码(将在10个小版本后移除-1.23)
  12956. // ------------------------------
  12957.  
  12958. {
  12959. let bottomZh_CN = GM_getValue("bottomZh_CN");
  12960. if (bottomZh_CN !== undefined) {
  12961. if (bottomZh_CN == true) {
  12962. GM_setValue("localizationLanguage", "zh");
  12963. } else {
  12964. GM_setValue("localizationLanguage", "initial");
  12965. }
  12966. GM_deleteValue("bottomZh_CN");
  12967. location.reload();
  12968. }
  12969. }
  12970. {
  12971. let config = GM_getValue("chatgpt-config");
  12972. if (config && config !== undefined) {
  12973. let index = parseInt(config.choice, 10);
  12974. if (index == -1) config.choice = "";
  12975. else config.choice = config.configurations[index].note;
  12976. config.configurations.forEach(function (item) {
  12977. item.name = item.note;
  12978. delete item.note;
  12979. });
  12980. GM_deleteValue("chatgpt-config");
  12981. GM_setValue("chatgpt_config", config);
  12982. location.reload();
  12983. }
  12984. }