Codeforces Better!

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

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

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