Codeforces Better!

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

目前為 2023-06-03 提交的版本,檢視 最新版本

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