Codeforces Better!

Codeforces界面汉化、题目翻译,markdown视图,一键复制题目

当前为 2023-06-04 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Codeforces Better!
  3. // @namespace https://greasyfork.org/users/747162
  4. // @version 1.33
  5. // @description Codeforces界面汉化、题目翻译,markdown视图,一键复制题目
  6. // @author 北极小狐
  7. // @match https://*.codeforces.com/*
  8. // @connect www2.deepl.com
  9. // @connect m.youdao.com
  10. // @connect openai.api2d.net
  11. // @connect api.openai.com
  12. // @connect greasyfork.org
  13. // @grant GM_xmlhttpRequest
  14. // @grant GM_info
  15. // @grant GM_setValue
  16. // @grant GM_getValue
  17. // @icon https://aowuucdn.oss-cn-beijing.aliyuncs.com/codeforces.png
  18. // @require https://cdn.staticfile.org/turndown/7.1.2/turndown.min.js
  19. // @require https://cdn.staticfile.org/markdown-it/13.0.1/markdown-it.min.js
  20. // @license MIT
  21. // ==/UserScript==
  22.  
  23. // 状态与初始化
  24. const getGMValue = (key, defaultValue) => {
  25. const value = GM_getValue(key);
  26. if (value === undefined) {
  27. GM_setValue(key, defaultValue);
  28. return defaultValue;
  29. }
  30. return value;
  31. };
  32. const is_mSite = window.location.hostname.startsWith('m');
  33. const is_oldLatex = $('.tex-span').length;
  34. const bottomZh_CN = getGMValue("bottomZh_CN", true);
  35. const translation = getGMValue("translation", "deepl");
  36. const expandFoldingblocks = getGMValue("expandFoldingblocks", true);
  37. var x_api2d_no_cache = getGMValue("x_api2d_no_cache", true);
  38.  
  39. // 报错信息捕获
  40. /*let errorMessages = "";
  41. const defaultError = console.error.bind(console);
  42. console.error = (message) => {
  43. const error = new Error();
  44. const stack = error.stack.split("\n").slice(2).join("\n");
  45. const now = new Date().toLocaleString();
  46. errorMessages += "\n## " + message + "\n### time: " + now +"\n" + stack + "\n";
  47. defaultError(message);
  48. };
  49. window.onerror = (message, source, lineno, colno, error) => {
  50. const now = new Date().toLocaleString();
  51. errorMessages += "\n## " + message + "\n### time: " + now +"\n" + error.stack + "\n";
  52. defaultError(message);
  53. return true;
  54. };*/
  55.  
  56. // 样式
  57. function loadCssCode(code) {
  58. var style = document.createElement('style');
  59. style.type = 'text/css';
  60. style.rel = 'stylesheet';
  61. style.appendChild(document.createTextNode(code));
  62. var head = document.getElementsByTagName('head')[0];
  63. head.appendChild(style);
  64. }
  65. loadCssCode(`
  66. :root {
  67. --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";
  68. }
  69. span.mdViewContent {
  70. white-space: pre-wrap;
  71. }
  72. /*翻译div*/
  73. .translate-problem-statement {
  74. display: grid;
  75. justify-items: start;
  76. white-space: pre-wrap;
  77. letter-spacing: 1.8px;
  78. color: #059669;
  79. background-color: #f9f9fa;
  80. border: 1px solid #10b981;
  81. border-radius: 0.3rem;
  82. padding: 5px;
  83. margin: 10px 0px;
  84. font-size: 13px;
  85. }
  86. .translate-problem-statement.error_translate {
  87. color: red;
  88. border-color: red;
  89. }
  90. .translate-problem-statement a {
  91. color: #10b981;
  92. font-weight: 600;
  93. background: 0 0;
  94. text-decoration: none;
  95. }
  96. .translate-problem-statement p {
  97. margin: 8px 0 !important;
  98. }
  99. .translate-problem-statement img {
  100. max-width: 100.0%;
  101. max-height: 100.0%;
  102. }
  103. .ttypography .translate-problem-statement .MathJax {
  104. color: #059669!important;
  105. }
  106. .translate-problem-statement span.math {
  107. margin: 0px 2.5px !important;
  108. }
  109. .translate-problem-statement a:hover {
  110. background-color: #800;
  111. color: #fff;
  112. text-decoration: none;
  113. }
  114. .html2md-panel {
  115. display: flex;
  116. justify-content: flex-end;
  117. }
  118. button.html2mdButton {
  119. cursor: pointer;
  120. background-color: #ffffff;
  121. color: #606266;
  122. height: 22px;
  123. width: auto;
  124. font-size: 13px;
  125. border-radius: 0.3rem;
  126. padding: 1px 5px;
  127. margin: 5px;
  128. border: 1px solid #dcdfe6;
  129. }
  130. button.html2mdButton.copied {
  131. background-color: #f0f9eb;
  132. color: #67c23e;
  133. border: 1px solid #b3e19d;
  134. }
  135. button.html2mdButton.mdViewed {
  136. background-color: #fdf6ec;
  137. color: #e6a23c;
  138. border: 1px solid #f3d19e;
  139. }
  140. button.translated {
  141. cursor: not-allowed;
  142. background-color: #f0f9eb;
  143. color: #67c23e;
  144. border: 1px solid #b3e19d;
  145. }
  146. button.html2mdButton.reTranslation {
  147. background-color: #f4f4f5;
  148. color: #909399;
  149. border: 1px solid #c8c9cc;
  150. }
  151. .translate-problem-statement table {
  152. border: 1px #ccc solid;
  153. border-collapse: collapse;
  154. margin: 1.3571em 0 0;
  155. color: #222;
  156. }
  157. .translate-problem-statement table td {
  158. border-right: 1px solid #ccc;
  159. border-top: 1px solid #ccc;
  160. padding: 0.7143em 0.5em;
  161. }
  162. .translate-problem-statement table th {
  163. padding: 0.7143em 0.5em;
  164. }
  165. .translate-problem-statement p:not(:first-child) {
  166. margin: 1.5em 0 0;
  167. }
  168. /*设置面板*/
  169. header .enter-or-register-box, header .languages {
  170. position: absolute;
  171. right: 170px;
  172. }
  173. button.html2mdButton.CFBetter_setting {
  174. float: right;
  175. height: 30px;
  176. background: #60a5fa;
  177. color: white;
  178. margin: 10px;
  179. }
  180. #CFBetter_setting_menu {
  181. z-index: 9999;
  182. box-shadow: 0px 0px 5px 1px rgb(0 0 0 / 10%), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  183. display: grid;
  184. position: fixed;
  185. top: 50%;
  186. left: 50%;
  187. width: 300px;
  188. transform: translate(-50%, -50%);
  189. border-radius: 16px;
  190. background-color: #ecf0ff;
  191. border: 6px solid #ffffff;
  192. color: #697e91;
  193. font-family: var(--vp-font-family-base);
  194. padding: 10px 20px 20px 20px;
  195. }
  196. #CFBetter_setting_menu hr {
  197. border: none;
  198. height: 1px;
  199. background-color: #ccc;
  200. margin: 10px 0;
  201. }
  202. /*设置面板-关闭按钮*/
  203. #CFBetter_setting_menu .tool-box {
  204. position: absolute;
  205. display: flex;
  206. align-items: center;
  207. justify-content: center;
  208. width: 2.5rem;
  209. height: 2.5rem;
  210. top: 3px;
  211. right: 3px;
  212. }
  213.  
  214. #CFBetter_setting_menu .btn-close {
  215. display: flex;
  216. align-items: center;
  217. justify-content: center;
  218. text-align: center;
  219. padding: 10px;
  220. width: 1px;
  221. height: 1px;
  222. color: transparent;
  223. font-size: 0;
  224. cursor: pointer;
  225. background-color: #ff000080;
  226. border: none;
  227. border-radius: 10px;
  228. transition: .15s ease all;
  229. }
  230.  
  231. #CFBetter_setting_menu .btn-close:hover {
  232. width: 20px;
  233. height: 20px;
  234. font-size: 17px;
  235. color: #ffffff;
  236. background-color: #ff0000cc;
  237. box-shadow: 0 5px 5px 0 #00000026;
  238. }
  239.  
  240. #CFBetter_setting_menu .btn-close:active {
  241. width: .9rem;
  242. height: .9rem;
  243. font-size: 1px;
  244. color: #ffffffde;
  245. --shadow-btn-close: 0 3px 3px 0 #00000026;
  246. box-shadow: var(--shadow-btn-close);
  247. }
  248.  
  249. /*设置面板-checkbox*/
  250. #CFBetter_setting_menu input[type=checkbox]:focus {
  251. outline: 0px;
  252. }
  253.  
  254. #CFBetter_setting_menu input[type="checkbox"] {
  255. margin: 0px;
  256. appearance: none;
  257. -webkit-appearance: none;
  258. width: 40px;
  259. height: 20px;
  260. border: 1.5px solid #6b8092;
  261. border-radius: 20px;
  262. background: #f1e1e1;
  263. position: relative;
  264. box-sizing: border-box;
  265. }
  266.  
  267. #CFBetter_setting_menu input[type="checkbox"]::before {
  268. content: "";
  269. width: 14px;
  270. height: 14px;
  271. background: #6b80927a;
  272. border: 1.5px solid #6b8092;
  273. border-radius: 50%;
  274. position: absolute;
  275. top: 0;
  276. left: 0;
  277. transform: translate(2%, 2%);
  278. transition: all 0.3s ease-in-out;
  279. }
  280.  
  281. #CFBetter_setting_menu input[type="checkbox"]::after {
  282. 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");
  283. position: absolute;
  284. top: 0;
  285. left: 24px;
  286. }
  287.  
  288. #CFBetter_setting_menu input[type="checkbox"]:checked {
  289. border: 1.5px solid #02c202;
  290. background: #e2f1e1;
  291. }
  292.  
  293. #CFBetter_setting_menu input[type="checkbox"]:checked::before {
  294. background: rgba(2, 194, 2, 0.5);
  295. border: 1.5px solid #02c202;
  296. transform: translate(122%, 2%);
  297. transition: all 0.3s ease-in-out;
  298. }
  299.  
  300. #CFBetter_setting_menu input[type="checkbox"]:checked::after {
  301. 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='%2302C202' fill-opacity='0.9'/%3E%3C/svg%3E");
  302. position: absolute;
  303. top: 1.5px;
  304. left: 4.5px;
  305. }
  306.  
  307. #CFBetter_setting_menu input[type="checkbox"] + label {
  308. margin: 0px 0px 0px 10px !important;
  309. font-size: 16px;
  310. }
  311.  
  312. .CFBetter_setting_list {
  313. display: flex;
  314. align-items: center;
  315. margin: 10px 0px;
  316. }
  317.  
  318. /*设置面板-radio*/
  319. #CFBetter_setting_menu>label {
  320. display: flex;
  321. list-style-type: none;
  322. padding-inline-start: 0px;
  323. overflow-x: auto;
  324. max-width: 100%;
  325. margin: 0px;
  326. align-items: center;
  327. margin: 3px 0px;
  328. }
  329.  
  330. .CFBetter_setting_menu_label_text {
  331. border: 1px dashed #00aeeccc;
  332. display: block;
  333. height: 20px;
  334. width: 100%;
  335. color: gray;
  336. font-weight: 300;
  337. font-size: 14px;
  338. letter-spacing: 2px;
  339. padding: 7px;
  340. }
  341.  
  342. input[type="radio"]:checked+.CFBetter_setting_menu_label_text {
  343. background: #41e49930;
  344. border: 1px solid green;
  345. color: green;
  346. font-weight: 500;
  347. }
  348.  
  349. #CFBetter_setting_menu>label input[type="radio"] {
  350. -webkit-appearance: none;
  351. appearance: none;
  352. list-style: none;
  353. margin: 0px;
  354. }
  355.  
  356. #CFBetter_setting_menu input[type="text"] {
  357. display: block;
  358. height: 25px;
  359. background-color: #ffffff;
  360. color: #727378;
  361. font-size: 12px;
  362. border-radius: 0.3rem;
  363. padding: 1px 5px;
  364. margin: 5px 0px 5px 0px;
  365. border: 1px solid #00aeeccc;
  366. box-shadow: 0 0 1px #0000004d;
  367. }
  368.  
  369. .CFBetter_setting_menu_input {
  370. width: 100%;
  371. display: grid;
  372. justify-content: start;
  373. }
  374.  
  375. #CFBetter_setting_menu #save {
  376. cursor: pointer;
  377. display: inline-flex;
  378. padding: 0.5rem 1rem;
  379. background-color: #1aa06d;
  380. color: #ffffff;
  381. font-size: 1rem;
  382. line-height: 1.5rem;
  383. font-weight: 500;
  384. justify-content: center;
  385. width: 100%;
  386. border-radius: 0.375rem;
  387. border: none;
  388. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  389. }
  390. #CFBetter_setting_menu button#debug_button.debug_button {
  391. width: 18%;
  392. }
  393.  
  394. #CFBetter_setting_menu span.tip {
  395. color: #999;
  396. font-size: 12px;
  397. font-weight: 500;
  398. padding: 5px 0px;
  399. }
  400. /*更新检查*/
  401. div#update_panel {
  402. position: fixed;
  403. top: 50%;
  404. left: 50%;
  405. width: 240px;
  406. transform: translate(-50%, -50%);
  407. background-color: #fdfdfd;
  408. border: 1px solid #00aeeccc;
  409. border-radius: 5px;
  410. box-shadow: 2px 2px 3px 1px #0000004d;
  411. padding: 10px 20px 20px 20px;
  412. color: #444242;
  413. background-color: #ecf0ff;
  414. border: 6px solid #ffffff;
  415. border-radius: 16px;
  416. }
  417. div#update_panel #updating {
  418. cursor: pointer;
  419. display: inline-flex;
  420. padding: 0px;
  421. background-color: #1aa06d;
  422. color: #ffffff;
  423. font-size: 1rem;
  424. line-height: 1.5rem;
  425. font-weight: 500;
  426. justify-content: center;
  427. width: 100%;
  428. border-radius: 0.375rem;
  429. border: none;
  430. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  431. }
  432. div#update_panel #updating a {
  433. text-decoration: none;
  434. color: white;
  435. display: flex;
  436. position: inherit;
  437. top: 0;
  438. left: 0;
  439. width: 100%;
  440. height: 22px;
  441. font-size: 14px;
  442. justify-content: center;
  443. align-items: center;
  444. }
  445. `);
  446.  
  447. // 更新检查
  448. (function checkScriptVersion() {
  449. function compareVersions(version1 = "0", version2 = "0") {
  450. const v1Array = String(version1).split(".");
  451. const v2Array = String(version2).split(".");
  452. const minLength = Math.min(v1Array.length, v2Array.length);
  453. let result = 0;
  454. for (let i = 0; i < minLength; i++) {
  455. const curV1 = Number(v1Array[i]);
  456. const curV2 = Number(v2Array[i]);
  457. if (curV1 > curV2) {
  458. result = 1;
  459. break;
  460. } else if (curV1 < curV2) {
  461. result = -1;
  462. break;
  463. }
  464. }
  465. if (result === 0 && v1Array.length !== v2Array.length) {
  466. const v1IsBigger = v1Array.length > v2Array.length;
  467. const maxLenArray = v1IsBigger ? v1Array : v2Array;
  468. for (let i = minLength; i < maxLenArray.length; i++) {
  469. const curVersion = Number(maxLenArray[i]);
  470. if (curVersion > 0) {
  471. v1IsBigger ? result = 1 : result = -1;
  472. break;
  473. }
  474. }
  475. }
  476. return result;
  477. }
  478.  
  479. GM_xmlhttpRequest({
  480. method: "GET",
  481. url: "https://greasyfork.org/zh-CN/scripts/465777.json",
  482. timeout: 10 * 1e3,
  483. onload: function (response) {
  484. const scriptData = JSON.parse(response.responseText);
  485. if (scriptData.name === GM_info.script.name && compareVersions(scriptData.version, GM_info.script.version) === 1) {
  486. $("body").append(`
  487. <div id='update_panel'>
  488. <h3>${GM_info.script.name}有新版本!</h3>
  489. <hr>
  490. <div class='update_panel_menu'>
  491. <span class ='tip'>版本信息:${GM_info.script.version} ${scriptData.version}</span>
  492. </div>
  493. <br>
  494. <button id='updating'><a target="_blank" href="${scriptData.url}">更新</a></button>
  495. </div>
  496. `);
  497. }
  498. }
  499. });
  500. })();
  501.  
  502. // 汉化替换
  503. (function () {
  504. if (!bottomZh_CN) return;
  505. // 设置语言为zh
  506. var htmlTag = document.getElementsByTagName("html")[0];
  507. htmlTag.setAttribute("lang", "zh-CN");
  508.  
  509. // 文本节点遍历替换
  510. $(document).ready(function () {
  511. function traverseTextNodes(node, rules) {
  512. if (!node) return;
  513. if (node.nodeType === Node.TEXT_NODE) {
  514. rules.forEach(rule => {
  515. const regex = new RegExp(rule.match, 'g');
  516. node.textContent = node.textContent.replace(regex, rule.replace);
  517. });
  518. } else {
  519. $(node).contents().each((_, child) => traverseTextNodes(child, rules));
  520. }
  521. }
  522.  
  523. const rules1 = [
  524. { match: 'Virtual participation', replace: '参加虚拟重现赛' },
  525. { match: 'Enter', replace: '进入' },
  526. { match: 'Current standings', replace: '当前榜单' },
  527. { match: 'Final standings', replace: '最终榜单' },
  528. { match: 'Preliminary results', replace: '初步结果' },
  529. { match: 'open hacking:', replace: '公开黑客攻击中(即尝试提交数据加强,对已通过的代码重测)' },
  530. { match: 'School/University/City/Region Championship', replace: '学校/大学/城市/区域比赛' },
  531. { match: 'Official School Contest', replace: '学校官方比赛' },
  532. { match: 'Training Contest', replace: '训练赛' },
  533. { match: 'Training Camp Contest', replace: '训练营比赛' },
  534. { match: 'Official ICPC Contest', replace: 'ICPC官方比赛' },
  535. { match: 'Official International Personal Contest', replace: '官方国际个人赛' },
  536. { match: 'China', replace: '中国' },
  537. { match: 'Statements', replace: '题目描述' },
  538. { match: 'in Chinese', replace: '中文' },
  539. { match: 'Trainings', replace: '训练' },
  540. { match: 'Prepared by', replace: '编写人' },
  541. { match: 'Current or upcoming contests', replace: '当前或即将举行的比赛' },
  542. { match: 'Past contests', replace: '过去的比赛' },
  543. { match: 'Exclusions', replace: '排除' },
  544. { match: 'Before start', replace: '还有' },
  545. { match: 'Before registration', replace: '距报名开始还有' },
  546. { match: 'Until closing ', replace: '距报名结束还有' },
  547. { match: 'Register', replace: '报名' },
  548. { match: 'Registration completed', replace: '已报名' },
  549. { match: 'Problems', replace: '问题集' },
  550. { match: 'Questions about problems', replace: '关于问题的提问' },
  551. { match: 'Contest status', replace: '比赛状态' },
  552. ];
  553. traverseTextNodes($('.datatable'), rules1);
  554.  
  555. const rules2 = [
  556. { match: 'Home', replace: '主页' },
  557. { match: 'Top', replace: '热门' },
  558. { match: 'Catalog', replace: '指南目录' },
  559. { match: 'Contests', replace: '比赛' },
  560. { match: 'Gym', replace: '训练营(过去的大型比赛)' },
  561. { match: 'Problemset', replace: '题单' },
  562. { match: 'Groups', replace: '团体' },
  563. { match: 'Rating', replace: 'Rating(评级)排行榜' },
  564. { match: 'Edu', replace: '培训' },
  565. { match: 'Calendar', replace: '日历' },
  566. { match: 'Help', replace: '帮助' }
  567. ];
  568. traverseTextNodes($('.menu-list.main-menu-list'), rules2);
  569.  
  570. const rules3 = [
  571. { match: 'Settings', replace: '设置' },
  572. { match: 'Blog', replace: '博客' },
  573. { match: 'Teams', replace: '队伍' },
  574. { match: 'Submissions', replace: '提交' },
  575. { match: 'Favourites', replace: '收藏' },
  576. { match: 'Talks', replace: '私信' },
  577. { match: 'Contests', replace: '比赛' },
  578. ];
  579. traverseTextNodes($('.nav-links'), rules3);
  580.  
  581. const rules4 = [
  582. { match: 'Before contest', replace: '即将进行的比赛' },
  583. { match: 'Contest is running', replace: '比赛进行中' },
  584. ];
  585. traverseTextNodes($('.contest-state-phase'), rules4);
  586.  
  587. const rules5 = [
  588. { match: 'has extra registration', replace: '有额外的报名时期' },
  589. { match: 'If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes.', replace: '如果您在比赛开始前5分钟前还未报名,您可以在额外的报名期间稍后报名。额外的报名将在比赛开始后10分钟开放,并持续25分钟。' },
  590. ];
  591. traverseTextNodes($('.notice'), rules5);
  592.  
  593. const rules6 = [
  594. { match: 'Contribution', replace: '贡献' },
  595. ];
  596. traverseTextNodes($('.propertyLinks'), rules6);
  597.  
  598. const rules7 = [
  599. { match: 'Contest history', replace: '比赛历史' },
  600. ];
  601. traverseTextNodes($('.contests-table'), rules7);
  602.  
  603. const rules8 = [
  604. { match: 'Register now', replace: '现在报名' },
  605. ];
  606. traverseTextNodes($('.roundbox.sidebox.borderTopRound '), rules8);
  607.  
  608. const rules9 = [
  609. { match: 'Add to exclusions', replace: '添加到排除列表' },
  610. ];
  611. traverseTextNodes($('.icon-eye-close.icon-large'), rules9);
  612.  
  613. const rules10 = [
  614. { match: 'Add to exclusions for gym contests filter', replace: '添加训练营过滤器的排除项' },
  615. ];
  616. traverseTextNodes($("._ContestFilterExclusionsManageFrame_addExclusionLink"), rules10);
  617.  
  618. const rules11 = [
  619. { match: 'Announcement', replace: '公告' },
  620. { match: 'Statements', replace: '统计报表' },
  621. { match: 'Tutorial', replace: '题解' },
  622. ];
  623. traverseTextNodes($('.roundbox.sidebox.sidebar-menu.borderTopRound '), rules11);
  624.  
  625. const rules12 = [
  626. { match: 'Problems', replace: '问题' },
  627. { match: 'Submit Code', replace: '提交代码' },
  628. { match: 'My Submissions', replace: '我的提交' },
  629. { match: 'Status', replace: '状态' },
  630. { match: 'Standings', replace: '榜单' },
  631. { match: 'Custom Invocation', replace: '自定义调试' },
  632. { match: 'Common standings', replace: '全部排行' },
  633. { match: 'Friends standings', replace: '只看朋友' },
  634. { match: 'Submit', replace: '提交' },
  635. { match: 'Hacks', replace: '黑客' },
  636. { match: 'Room', replace: '房间' },
  637. { match: 'Custom test', replace: '自定义测试' },
  638. { match: 'Blog', replace: '博客' },
  639. { match: 'Teams', replace: '队伍' },
  640. { match: 'Submissions', replace: '提交记录' },
  641. { match: 'Groups', replace: '团体' },
  642. { match: 'Favourites', replace: '收藏' },
  643. { match: 'Contests', replace: '比赛' },
  644. { match: '问题etting', replace: '参与编写的问题' },
  645. { match: 'Gym', replace: '训练营' },
  646. { match: 'Mashups', replace: '组合混搭' },
  647. { match: 'Posts', replace: '帖子' },
  648. { match: '>Comments<', replace: '>回复<' },
  649. { match: 'Main', replace: '主要' },
  650. { match: 'Settings', replace: '设置' },
  651. { match: 'Lists', replace: '列表' },
  652. { match: 'General', replace: '基本' },
  653. { match: 'Sidebar', replace: '侧边栏' },
  654. { match: 'Social', replace: '社会信息' },
  655. { match: 'Address', replace: '地址' },
  656. { match: 'Wallets', replace: '钱包' },
  657. ];
  658. traverseTextNodes($('.second-level-menu'), rules12);
  659. if (is_mSite) {
  660. traverseTextNodes($('nav'), rules12);
  661. }
  662.  
  663. const rules13 = [
  664. { match: 'Expand', replace: '展开' }
  665. ];
  666. traverseTextNodes($('.topic-toggle-collapse'), rules13);
  667.  
  668. const rules14 = [
  669. { match: 'Full text and comments', replace: '阅读全文/评论' }
  670. ];
  671. traverseTextNodes($('.topic-read-more'), rules14);
  672.  
  673. const rules15 = [
  674. { match: 'Switch off editor', replace: '关闭编辑器语法高亮' }
  675. ];
  676. traverseTextNodes($('.toggleEditorCheckboxLabel'), rules15);
  677.  
  678. const rules16 = [
  679. { match: 'Registration for the contest', replace: '比赛报名' }
  680. ];
  681. traverseTextNodes($('.submit'), rules16);
  682.  
  683. const rules17 = [
  684. { match: 'Difficulty:', replace: '难度:' },
  685. ];
  686. traverseTextNodes($('._FilterByTagsFrame_difficulty'), rules17);
  687.  
  688. const rules18 = [
  689. { match: 'Add tag', replace: '添加标签' }
  690. ];
  691. traverseTextNodes($('._FilterByTagsFrame_addTagLink'), rules18);
  692.  
  693. const rules19 = [
  694. { match: 'Reminder: in case of any technical issues, you can use the lightweight website', replace: '提醒:如果出现任何技术问题,您可以使用轻量网站' }
  695. ];
  696. traverseTextNodes($('.alert'), rules19);
  697.  
  698. const rules20 = [
  699. { match: 'Enter', replace: '登录' },
  700. { match: 'Register', replace: '注册' },
  701. { match: 'Contest rating', replace: '测试 rating' },
  702. { match: 'Logout', replace: '退出登录' }
  703. ];
  704. traverseTextNodes($('.lang-chooser'), rules20);
  705.  
  706. const rules21 = [
  707. { match: 'Change photo', replace: '更换图片' },
  708. { match: 'Contest rating', replace: '比赛Rating' },
  709. { match: 'Contribution', replace: '贡献' },
  710. { match: 'My friends', replace: '我的好友' },
  711. { match: 'Change settings', replace: '改变设置' },
  712. { match: 'Last visit', replace: '最后访问' },
  713. { match: 'Registered', replace: '注册于' },
  714. { match: 'Blog entries', replace: '博客条目' },
  715. { match: 'comments', replace: '评论' },
  716. { match: 'Write new entry', replace: '编写新条目' },
  717. { match: 'View my talks', replace: '查看我的私信' },
  718. { match: 'Talks', replace: '私信' },
  719. { match: 'Send message', replace: '发送消息' },
  720. ];
  721. traverseTextNodes($('.userbox'), rules21);
  722.  
  723. const rules22 = [
  724. { match: 'Reset', replace: '重置' },
  725. ];
  726. traverseTextNodes($('#vote-reset-filterDifficultyLowerBorder'), rules22);
  727. traverseTextNodes($('#vote-reset-filterDifficultyUpperBorder'), rules22);
  728.  
  729. const rules23 = [
  730. { match: 'The problem statement has recently been changed.', replace: '题目描述最近已被更改。\n(说明:如果是进入该页面后立即显示的,这通常是Codeforces Better!插入翻译按钮导致的)' },
  731. { match: 'View the changes.', replace: '查看更改' },
  732. ];
  733. traverseTextNodes($('.alert.alert-info'), rules23);
  734. });
  735. // 元素选择替换
  736. // 侧栏titled汉化
  737. (function () {
  738. var translations = {
  739. "Pay attention": "→ 注意",
  740. "Top rated": "→ 评级排行",
  741. "Top contributors": "→ 贡献者排行",
  742. "Find user": "→ 查找用户",
  743. "Recent actions": "→ 最新动态",
  744. "Training filter": "→ 过滤筛选",
  745. "Find training": "→ 搜索比赛/问题",
  746. "Virtual participation": "→ 什么是虚拟参赛",
  747. "Contest materials": "→ 比赛相关资料",
  748. "Settings": "→ 设置",
  749. "Clone Contest to Mashup": "→ 克隆比赛到组合混搭",
  750. "Submit": "→ 提交",
  751. "Practice": "→ 练习",
  752. "Problem tags": "→ 问题标签",
  753. "Filter Problems": "→ 过滤问题",
  754. "Attention": "→ 注意",
  755. "About Contest": "→ 关于比赛",
  756. "Last submissions": "→ 提交历史",
  757. "Streams": "→ 直播",
  758. "Coach rights": "→ 教练权限",
  759. "Advices to fill address": "→ 填写地址的建议",
  760. "Hacks filter": "→ 黑客过滤器",
  761. "Score table": "→ 评分表",
  762. "Contests": "→ 比赛",
  763. "Login into Codeforces": "登录 Codeforces",
  764. };
  765.  
  766. $(".caption.titled").each(function () {
  767. var tag = $(this).text();
  768. for (var property in translations) {
  769. if (tag.match(property)) {
  770. $(this).addClass(property);
  771. $(this).text(translations[property]);
  772. break;
  773. }
  774. }
  775. });
  776. })();
  777. // 题目Tag汉化
  778. (function () {
  779. var parentElement = $('._FilterByTagsFrame_addTagLabel');
  780. var selectElement = parentElement.find('select');
  781. var translations = {
  782. "*combine tags by OR": "*按逻辑或组合我选择的标签",
  783. "combine-tags-by-or": "*按逻辑或组合我选择的标签(combine-tags-by-or)",
  784. "2-sat": "二分图可满足性问题(2-sat)",
  785. "binary search": "二分搜索(binary search)",
  786. "bitmasks": "位掩码(bitmasks)",
  787. "brute force": "暴力枚举(brute force)",
  788. "chinese remainder theorem": "中国剩余定理(chinese remainder theorem)",
  789. "combinatorics": "组合数学(combinatorics)",
  790. "constructive algorithms": "构造算法(constructive algorithms)",
  791. "data structures": "数据结构(data structures)",
  792. "dfs and similar": "深度优先搜索及其变种(dfs and similar)",
  793. "divide and conquer": "分治算法(divide and conquer)",
  794. "dp": "动态规划(dp)",
  795. "dsu": "并查集(dsu)",
  796. "expression parsing": "表达式解析(expression parsing)",
  797. "fft": "快速傅里叶变换(fft)",
  798. "flows": "流(flows)",
  799. "games": "博弈论(games)",
  800. "geometry": "计算几何(geometry)",
  801. "graph matchings": "图匹配(graph matchings)",
  802. "graphs": "图论(graphs)",
  803. "greedy": "贪心策略(greedy)",
  804. "hashing": "哈希表(hashing)",
  805. "implementation": "实现问题,编程技巧,模拟(implementation)",
  806. "interactive": "交互性问题(interactive)",
  807. "math": "数学(math)",
  808. "matrices": "矩阵(matrices)",
  809. "meet-in-the-middle": "meet-in-the-middle算法(meet-in-the-middle)",
  810. "number theory": "数论(number theory)",
  811. "probabilities": "概率论(probabilities)",
  812. "schedules": "调度算法(schedules)",
  813. "shortest paths": "最短路算法(shortest paths)",
  814. "sortings": "排序算法(sortings)",
  815. "string suffix structures": "字符串后缀结构(string suffix structures)",
  816. "strings": "字符串处理(strings)",
  817. "ternary search": "三分搜索(ternary search)",
  818. "trees": "树形结构(trees)",
  819. "two pointers": "双指针算法(two pointers)"
  820. };
  821. selectElement.find("option").each(function () {
  822. var optionValue = $(this).val();
  823. if (translations[optionValue]) {
  824. $(this).text(translations[optionValue]);
  825. }
  826. });
  827. $("._FilterByTagsFrame_tagBoxCaption").each(function () {
  828. var tag = $(this).text();
  829. if (tag in translations) {
  830. $(this).text(translations[tag]);
  831. }
  832. });
  833. $(".notice").each(function () {
  834. var tag = $(this).text();
  835. if (tag in translations) {
  836. $(this).text(translations[tag]);
  837. }
  838. });
  839. $(".tag-box").each(function () {
  840. var tag = $(this).text();
  841. for (var property in translations) {
  842. property = property.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
  843. if (tag.match(property)) {
  844. $(this).text(translations[property]);
  845. break;
  846. }
  847. }
  848. });
  849. })();
  850. // 题目过滤器选项汉化
  851. (function () {
  852. var parentElement = $('#gym-filter-form');
  853. var selectElement = parentElement.find('div');
  854. var translations = {
  855. "Contest type:": "比赛类型:",
  856. "ICPC region:": "ICPC地区:",
  857. "Contest format:": "比赛形式:",
  858. "Order by:": "排序方式:",
  859. "Secondary order by:": "次要排序方式:",
  860. "Hide, if participated:": "隐藏我参加过的:",
  861. };
  862. selectElement.find("label").each(function () {
  863. var optionValue = $(this).text();
  864. if (translations[optionValue]) {
  865. $(this).text(translations[optionValue]);
  866. }
  867. });
  868. translations = {
  869. "Season:": "时间范围(年度)",
  870. "Duration, hours:": "持续时间(小时):",
  871. "Difficulty:": "难度:"
  872. };
  873. selectElement.each(function () {
  874. var optionValue = $(this).text();
  875. if (translations[optionValue]) {
  876. $(this).text(translations[optionValue]);
  877. }
  878. });
  879. })();
  880. (function () {
  881. var parentElement = $('.setting-value');
  882. var selectElement = parentElement.find('select');
  883. var translations = {
  884. "Official ACM-ICPC Contest": "ICPC官方比赛",
  885. "Official School Contest": "学校官方比赛",
  886. "Opencup Contest": "Opencup比赛",
  887. "School/University/City/Region Championship": "学校/大学/城市/地区锦标赛",
  888. "Training Camp Contest": "训练营比赛",
  889. "Official International Personal Contest": "官方国际个人赛",
  890. "Training Contest": "训练比赛",
  891. "ID_ASC": "创建时间(升序)",
  892. "ID_DESC": "创建时间(降序)",
  893. "RATING_ASC": "评分(升序)",
  894. "RATING_DESC": "评分(降序)",
  895. "DIFFICULTY_ASC": "难度(升序)",
  896. "DIFFICULTY_DESC": "难度(降序)",
  897. "START_TIME_ASC": "开始时间(升序)",
  898. "START_TIME_DESC": "开始时间(降序)",
  899. "DURATION_ASC": "持续时间(升序)",
  900. "DURATION_DESC": "持续时间(降序)",
  901. "POPULARITY_ASC": "热度(升序)",
  902. "POPULARITY_DESC": "热度(降序)",
  903. "UPDATE_TIME_ASC": "更新时间(升序)",
  904. "UPDATE_TIME_DESC": "更新时间(降序)"
  905. };
  906. selectElement.find("option").each(function () {
  907. var optionValue = $(this).val();
  908. if (translations[optionValue]) {
  909. $(this).text(translations[optionValue]);
  910. }
  911. });
  912. parentElement = $('.setting-last-value');
  913. selectElement = parentElement.find('select');
  914. selectElement.find("option").each(function () {
  915. var optionValue = $(this).val();
  916. if (translations[optionValue]) {
  917. $(this).text(translations[optionValue]);
  918. }
  919. });
  920. })();
  921. // 右侧sidebox通用汉化
  922. (function () {
  923. var parentElement = $('.sidebox');
  924. var selectElement = parentElement.find('div');
  925. var translations = {
  926. "Show tags for unsolved problems": "显示未解决问题的标签",
  927. "Hide solved problems": "隐藏已解决的问题",
  928. };
  929. selectElement.find("label").each(function () {
  930. var optionValue = $(this).text();
  931. if (translations[optionValue]) {
  932. $(this).text(translations[optionValue]);
  933. }
  934. });
  935. })();
  936. // 表单字段名汉化
  937. (function () {
  938. var translations = {
  939. "Problem:": "题目:",
  940. "Language:": "语言:",
  941. "Source code:": "源代码:",
  942. "Or choose file:": "或者选择文件:",
  943. "Choose file:": "选择文件:",
  944. "Notice:": "注意:",
  945. "virtual participation:": "虚拟参与:",
  946. "Registration for the contest:": "比赛报名:",
  947. "Take part:": "参与:",
  948. "as individual participant:": "作为个人参与者:",
  949. "as a team member:": "作为团队成员:",
  950. "Virtual start time:": "虚拟开始时间:",
  951. "Complete problemset:": "完整的问题集:",
  952. "First name (English)": "名字(英文)",
  953. "Last name (English)": "姓氏(英文)",
  954. "First name (Native)": "名字(本地语言)",
  955. "Last name (Native)": "姓氏(本地语言)",
  956. "Birth date": "出生日期",
  957. "Country": "国家",
  958. "City": "城市",
  959. "Organization": "组织",
  960. "Handle/Email": "账号/邮箱",
  961. "Password": "密码",
  962. };
  963. $(".field-name").each(function () {
  964. var optionValue = $(this).text();
  965. if (translations[optionValue]) {
  966. $(this).text(translations[optionValue]);
  967. }
  968. });
  969. })();
  970. (function () {
  971. var translations = {
  972. "Terms of agreement:": "协议条款:",
  973. "Choose team:": "选择团队:"
  974. };
  975. $(".field-name label").each(function () {
  976. var optionValue = $(this).text();
  977. if (translations[optionValue]) {
  978. $(this).text(translations[optionValue]);
  979. }
  980. });
  981. })();
  982. (function () {
  983. var translations = {
  984. "Hide sidebar block \"Find user\"": "隐藏侧边栏块“查找用户”",
  985. "Hide sidebar block \"Current user\"": "隐藏侧边栏块“当前用户”",
  986. "Hide sidebar block \"Recent аctions\"": "隐藏侧边栏块“最新动态”",
  987. "Hide sidebar block \"Favourite groups\"": "隐藏侧边栏块“收藏组”",
  988. "Hide sidebar block \"Top contributors\"": "隐藏侧边栏块“贡献者排行”",
  989. "Hide sidebar block \"Top rated\"": "隐藏侧边栏块“评级排行”",
  990. "Hide sidebar block \"Streams\"": "隐藏侧边栏块“直播”",
  991. "Old password": "旧密码",
  992. "New password": "新密码",
  993. "Confirm new password": "确认新密码",
  994. "Contest email notification": "比赛邮件通知",
  995. "Send email on new user talk": "在有新用户对话时发送电子邮件",
  996. "Send email on new comment": "在有新评论时发送电子邮件",
  997. "Hide contact information": "隐藏联系人信息",
  998. "Remember me by Gmail, Facebook and etc": "通过 Gmail、Facebook 等记住我",
  999. "Show tags for unsolved problems": "显示未解决问题的标签",
  1000. "Hide solved problems from problemset": "从问题集中隐藏已解决的问题",
  1001. "Hide low rated blogs": "隐藏评级较低的博客",
  1002. "Offer to publish great rating rises": "提供展示Rating显著提升的机会",
  1003. "Enforce https": "强制 HTTPS",
  1004. "Show private activity in the profile": "在个人资料中显示私人活动",
  1005. "Show diagnostics": "显示诊断信息"
  1006. };
  1007. $(".field-name").each(function () {
  1008. var tag = $(this).text();
  1009. for (var property in translations) {
  1010. property = property.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
  1011. if (tag.match(property)) {
  1012. $(this).text(translations[property]);
  1013. break;
  1014. }
  1015. }
  1016. });
  1017. })();
  1018. (function () {
  1019. var translations = {
  1020. "Postal/zip code": "邮政编码/邮编",
  1021. "Country (English)": "国家(英文)",
  1022. "State (English)": "州/省份(英文)",
  1023. "City (English)": "城市(英文)",
  1024. "Address (English)": "地址(英文)",
  1025. "Recipient (English)": "收件人姓名(英文)",
  1026. "Country (Native)": "国家(本地语言)",
  1027. "State (Native)": "州/省份(本地语言)",
  1028. "City (Native)": "城市(本地语言)",
  1029. "Address (Native)": "地址(本地语言)",
  1030. "Recipient (Native)": "收件人姓名(本地语言)",
  1031. "Phone": "电话",
  1032. "TON Wallet:": "TON 钱包:",
  1033. "Secret Code:": "验证码:"
  1034. };
  1035. $("td.field-name label").each(function () {
  1036. var optionValue = $(this).text();
  1037. if (translations[optionValue]) {
  1038. $(this).text(translations[optionValue]);
  1039. }
  1040. });
  1041. })();
  1042.  
  1043. // 按钮汉化input[type="submit"]
  1044. (function () {
  1045. var translations = {
  1046. "Register for virtual participation": "报名虚拟参赛",
  1047. "Register for practice": "登录以开始练习",
  1048. "Apply": "应用",
  1049. "Register": "报名",
  1050. "Login": "登录",
  1051. "Run": "运行",
  1052. "Start virtual contest": "开始虚拟参赛",
  1053. "Clone Contest": "克隆比赛",
  1054. "Submit": "提交",
  1055. "Save changes": "保存设置",
  1056. };
  1057. $('input[type="submit"]').each(function () {
  1058. var optionValue = $(this).val();
  1059. if (translations[optionValue]) {
  1060. $(this).val(translations[optionValue]);
  1061. }
  1062. });
  1063. })();
  1064. (function () {
  1065. var translations = {
  1066. "Reset": "重置",
  1067. };
  1068. $('input[type="button"]').each(function () {
  1069. var optionValue = $(this).val();
  1070. if (translations[optionValue]) {
  1071. $(this).val(translations[optionValue]);
  1072. }
  1073. });
  1074. })();
  1075.  
  1076. // 选项汉化input[type="radio"]
  1077. (function () {
  1078. var translations = {
  1079. "as individual participant": "个人",
  1080. "as a team member": "作为一个团队成员",
  1081. };
  1082. $('input[type="radio"]').each(function () {
  1083. var tag = $(this).parent().contents().filter(function() {
  1084. return this.nodeType === Node.TEXT_NODE;
  1085. });
  1086. for (var i = 0; i < tag.length; i++) {
  1087. var text = tag[i].textContent.trim();
  1088. if (translations.hasOwnProperty(text)) {
  1089. $(this).addClass(text);
  1090. tag[i].replaceWith(translations[text]);
  1091. break;
  1092. }
  1093. }
  1094. });
  1095. })();
  1096.  
  1097.  
  1098. // 杂项
  1099. (function () {
  1100. var translations = {
  1101. "(standard input\/output)": "标准输入/输出",
  1102. };
  1103. $("div.notice").each(function () {
  1104. var tag = $(this).children().eq(0).text();
  1105. for (var property in translations) {
  1106. if (tag.match(property)) {
  1107. $(this).children().eq(0).text(translations[property]);
  1108. break;
  1109. }
  1110. }
  1111. });
  1112. })();
  1113. (function () {
  1114. var translations = {
  1115. "Ask a question": "提一个问题",
  1116. };
  1117. $(".ask-question-link").each(function () {
  1118. var optionValue = $(this).text();
  1119. if (translations[optionValue]) {
  1120. $(this).text(translations[optionValue]);
  1121. }
  1122. });
  1123. })();
  1124.  
  1125. // 轻量站特殊
  1126. if (is_mSite) {
  1127. (function () {
  1128. var translations = {
  1129. "Announcements": "公告",
  1130. "Submissions": "提交记录",
  1131. "Contests": "比赛",
  1132. };
  1133. $(".caption").each(function () {
  1134. var optionValue = $(this).text();
  1135. if (translations[optionValue]) {
  1136. $(this).text(translations[optionValue]);
  1137. }
  1138. });
  1139. })();
  1140. }
  1141. })();
  1142.  
  1143. // 设置面板
  1144.  
  1145. $("div[class='lang-chooser']").each(function () {
  1146. $(this).before(
  1147. "<button class='html2mdButton CFBetter_setting'>CodeforcesBetter设置</button>"
  1148. );
  1149. });
  1150. $("div[class='enter-or-register-box']").each(function () {
  1151. $(this).after(
  1152. "<button class='html2mdButton CFBetter_setting'>CodeforcesBetter设置</button>"
  1153. );
  1154. });
  1155. $(document).ready(function () {
  1156. $(".CFBetter_setting").click(function () {
  1157. $(".CFBetter_setting").attr("disabled", true);
  1158. $(".CFBetter_setting").css({
  1159. "background-color": "#e6e6e6",
  1160. "color": "#727378",
  1161. "border": "1px solid #cecece",
  1162. "cursor": "not-allowed"
  1163. });
  1164. $("body").append(`
  1165. <div id='CFBetter_setting_menu'>
  1166. <div class="tool-box">
  1167. <button class="btn-close">×</button>
  1168. </div>
  1169. <h3>基本设置</h3>
  1170. <hr>
  1171. <div class='CFBetter_setting_list'>
  1172. <input type="checkbox" id="bottomZh_CN" name="bottomZh_CN">
  1173. <label for="bottomZh_CN">界面汉化</label>
  1174. </div>
  1175. <div class='CFBetter_setting_list'>
  1176. <input type="checkbox" id="expandFoldingblocks" name="expandFoldingblocks">
  1177. <label for="expandFoldingblocks">自动展开折叠块</label>
  1178. </div>
  1179. <h3>翻译设置</h3>
  1180. <hr>
  1181. <label>
  1182. <input type='radio' name='translation' value='deepl'>
  1183. <span class='CFBetter_setting_menu_label_text'>deepl翻译</span>
  1184. </label>
  1185. <label>
  1186. <input type='radio' name='translation' value='youdao'>
  1187. <span class='CFBetter_setting_menu_label_text'>有道翻译</span>
  1188. </label>
  1189. <label>
  1190. <input type='radio' name='translation' value='openai'>
  1191. <span class='CFBetter_setting_menu_label_text'>使用ChatGPT翻译(API)</span>
  1192. </label>
  1193. <label>
  1194. <input type='radio' name='translation' value='api2d'>
  1195. <span class='CFBetter_setting_menu_label_text'>使用api2d翻译(API)</span>
  1196. </label>
  1197. <div class='CFBetter_setting_menu_input' id='baidu' style='display: none;'>
  1198. <label for='baidu_uid'>APP ID:</label><input type='text' id='baidu_uid'>
  1199. <label for='baidu_key'>KEY:</label><input type='text' id='baidu_key'>
  1200. </div>
  1201. <div class='CFBetter_setting_menu_input' id='openai' style='display: none;'>
  1202. <span class ='tip'>提示:<br>请确保你能够正常访问OpenAIapi<br></span>
  1203. <span class ='tip'>使用ChatGPT-3.5进行翻译,脚本的所有请求均在本地完成,</span>
  1204. <span class ='tip'>你需要输入自己的OpenAI KEY,<a target="_blank" href="https://platform.openai.com/account/usage">官网</a></span>
  1205. <label for='openai_key'>KEY:</label><input type='text' id='openai_key'>
  1206. </div>
  1207. <div class='CFBetter_setting_menu_input' id='api2d' style='display: none;'>
  1208. <span class ='tip'>提示:<br>api2d是国内的一家提供代理直连访问OpenAIapi的服务商,相当于OpenAIapi的套壳<br></span>
  1209. <span class ='tip'>使用ChatGPT-3.5进行翻译,脚本的所有请求均在本地完成<br></span>
  1210. <span class ='tip'>你需要输入自己的api2d KEY,<a target="_blank" href="https://api2d.com/profile">官网</a></span>
  1211. <label for='api2d_key'>KEY:</label><input type='text' id='api2d_key'>
  1212. <div class='CFBetter_setting_list'>
  1213. <input type="checkbox" id="x_api2d_no_cache" name="x_api2d_no_cache">
  1214. <label for="x_api2d_no_cache">使用缓存</label>
  1215. </div>
  1216. <span class ='tip'>?API2D 的服务器会对请求结果做缓存,如果请求文本的hash值相同,会直接返回缓存的结果。缓存命中之后,本次请求不会扣除任何点数。</span>
  1217. <span class ='tip'>缓存会保存 24 小时,如果不想使用缓存,你可以关闭“使用缓存”来跳过缓存,强制 API2D 服务器发送新请求。<a target="_blank" href="https://api2d.com/wiki/doc">详请阅读官方文档</a></span>
  1218. </div>
  1219. <br>
  1220. <button id='save'>保存</button>
  1221. </div>
  1222. `);
  1223. $("#bottomZh_CN").prop("checked", GM_getValue("bottomZh_CN") === true);
  1224. $("#expandFoldingblocks").prop("checked", GM_getValue("expandFoldingblocks") === true);
  1225. $("#x_api2d_no_cache").prop("checked", GM_getValue("x_api2d_no_cache") === true);
  1226. $("input[name='translation'][value='" + translation + "']").prop("checked", true);
  1227. $("input[name='translation']").css("color", "gray");
  1228. if (translation == "baidu") {
  1229. $("#baidu").show();
  1230. $("#baidu_uid").val(GM_getValue("baidu_uid"));
  1231. $("#baidu_key").val(GM_getValue("baidu_key"));
  1232. $("#baidu_uid").css("color", "gray");
  1233. $("#baidu_key").css("color", "gray");
  1234. } else if (translation == "openai") {
  1235. $("#openai").show();
  1236. $("#openai_key").val(GM_getValue("openai_key"));
  1237. $("#openai_key").css("color", "gray");
  1238. } else if (translation == "api2d") {
  1239. $("#api2d").show();
  1240. $("#api2d_key").val(GM_getValue("api2d_key"));
  1241. $("#api2d_key").css("color", "gray");
  1242. }
  1243.  
  1244.  
  1245. // 当单选框被选中时,显示对应的输入框,同时隐藏其他输入框
  1246. $("input[name='translation']").change(function () {
  1247. var selected = $(this).val(); // 获取当前选中的值
  1248. if (selected === "baidu") {
  1249. $("#baidu").show();
  1250. $("#baidu_uid").val(GM_getValue("baidu_uid"));
  1251. $("#baidu_key").val(GM_getValue("baidu_key"));
  1252. $("#openai, #api2d").hide();
  1253. } else if (selected === "openai") {
  1254. $("#openai").show();
  1255. $("#openai_key").val(GM_getValue("openai_key"));
  1256. $("#baidu, #api2d").hide();
  1257. } else if (selected === "api2d") {
  1258. $("#api2d").show();
  1259. $("#api2d_key").val(GM_getValue("api2d_key"));
  1260. $("#x_api2d_no_cache").prop("checked", GM_getValue("x_api2d_no_cache"));
  1261. $("#baidu, #openai").hide();
  1262. } else {
  1263. $("#baidu, #openai, #api2d").hide();
  1264. }
  1265. });
  1266.  
  1267.  
  1268. $("#save").click(function () {
  1269. GM_setValue("bottomZh_CN", $("#bottomZh_CN").prop("checked"));
  1270. GM_setValue("expandFoldingblocks", $("#expandFoldingblocks").prop("checked"));
  1271. var translation = $("input[name='translation']:checked").val();
  1272. var baidu_uid = $("#baidu_uid").val();
  1273. var baidu_key = $("#baidu_key").val();
  1274. var openai_key = $("#openai_key").val();
  1275. var api2d_key = $("#api2d_key").val();
  1276. GM_setValue("translation", translation);
  1277. if (translation == "baidu") {
  1278. GM_setValue("baidu_uid", baidu_uid);
  1279. GM_setValue("baidu_key", baidu_key);
  1280. } else if (translation == "openai") {
  1281. GM_setValue("openai_key", openai_key);
  1282. } else if (translation == "api2d") {
  1283. GM_setValue("api2d_key", api2d_key);
  1284. GM_setValue("x_api2d_no_cache", $("#x_api2d_no_cache").prop("checked"));
  1285. }
  1286. location.reload();
  1287.  
  1288. /* 切换汉化
  1289. if(JSON.parse(GM_getValue("bottomZh_CN")) != $("#bottomZh_CN").prop("checked")){
  1290. GM_setValue("bottomZh_CN", $("#bottomZh_CN").prop("checked"), 3650);
  1291. location.reload();
  1292. }else{
  1293. $("#CFBetter_setting_menu .btn-close").click();
  1294. }*/
  1295. });
  1296.  
  1297. // 关闭
  1298. $("#CFBetter_setting_menu .btn-close").click(function () {
  1299. $("#CFBetter_setting_menu").remove();
  1300. $(".CFBetter_setting").attr("disabled", false);
  1301. $(".CFBetter_setting").css("background-color", "#60a5fa");
  1302. $(".CFBetter_setting").css("color", "white");
  1303. $(".CFBetter_setting").css("cursor", "pointer");
  1304. });
  1305. });
  1306. });
  1307.  
  1308. // 说明为旧的latex渲染
  1309. if (is_oldLatex) {
  1310. var newElement = $("<div></div>").addClass("alert alert-warning").html(`
  1311. 注意:当前页面存在使用非 MathJax 库渲染为 HTML Latex 公式(这通常是一道古老的题目),这导致 CodeforcesBetter! 无法将其还原回 Latex,因此当前页面部分功能不适用。
  1312. <br>此外当前页面的翻译功能采用了特别的实现方式,因此可能会出现排版错位的情况。
  1313. `).css({
  1314. "margin": "1em",
  1315. "text-align": "center",
  1316. "position": "relative"
  1317. });
  1318. $(".menu-box:first").next().after(newElement);
  1319. }
  1320.  
  1321. // md2html转换/处理规则
  1322. var turndownService = new TurndownService({bulletListMarker: '-'});
  1323. var turndown = turndownService.turndown;
  1324.  
  1325. // 保留原始
  1326. turndownService.keep(['del']);
  1327.  
  1328. // 丢弃
  1329. turndownService.addRule('ignore-sample-tests', {
  1330. filter: function (node) {
  1331. return node.classList.contains('sample-tests') || node.classList.contains('header');
  1332. },
  1333. replacement: function (content, node) {
  1334. return "";
  1335. }
  1336. });
  1337. turndownService.addRule('remove-script', {
  1338. filter: function (node, options) {
  1339. return node.tagName.toLowerCase() == "script" && node.type.startsWith("math/tex");
  1340. },
  1341. replacement: function (content, node) {
  1342. return "";
  1343. }
  1344. });
  1345.  
  1346. // inline math
  1347. turndownService.addRule('inline-math', {
  1348. filter: function (node, options) {
  1349. return node.tagName.toLowerCase() == "span" && node.className == "MathJax";
  1350. },
  1351. replacement: function (content, node) {
  1352. return "$ " + $(node).next().text() + " $";
  1353. }
  1354. });
  1355.  
  1356. // block math
  1357. turndownService.addRule('block-math', {
  1358. filter: function (node, options) {
  1359. return node.tagName.toLowerCase() == "div" && node.className == "MathJax_Display";
  1360. },
  1361. replacement: function (content, node) {
  1362. return "\n$$\n" + $(node).next().text() + "\n$$\n";
  1363. }
  1364. });
  1365.  
  1366. // 表格
  1367. turndownService.addRule('bordertable', {
  1368. filter: 'table',
  1369. replacement: function (content, node) {
  1370. if (node.classList.contains('bordertable')) {
  1371. var output = [],
  1372. thead = '',
  1373. trs = node.querySelectorAll('tr');
  1374. if (trs.length > 0) {
  1375. var ths = trs[0].querySelectorAll('th');
  1376. if (ths.length > 0) {
  1377. thead = '| ' + Array.from(ths).map(th => turndownService.turndown(th.innerHTML.trim())).join(' | ') + ' |\n'
  1378. + '| ' + Array.from(ths).map(() => ' --- ').join('|') + ' |\n';
  1379. }
  1380. }
  1381. var rows = node.querySelectorAll('tr');
  1382. Array.from(rows).forEach(function (row, i) {
  1383. if (i > 0) {
  1384. var cells = row.querySelectorAll('td,th');
  1385. var trow = '| ' + Array.from(cells).map(cell => turndownService.turndown(cell.innerHTML.trim())).join(' | ') + ' |';
  1386. output.push(trow);
  1387. }
  1388. });
  1389. return thead + output.join('\n');
  1390. } else {
  1391. return content;
  1392. }
  1393. }
  1394. });
  1395.  
  1396. // 题目markdown转换/翻译面板
  1397. function addButtonPanel(parent, suffix, type, is_simple = false) {
  1398. let htmlString = `<div class='html2md-panel'>
  1399. <button class='html2mdButton html2md-view${suffix}'>MarkDown视图</button>
  1400. <button class='html2mdButton html2md-cb${suffix}'>Copy</button>
  1401. <button class='html2mdButton translateButton${suffix}'>翻译</button>
  1402. </div>`;
  1403. if (type === "upper_level_2" || type === "problem") {
  1404. $(parent).children(':eq(1)').before(htmlString);
  1405. } else if (type === "child_level") {
  1406. $(parent).prepend("<div></div>");
  1407. var newDiv = $(parent).find("div:first-child");
  1408. $(newDiv).before(htmlString);
  1409. } else {
  1410. $(parent).before(htmlString);
  1411. }
  1412. if (is_simple) {
  1413. $('.html2md-panel').find('.html2mdButton.html2md-view' + suffix + ', .html2mdButton.html2md-cb' + suffix).remove();
  1414. }
  1415. }
  1416. function addButtonWithHTML2MD(parent, suffix, type) {
  1417. if(is_oldLatex){
  1418. $(".html2md-view" + suffix).css({
  1419. "cursor": "not-allowed",
  1420. "background-color": "#ffffff",
  1421. "color": "#a8abb2",
  1422. "border": "1px solid #e4e7ed"
  1423. });
  1424. $(".html2md-view" + suffix).prop("disabled", true);
  1425. }
  1426. $(".html2md-view" + suffix).click(function () {
  1427. var target, removedChildren;
  1428. if (type === "problem") {
  1429. target = $(parent).children().next().next().get(0);
  1430. } else if (type === "problem_QA") {
  1431. target = $(this).parent().parent().get(0);
  1432. removedChildren = $(this).parent().parent().children().eq(0).detach();
  1433. } else if (type === "upper_level_2") {
  1434. target = parent;
  1435. removedChildren = $(parent).children().slice(0, 2).detach();
  1436. } else if (type === "child_level") {
  1437. target = parent;
  1438. removedChildren = $(parent).children(':first').detach();
  1439. } else {
  1440. target = parent;
  1441. }
  1442. if (target.viewmd) {
  1443. target.viewmd = false;
  1444. $(this).text("MarkDown视图");
  1445. $(this).removeClass("mdViewed");
  1446. $(target).html(target.original_html);
  1447. } else {
  1448. target.viewmd = true;
  1449. if (!target.original_html) {
  1450. target.original_html = $(target).html();
  1451. }
  1452. if (!target.markdown) {
  1453. target.markdown = turndownService.turndown($(target).html());
  1454. }
  1455. $(this).text("原始内容");
  1456. $(this).addClass("mdViewed");
  1457. $(target).html(`<span class="mdViewContent" oninput="$(this).parent().get(0).markdown=this.value;" style="width:auto; height:auto;">${target.markdown}</span>`);
  1458. }
  1459. // 恢复删除的元素
  1460. if (type === "problem_QA" || type === "upper_level_2" || type === "child_level") $(target).prepend(removedChildren);
  1461. });
  1462. }
  1463.  
  1464. function addButtonWithCopy(parent, suffix, type) {
  1465. if(is_oldLatex){
  1466. $(".html2md-cb" + suffix).css({
  1467. "cursor": "not-allowed",
  1468. "background-color": "#ffffff",
  1469. "color": "#a8abb2",
  1470. "border": "1px solid #e4e7ed"
  1471. });
  1472. $(".html2md-cb" + suffix).prop("disabled", true);
  1473. }
  1474. $(".html2md-cb" + suffix).click(function () {
  1475. var target, removedChildren;
  1476. if (type === "problem") {
  1477. target = $($(parent).children().next().next().get(0)).clone();
  1478. } else if (type === "problem_QA") {
  1479. target = $(this).parent().parent().eq(0).clone();
  1480. $(target).children(':first').remove();
  1481. } else if (type === "upper_level_2") {
  1482. target = $(parent).clone();
  1483. $(target).children(':first').remove(); // 删除前两个元素(标题和按钮面板)
  1484. $(target).children(':first').remove();
  1485. } else if (type === "child_level") {
  1486. target = $(parent).clone();
  1487. $(target).children(':first').remove();
  1488. }else {
  1489. target = $(parent).clone();
  1490. }
  1491. if (!target.markdown) {
  1492. target.markdown = turndownService.turndown($(target).html());
  1493. }
  1494. const textarea = document.createElement('textarea');
  1495. textarea.value = target.markdown;
  1496. document.body.appendChild(textarea);
  1497. textarea.select();
  1498. document.execCommand('copy');
  1499. document.body.removeChild(textarea);
  1500. $(this).addClass("copied");
  1501. $(this).text("Copied");
  1502. // 更新复制按钮文本
  1503. setTimeout(() => {
  1504. $(this).removeClass("copied");
  1505. $(this).text("Copy");
  1506. }, 2000);
  1507. $(target).remove();
  1508. });
  1509. }
  1510.  
  1511. function addButtonWithTranslation(parent, suffix, type) {
  1512. $(".translateButton" + suffix).click(async function () {
  1513. var target, removedChildren;
  1514. if (type === "problem") {
  1515. target = $($(parent).children().next().next().get(0)).clone();
  1516. } else if (type === "problem_QA") {
  1517. target = $(this).parent().parent().eq(0).clone();
  1518. $(target).children(':first').remove();
  1519. } else if (type === "upper_level_2") {
  1520. target = $(parent).clone();
  1521. $(target).children(':first').remove(); // 删除前两个元素(标题和按钮面板)
  1522. $(target).children(':first').remove();
  1523. } else if (type === "child_level") {
  1524. target = $(parent).clone();
  1525. $(target).children(':first').remove();
  1526. } else {
  1527. target = $(parent).clone();
  1528. }
  1529. if (is_oldLatex) {
  1530. target.markdown = $(target).html();
  1531. } else if (!target.markdown) {
  1532. target.markdown = turndownService.turndown($(target).html());
  1533. }
  1534. const textarea = document.createElement('textarea');
  1535. textarea.value = target.markdown;
  1536. // 翻译处理
  1537. $(this).removeClass("translated");
  1538. $(this).text("翻译中");
  1539. $(this).css("cursor", "not-allowed");
  1540. var element_node;
  1541. if (type === "problem") {
  1542. element_node = $(parent).children()[2]; // 题面特殊处理
  1543. } else if (type === "problem_QA") {
  1544. element_node = $(parent).children().last().get(0);
  1545. } else if (type === "child_level") {
  1546. $(parent).append("<div></div>");
  1547. element_node = $(parent).find("div:last-child").get(0);
  1548. } else {
  1549. element_node = parent;
  1550. }
  1551. var translateDiv = await translateProblemStatement(textarea.value, element_node);
  1552. //
  1553. $(this).addClass("translated");
  1554. $(this).text("已翻译");
  1555. $(this).prop("disabled", true);
  1556. $(target).remove();
  1557. // 重新翻译
  1558. if ($(this).next('.reTranslation').length === 0) {
  1559. const reTranslateBtn = $('<button>').addClass('html2mdButton reTranslation').html('&circlearrowright;').attr('title', '重新翻译');
  1560. reTranslateBtn.on('click', function() {
  1561. $(translateDiv).remove();
  1562. x_api2d_no_cache ? (x_api2d_no_cache = false, $(this).prev().click(), x_api2d_no_cache = true) : $(this).prev().click();
  1563. });
  1564. $(this).after(reTranslateBtn);
  1565. } else {
  1566. const reTranslateBtn = $(this).next('.reTranslation');
  1567. reTranslateBtn.off('click').on('click', function() {
  1568. $(translateDiv).remove();
  1569. x_api2d_no_cache ? (x_api2d_no_cache = false, $(this).prev().click(), x_api2d_no_cache = true) : $(this).prev().click();
  1570. });
  1571. }
  1572. });
  1573. }
  1574.  
  1575.  
  1576. function addConversionButton() {
  1577. // 添加按钮到题面部分
  1578. $("div[class='problem-statement']").each(function () {
  1579. var problem_id = "_comment_" + getRandomNumber(8);
  1580. addButtonPanel(this, problem_id, "problem");
  1581. addButtonWithHTML2MD(this, problem_id, "problem");
  1582. addButtonWithCopy(this, problem_id, "problem");
  1583. addButtonWithTranslation(this, problem_id, "problem");
  1584. });
  1585.  
  1586. // 添加按钮到input部分
  1587. $("div[class='input-specification']").each(function () {
  1588. var id = "_" + getRandomNumber(8);
  1589. addButtonPanel(this, id, "upper_level_2");
  1590. addButtonWithHTML2MD(this, id, "upper_level_2");
  1591. addButtonWithCopy(this, id, "upper_level_2");
  1592. addButtonWithTranslation(this, id, "upper_level_2");
  1593. });
  1594.  
  1595. // 添加按钮到output部分
  1596. $("div[class='output-specification']").each(function () {
  1597. var id = "_" + getRandomNumber(8);
  1598. addButtonPanel(this, id, "upper_level_2");
  1599. addButtonWithHTML2MD(this, id, "upper_level_2");
  1600. addButtonWithCopy(this, id, "upper_level_2");
  1601. addButtonWithTranslation(this, id, "upper_level_2");
  1602. });
  1603.  
  1604. // 添加按钮到note部分
  1605. $("div[class='note']").each(function () {
  1606. var id = "_" + getRandomNumber(8);
  1607. addButtonPanel(this, id, "upper_level_2");
  1608. addButtonWithHTML2MD(this, id, "upper_level_2");
  1609. addButtonWithCopy(this, id, "upper_level_2");
  1610. addButtonWithTranslation(this, id, "upper_level_2");
  1611. });
  1612.  
  1613. // 添加按钮到ttypography部分
  1614. $(".ttypography").each(function () {
  1615. // 题目页特判
  1616. if (!$(this).parent().hasClass('problemindexholder')) {
  1617. var comment_id = "_comment_" + getRandomNumber(8);
  1618. addButtonPanel(this, comment_id, "this_level");
  1619. addButtonWithHTML2MD(this, comment_id, "this_level");
  1620. addButtonWithCopy(this, comment_id, "this_level");
  1621. addButtonWithTranslation(this, comment_id, "this_level");
  1622. }
  1623. });
  1624. // 题解页特判
  1625. if($('.content').find('.spoiler-content').length > 0) {
  1626. $('.content').find('.html2md-panel:first-child').remove();
  1627. }
  1628.  
  1629. // 添加按钮到spoiler部分
  1630. $('.spoiler-content').each(function() {
  1631. if ($(this).find('.html2md-panel').length === 0) {
  1632. var spoiler_id = "_titled_" + getRandomNumber(8);
  1633. addButtonPanel(this, spoiler_id, "child_level");
  1634. addButtonWithHTML2MD(this, spoiler_id, "child_level");
  1635. addButtonWithCopy(this, spoiler_id, "child_level");
  1636. addButtonWithTranslation(this, spoiler_id, "child_level");
  1637. }
  1638. });
  1639.  
  1640. // 添加按钮到titled部分
  1641. (function () {
  1642. var elements = [".Virtual.participation", ".Attention", ".Practice"];//只为部分titled添加
  1643. $.each(elements, function (index, value) {
  1644. $(value).each(function () {
  1645. var titled_id = "_titled_" + getRandomNumber(8);
  1646. var $nextDiv = $(this).next().get(0);
  1647. addButtonPanel($nextDiv, titled_id, "this_level", true);
  1648. addButtonWithTranslation($nextDiv, titled_id, "this_level");
  1649. });
  1650. });
  1651. })();
  1652. if (is_mSite) {
  1653. $("div[class='_IndexPage_notice']").each(function () {
  1654. var titled_id = "_titled_" + getRandomNumber(8);
  1655. addButtonPanel(this, titled_id, "child_level", true);
  1656. addButtonWithTranslation(this, titled_id, "child_level");
  1657. });
  1658. }
  1659.  
  1660. // 添加按钮到比赛QA部分
  1661. $(".question-requestText-td").each(function () {
  1662. var $nextDiv = $(this).children().get(0);
  1663. var question_id = "_question_" + getRandomNumber(8);
  1664. addButtonPanel($nextDiv, question_id, "problem_QA", true);
  1665. addButtonWithTranslation(this, question_id, "problem_QA");
  1666. });
  1667. if (is_mSite) {
  1668. $("div._ProblemsPage_announcements table tbody tr:gt(0)").each(function() {
  1669. var $nextDiv = $(this).find("td:first");
  1670. var question_id = "_question_" + getRandomNumber(8);
  1671. addButtonPanel($nextDiv, question_id, "child_level", true);
  1672. addButtonWithTranslation($nextDiv, question_id, "child_level");
  1673. });
  1674. }
  1675. };
  1676.  
  1677. /* alert弹窗汉化
  1678. function alertZh() {
  1679. var _alert = window.alert;
  1680. window.alert = async function(msg){
  1681. _alert(msg+"\n=========翻译=========\n"+await translate_deepl(msg));
  1682. return true;
  1683. }
  1684. };
  1685. */
  1686.  
  1687. // 展开折叠块
  1688. function ExpandFoldingblocks() {
  1689. if(expandFoldingblocks){
  1690. $('.spoiler').addClass('spoiler-open');
  1691. $('.spoiler-content').attr('style', '');
  1692. }
  1693. };
  1694.  
  1695. // 等待Latex渲染队列全部完成
  1696. function waitUntilIdleThenDo(callback) {
  1697. var intervalId = setInterval(function() {
  1698. var queue = MathJax.Hub.queue;
  1699. if (queue.pending === 0 && queue.running === 0) {
  1700. clearInterval(intervalId);
  1701. callback();
  1702. }
  1703. }, 100);
  1704. }
  1705.  
  1706. $(document).ready(function () {
  1707. var newElement = $("<div></div>").addClass("alert alert-info").html(`
  1708. Codeforces Better! —— 正在等待页面资源加载……
  1709. `).css({
  1710. "margin": "1em",
  1711. "text-align": "center",
  1712. "font-weight": "600",
  1713. "position": "relative"
  1714. });
  1715. $(".menu-box:first").next().after(newElement);
  1716. // 页面完全加载完成后执行
  1717. window.onload = function() {
  1718. newElement.html('Codeforces Better! —— 正在等待Latex渲染队列全部完成……');
  1719. waitUntilIdleThenDo(function() {
  1720. newElement.html('Codeforces Better! —— 加载已完成');
  1721. newElement.removeClass('alert-warning').addClass('alert-success');
  1722. setTimeout(function(){
  1723. newElement.remove();
  1724. }, 3000);
  1725. ExpandFoldingblocks();
  1726. addConversionButton();
  1727. });
  1728. }
  1729. })
  1730.  
  1731. // 翻译框/翻译处理器
  1732. var translatedText = "";
  1733. async function translateProblemStatement(text, element_node) {
  1734. let id = Math.floor(Date.now() / 1000);
  1735. let matches = [];
  1736. let replacements = {};
  1737. // 创建元素并放在element_node的后面
  1738. const translateDiv = document.createElement('div');
  1739. translateDiv.setAttribute('id', id);
  1740. translateDiv.classList.add('translate-problem-statement');
  1741. const spanElement = document.createElement('span');
  1742. translateDiv.appendChild(spanElement);
  1743. element_node.insertAdjacentElement('afterend', translateDiv);
  1744. // 替换latex公式
  1745. if (is_oldLatex) {
  1746. //去除开头结尾的<p>标签
  1747. text = text.replace(/^<p>/i, "");
  1748. text = text.replace(/<\/p>$/i, "");
  1749. //
  1750. let i = 0;
  1751. let regex = /<span\s+class="tex-span">.*?<\/span>/gi;
  1752. matches = text.match(regex);
  1753. try {
  1754. for (i; i < matches.length; i++) {
  1755. let match = matches[i];
  1756. text = text.replace(match, `【${i + 1}】`);
  1757. replacements[`【${i + 1}】`] = match;
  1758. }
  1759. } catch (e) { }
  1760. } else if (translation != "api2d" && translation != "openai") {
  1761. // 使用GPT翻译时不必替换latex公式
  1762. let i = 0;
  1763. // 块公式
  1764. matches = matches.concat(text.match(/\$\$([\s\S]*?)\$\$/g));
  1765. try {
  1766. for (i; i < matches.length; i++) {
  1767. let match = matches[i];
  1768. text = text.replace(match, `【${i + 1}】`);
  1769. replacements[`【${i + 1}】`] = match;
  1770. }
  1771. } catch (e) { }
  1772. // 行内公式
  1773. matches = matches.concat(text.match(/\$(.*?)\$/g));
  1774. try {
  1775. for (i; i < matches.length; i++) {
  1776. let match = matches[i];
  1777. text = text.replace(match, `【${i + 1}】`);
  1778. replacements[`【${i + 1}】`] = match;
  1779. }
  1780. } catch (e) { }
  1781. }
  1782. // 翻译
  1783. if (translation == "deepl") {
  1784. translateDiv.textContent = "正在翻译中……请稍等";
  1785. translatedText = await translate_deepl(text);
  1786. } else if (translation == "youdao") {
  1787. translateDiv.textContent = "正在翻译中……请稍等";
  1788. translatedText = await translate_youdao_mobile(text);
  1789. } else if (translation == "baidu") {
  1790. var baidu_appid = GM_getValue("baidu_uid");
  1791. var baidu_key = GM_getValue("baidu_key");
  1792. } else if (translation == "openai") {
  1793. translateDiv.textContent = "正在翻译中……\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待";
  1794. translatedText = await translate_openai(text);
  1795. } else if (translation == "api2d") {
  1796. translateDiv.textContent = "正在翻译中……\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待";
  1797. translatedText = await translate_api2d(text);
  1798. }
  1799. if(/^翻译出错/.test(translatedText)){
  1800. translateDiv.classList.add("error_translate");
  1801. }
  1802. // 还原latex公式
  1803. if (is_oldLatex) {
  1804. translatedText = "<p>" + translatedText;
  1805. translatedText += "</p>";
  1806. try {
  1807. for (let i = 0; i < matches.length; i++) {
  1808. let match = matches[i];
  1809. let replacement = replacements[`【${i + 1}】`];
  1810. translatedText = translatedText.replace(`【${i + 1}】`, replacement);
  1811. }
  1812. } catch (e) { }
  1813. }
  1814. else if (translation != "api2d" && translation != "openai") {
  1815. try {
  1816. for (let i = 0; i < matches.length; i++) {
  1817. let match = matches[i];
  1818. let replacement = replacements[`【${i + 1}】`];
  1819. translatedText = translatedText.replace(`【${i + 1}】`, replacement);
  1820. }
  1821. } catch (e) { }
  1822. }
  1823. // 使符合mathjx的转换语法
  1824. translatedText = translatedText.replace(/(\$\$)/g, "");
  1825. translatedText = translatedText.replace(/(?<!\$)\$(?!\$)/g, "$$$$$");
  1826. // 更新
  1827. if (is_oldLatex) {
  1828. // oldlatex
  1829. translatedText = $.parseHTML(translatedText);
  1830. $(translateDiv).empty().append($(translatedText));
  1831. } else {
  1832. translateDiv.innerHTML = translatedText;
  1833. // 渲染MarkDown
  1834. var md = window.markdownit();
  1835. var html = md.render(translateDiv.innerText);
  1836. translateDiv.innerHTML = html;
  1837. // 渲染Latex
  1838. MathJax.Hub.Queue(["Typeset", MathJax.Hub, document.getElementById(id)]);
  1839. }
  1840. return translateDiv;
  1841. }
  1842.  
  1843. // ChatGPT
  1844. async function translate_openai(raw) {
  1845. var openai_key = GM_getValue("openai_key");
  1846. var openai_retext = "";
  1847. var data;
  1848. if (is_oldLatex) {
  1849. data = {
  1850. prompt: "(You:请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的【】、HTML标签本身以及其中的内容不翻译不变动,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw + ")",
  1851. max_tokens: 2048,
  1852. model: "text-davinci-003",
  1853. };
  1854. } else {
  1855. data = {
  1856. prompt: "(You:请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw + ")",
  1857. max_tokens: 2048,
  1858. model: "text-davinci-003",
  1859. };
  1860. };
  1861. return new Promise(function (resolve, reject) {
  1862. GM_xmlhttpRequest({
  1863. method: 'POST',
  1864. url: 'https://api.openai.com/v1/completions',
  1865. data: JSON.stringify(data),
  1866. headers: {
  1867. 'Content-Type': 'application/json',
  1868. 'Authorization': 'Bearer ' + GM_getValue("openai_key") + ''
  1869. },
  1870. responseType: 'json',
  1871. onload: function (res) {
  1872. if (res.status === 200) {
  1873. openai_retext = res.response.choices[0].text;
  1874. openai_retext = openai_retext.replace(/^\s+/, '');
  1875. resolve(openai_retext);
  1876. }
  1877. else {
  1878. resolve("翻译出错,请重试\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈\n\n报错信息:" + JSON.stringify(res.response, null, '\n'));
  1879. }
  1880. }
  1881. });
  1882. });
  1883. }
  1884.  
  1885. // api2d
  1886. async function translate_api2d(raw) {
  1887. var api2d_key = GM_getValue("api2d_key");
  1888. var api2d_retext = "";
  1889. var postData;
  1890. if (is_oldLatex) {
  1891. postData = JSON.stringify({
  1892. model: 'gpt-3.5-turbo',
  1893. messages: [{ role: 'user', content: '请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的【】、HTML标签本身以及其中的内容不翻译不变动,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n' + raw }],
  1894. });
  1895. } else {
  1896. postData = JSON.stringify({
  1897. model: 'gpt-3.5-turbo',
  1898. messages: [{ role: 'user', content: '请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n' + raw }],
  1899. });
  1900. }
  1901. const options = {
  1902. method: 'POST',
  1903. headers: {
  1904. 'Content-Type': 'application/json',
  1905. Authorization: 'Bearer ' + api2d_key,
  1906. ...(x_api2d_no_cache ? {} : {'x-api2d-no-cache': 1})
  1907. },
  1908. data: postData,
  1909. };
  1910.  
  1911. return new Promise(function (resolve, reject) {
  1912. GM_xmlhttpRequest({
  1913. method: options.method,
  1914. url: `https://openai.api2d.net/v1/chat/completions`,
  1915. headers: options.headers,
  1916. data: options.data,
  1917. responseType: 'json',
  1918. onload: function (response) {
  1919. if (!response.response.choices || response.response.choices.length < 1 || !response.response.choices[0].message) {
  1920. resolve("翻译出错,请重试\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈\n\n报错信息:" + JSON.stringify(response.response, null, '\n'));
  1921. } else {
  1922. api2d_retext = response.response.choices[0].message.content;
  1923. resolve(api2d_retext);
  1924. }
  1925. },
  1926. onerror: function (response) {
  1927. console.error(response.statusText);
  1928. reject(response.statusText);
  1929. },
  1930. });
  1931. });
  1932.  
  1933.  
  1934. }
  1935. //
  1936.  
  1937. //--有道翻译m--start
  1938. async function translate_youdao_mobile(raw) {
  1939. const options = {
  1940. method: "POST",
  1941. url: 'http://m.youdao.com/translate',
  1942. data: "inputtext=" + encodeURIComponent(raw) + "&type=AUTO",
  1943. anonymous: true,
  1944. headers: {
  1945. "Content-Type": "application/x-www-form-urlencoded",
  1946. 'Host': 'm.youdao.com',
  1947. 'Origin': 'http://m.youdao.com',
  1948. 'Referer': 'http://m.youdao.com/translate',
  1949. }
  1950. }
  1951. return await BaseTranslate('有道翻译mobile', raw, options, res => /id="translateResult">\s*?<li>([\s\S]*?)<\/li>\s*?<\/ul/.exec(res)[1])
  1952. }
  1953. //--有道翻译m--end
  1954.  
  1955. //--Deepl翻译--start
  1956. function getTimeStamp(iCount) {
  1957. const ts = Date.now();
  1958. if (iCount !== 0) {
  1959. iCount = iCount + 1;
  1960. return ts - (ts % iCount) + iCount;
  1961. } else {
  1962. return ts;
  1963. }
  1964. }
  1965.  
  1966. async function translate_deepl(raw) {
  1967. const id = (Math.floor(Math.random() * 99999) + 100000) * 1000;
  1968. const data = {
  1969. jsonrpc: '2.0',
  1970. method: 'LMT_handle_texts',
  1971. id,
  1972. params: {
  1973. splitting: 'newlines',
  1974. lang: {
  1975. source_lang_user_selected: 'auto',
  1976. target_lang: 'ZH',
  1977. },
  1978. texts: [{
  1979. text: raw,
  1980. requestAlternatives: 3
  1981. }],
  1982. timestamp: getTimeStamp(raw.split('i').length - 1)
  1983. }
  1984. }
  1985. let postData = JSON.stringify(data);
  1986. if ((id + 5) % 29 === 0 || (id + 3) % 13 === 0) {
  1987. postData = postData.replace('"method":"', '"method" : "');
  1988. } else {
  1989. postData = postData.replace('"method":"', '"method": "');
  1990. }
  1991. const options = {
  1992. method: 'POST',
  1993. url: 'https://www2.deepl.com/jsonrpc',
  1994. data: postData,
  1995. headers: {
  1996. 'Content-Type': 'application/json',
  1997. 'Host': 'www2.deepl.com',
  1998. 'Origin': 'https://www.deepl.com',
  1999. 'Referer': 'https://www.deepl.com/',
  2000. },
  2001. anonymous: true,
  2002. nocache: true,
  2003. }
  2004. return await BaseTranslate('Deepl翻译', raw, options, res => JSON.parse(res).result.texts[0].text)
  2005. }
  2006.  
  2007. //--Deepl翻译--end
  2008.  
  2009. //--异步请求包装工具--start
  2010. async function PromiseRetryWrap(task, options, ...values) {
  2011. const { RetryTimes, ErrProcesser } = options || {};
  2012. let retryTimes = RetryTimes || 5;
  2013. const usedErrProcesser = ErrProcesser || (err => { throw err });
  2014. if (!task) return;
  2015. while (true) {
  2016. try {
  2017. return await task(...values);
  2018. } catch (err) {
  2019. if (!--retryTimes) {
  2020. console.log(err);
  2021. return usedErrProcesser(err);
  2022. }
  2023. }
  2024. }
  2025. }
  2026.  
  2027. async function BaseTranslate(name, raw, options, processer) {
  2028. let errtext;
  2029. const toDo = async () => {
  2030. var tmp;
  2031. try {
  2032. const data = await Request(options);
  2033. tmp = data.responseText;
  2034. const result = await processer(tmp);
  2035. if (result) sessionStorage.setItem(name + '-' + raw, result);
  2036. return result
  2037. } catch (err) {
  2038. errtext = tmp;
  2039. throw {
  2040. responseText: tmp,
  2041. err: err
  2042. }
  2043. }
  2044. }
  2045. return await PromiseRetryWrap(toDo, { RetryTimes: 3, ErrProcesser: () => "翻译出错,请重试或更换翻译接口\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈\n\n报错信息:" + errtext })
  2046. }
  2047.  
  2048.  
  2049. function Request(options) {
  2050. return new Promise((reslove, reject) => GM_xmlhttpRequest({ ...options, onload: reslove, onerror: reject }))
  2051. }
  2052.  
  2053. //--异步请求包装工具--end
  2054.  
  2055. // 随机数生成
  2056. function getRandomNumber(numDigits) {
  2057. let min = Math.pow(10, numDigits - 1);
  2058. let max = Math.pow(10, numDigits) - 1;
  2059. return Math.floor(Math.random() * (max - min + 1)) + min;
  2060. }
  2061.  
  2062. // 旧配置迁移(临时,将在1.38版本后删除)
  2063. if(getCookie("translation")){GM_setValue("translation",getCookie("translation"));deleteCookie("translation");}
  2064. if(getCookie("baidu_uid")){GM_setValue("baidu_uid",getCookie("baidu_uid"));deleteCookie("baidu_uid");}
  2065. if(getCookie("baidu_key")){GM_setValue("baidu_key",getCookie("baidu_key"));deleteCookie("baidu_key");}
  2066. if(getCookie("openai_key")){GM_setValue("openai_key",getCookie("openai_key"));deleteCookie("openai_key");}
  2067. if(getCookie("api2d_key")){GM_setValue("api2d_key",getCookie("api2d_key"));deleteCookie("api2d_key");}
  2068. if(getCookie("bottomZh_CN")){GM_setValue("bottomZh_CN",getCookie("bottomZh_CN")==="true");deleteCookie("bottomZh_CN");}
  2069. function deleteCookie(name){document.cookie=name+"=; expires=Thu, 01 Jan 1970 00:00:01 GMT;";}
  2070. function getCookie(cname) {var name = cname + "=";var decodedCookie = decodeURIComponent(document.cookie);var ca = decodedCookie.split(';');for (var i = 0; i < ca.length; i++) {var c = ca[i];while (c.charAt(0) == ' ') {c = c.substring(1);}if (c.indexOf(name) == 0) {return c.substring(name.length, c.length);}}return "";}