Codeforces Better!

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

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

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