Codeforces Better!

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

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

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