Codeforces Better!

Codeforces界面汉化、题目翻译,markdown视图,一键复制题目,跳转到洛谷

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

  1. // ==UserScript==
  2. // @name Codeforces Better!
  3. // @namespace https://greasyfork.org/users/747162
  4. // @version 1.55
  5. // @description Codeforces界面汉化、题目翻译,markdown视图,一键复制题目,跳转到洛谷
  6. // @author 北极小狐
  7. // @match *://*.codeforces.com/*
  8. // @connect www2.deepl.com
  9. // @connect m.youdao.com
  10. // @connect translate.google.com
  11. // @connect openai.api2d.net
  12. // @connect api.openai.com
  13. // @connect www.luogu.com.cn
  14. // @connect greasyfork.org
  15. // @connect *
  16. // @grant GM_xmlhttpRequest
  17. // @grant GM_info
  18. // @grant GM_setValue
  19. // @grant GM_getValue
  20. // @grant GM_addStyle
  21. // @grant GM_cookie
  22. // @grant GM_setClipboard
  23. // @icon https://aowuucdn.oss-cn-beijing.aliyuncs.com/codeforces.png
  24. // @require https://cdn.staticfile.org/turndown/7.1.2/turndown.min.js
  25. // @require https://cdn.staticfile.org/markdown-it/13.0.1/markdown-it.min.js
  26. // @license MIT
  27. // @compatible Chrome
  28. // @compatible Firefox
  29. // @compatible Edge
  30. // ==/UserScript==
  31.  
  32. // 状态与初始化
  33. const getGMValue = (key, defaultValue) => {
  34. const value = GM_getValue(key);
  35. if (value === undefined || value === "") {
  36. GM_setValue(key, defaultValue);
  37. return defaultValue;
  38. }
  39. return value;
  40. };
  41. const is_mSite = window.location.hostname.startsWith('m');
  42. const is_acmsguru = window.location.href.includes("acmsguru");
  43. const is_oldLatex = $('.tex-span').length;
  44. const bottomZh_CN = getGMValue("bottomZh_CN", true);
  45. const showLoading = getGMValue("showLoading", true);
  46. const loaded = getGMValue("loaded", false);
  47. const translation = getGMValue("translation", "deepl");
  48. const expandFoldingblocks = getGMValue("expandFoldingblocks", true);
  49. const enableSegmentedTranslation = getGMValue("enableSegmentedTranslation", false);
  50. const showJumpToLuogu = getGMValue("showJumpToLuogu", true);
  51. const hoverTargetAreaDisplay = getGMValue("hoverTargetAreaDisplay", false);
  52. //openai
  53. const openai_model = getGMValue("openai_model", "gpt-3.5-turbo");
  54. var showOpneAiAdvanced = getGMValue("showOpneAiAdvanced", false);
  55. // api2d
  56. const api2d_model = getGMValue("api2d_model", "gpt-3.5-turbo");
  57. const api2d_request_entry = getGMValue("api2d_request_entry", "https://openai.api2d.net");
  58. var x_api2d_no_cache = getGMValue("x_api2d_no_cache", true);
  59.  
  60. // 常量
  61. 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>';
  62. 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; }`;
  63.  
  64. // 报错信息捕获
  65. /*let errorMessages = "";
  66. const defaultError = console.error.bind(console);
  67. console.error = (message) => {
  68. const error = new Error();
  69. const stack = error.stack.split("\n").slice(2).join("\n");
  70. const now = new Date().toLocaleString();
  71. errorMessages += "\n## " + message + "\n### time: " + now +"\n" + stack + "\n";
  72. defaultError(message);
  73. };
  74. window.onerror = (message, source, lineno, colno, error) => {
  75. const now = new Date().toLocaleString();
  76. errorMessages += "\n## " + message + "\n### time: " + now +"\n" + error.stack + "\n";
  77. defaultError(message);
  78. return true;
  79. };*/
  80.  
  81. // 样式
  82. GM_addStyle(`
  83. :root {
  84. --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";
  85. }
  86. span.mdViewContent {
  87. white-space: pre-wrap;
  88. }
  89. /*翻译区域提示*/
  90. .overlay {
  91. pointer-events: none;
  92. position: absolute;
  93. top: 0;
  94. left: 0;
  95. width: 100%;
  96. height: 100%;
  97. background: repeating-linear-gradient(135deg, #97e7cacc, #97e7cacc 30px, #e9fbf1cc 0px, #e9fbf1cc 55px);
  98. border-radius: 5px;
  99. display: flex;
  100. align-items: center;
  101. justify-content: center;
  102. color: #00695C;
  103. font-size: 16px;
  104. font-weight: bold;
  105. text-shadow: 0px 0px 2px #edfcf4;
  106. }
  107. /*翻译div*/
  108. .translate-problem-statement {
  109. justify-items: start;
  110. letter-spacing: 1.8px;
  111. color: #059669;
  112. background-color: #f9f9fa;
  113. border: 1px solid #10b981;
  114. border-radius: 0.3rem;
  115. padding: 5px;
  116. margin: 10px 0px;
  117. width: 100%;
  118. box-sizing: border-box;
  119. font-size: 13px;
  120. }
  121. .translate-problem-statement.error_translate {
  122. color: red;
  123. border-color: red;
  124. }
  125. .translate-problem-statement a {
  126. color: #10b981;
  127. font-weight: 600;
  128. background: 0 0;
  129. text-decoration: none;
  130. }
  131. .translate-problem-statement ol, .translate-problem-statement ul {
  132. display: grid;
  133. margin-inline-start: 0.8em;
  134. margin-block-start: 0em;
  135. margin: 0.5em 0 0 3em;
  136. }
  137. .translate-problem-statement li {
  138. display: list-item;
  139. height: auto;
  140. word-wrap: break-word;
  141. }
  142. .translate-problem-statement ol li {
  143. list-style-type: auto;
  144. }
  145. .translate-problem-statement ul li {
  146. list-style-type: disc;
  147. }
  148. .translate-problem-statement img {
  149. max-width: 100.0%;
  150. max-height: 100.0%;
  151. }
  152. .ttypography .translate-problem-statement .MathJax {
  153. color: #059669!important;
  154. }
  155. .translate-problem-statement span.math {
  156. margin: 0px 2.5px !important;
  157. }
  158. .translate-problem-statement a:hover {
  159. background-color: #800;
  160. color: #fff;
  161. text-decoration: none;
  162. }
  163. .html2md-panel {
  164. display: flex;
  165. justify-content: flex-end;
  166. }
  167. .html2md-panel a {
  168. text-decoration: none;
  169. }
  170. button.html2mdButton {
  171. display: flex;
  172. align-items: center;
  173. cursor: pointer;
  174. background-color: #ffffff;
  175. color: #606266;
  176. height: 22px;
  177. width: auto;
  178. font-size: 13px;
  179. border-radius: 0.3rem;
  180. padding: 1px 5px;
  181. margin: 5px;
  182. border: 1px solid #dcdfe6;
  183. }
  184. button.html2mdButton:hover {
  185. color: #409eff;
  186. border-color: #409eff;
  187. background-color: #f1f8ff;
  188. }
  189. button.html2mdButton.copied {
  190. background-color: #f0f9eb;
  191. color: #67c23e;
  192. border: 1px solid #b3e19d;
  193. }
  194. button.html2mdButton.mdViewed {
  195. background-color: #fdf6ec;
  196. color: #e6a23c;
  197. border: 1px solid #f3d19e;
  198. }
  199. button.html2mdButton.error {
  200. background-color: #fef0f0;
  201. color: #f56c6c;
  202. border: 1px solid #fab6b6;
  203. }
  204. button.translated {
  205. background-color: #f0f9eb;
  206. color: #67c23e;
  207. border: 1px solid #b3e19d;
  208. }
  209. button.html2mdButton.reTranslation {
  210. background-color: #f4f4f5;
  211. color: #909399;
  212. border: 1px solid #c8c9cc;
  213. }
  214. .translate-problem-statement table {
  215. border: 1px #ccc solid !important;
  216. margin: 1.5em 0 !important;
  217. color: #059669 !important;
  218. }
  219. .translate-problem-statement table thead th {
  220. border: 1px #ccc solid !important;
  221. color: #059669 !important;
  222. }
  223. .translate-problem-statement table td {
  224. border-right: 1px solid #ccc;
  225. border-top: 1px solid #ccc;
  226. padding: 0.7143em 0.5em;
  227. }
  228. .translate-problem-statement table th {
  229. padding: 0.7143em 0.5em;
  230. }
  231. .translate-problem-statement p:not(:first-child) {
  232. margin: 1.5em 0 0;
  233. }
  234. /*设置面板*/
  235. header .enter-or-register-box, header .languages {
  236. position: absolute;
  237. right: 170px;
  238. }
  239. button.html2mdButton.CFBetter_setting {
  240. float: right;
  241. height: 30px;
  242. background: #60a5fa;
  243. color: white;
  244. margin: 10px;
  245. border: 0px;
  246. }
  247.  
  248. button.html2mdButton.CFBetter_setting.open {
  249. background-color: #e6e6e6;
  250. color: #727378;
  251. cursor: not-allowed;
  252. }
  253.  
  254. #CFBetter_setting_menu {
  255. z-index: 9999;
  256. box-shadow: 0px 0px 0px 4px #ffffff;
  257. display: grid;
  258. position: fixed;
  259. top: 50%;
  260. left: 50%;
  261. width: 480px;
  262. max-height: 90vh;
  263. overflow-y: auto;
  264. transform: translate(-50%, -50%);
  265. border-radius: 6px;
  266. background-color: #edf1ff;
  267. border-collapse: collapse;
  268. border: 1px solid #ffffff;
  269. color: #697e91;
  270. font-family: var(--vp-font-family-base);
  271. padding: 10px 20px 20px 20px;
  272. }
  273. #CFBetter_setting_menu h3 {
  274. margin-top: 10px;
  275. }
  276. #CFBetter_setting_menu hr {
  277. border: none;
  278. height: 1px;
  279. background-color: #ccc;
  280. margin: 10px 0;
  281. }
  282. /*设置面板-关闭按钮*/
  283. #CFBetter_setting_menu .tool-box {
  284. position: absolute;
  285. display: flex;
  286. align-items: center;
  287. justify-content: center;
  288. width: 2.5rem;
  289. height: 2.5rem;
  290. top: 3px;
  291. right: 3px;
  292. }
  293.  
  294. #CFBetter_setting_menu .btn-close {
  295. display: flex;
  296. align-items: center;
  297. justify-content: center;
  298. text-align: center;
  299. padding: 10px !important;
  300. width: 1px;
  301. height: 1px !important;
  302. color: transparent;
  303. font-size: 0;
  304. cursor: pointer;
  305. background-color: #ff000080;
  306. border: none;
  307. border-radius: 10px;
  308. transition: .15s ease all;
  309. }
  310.  
  311. #CFBetter_setting_menu .btn-close:hover {
  312. width: 20px;
  313. height: 20px !important;
  314. font-size: 17px;
  315. color: #ffffff;
  316. background-color: #ff0000cc;
  317. box-shadow: 0 5px 5px 0 #00000026;
  318. }
  319.  
  320. #CFBetter_setting_menu .btn-close:active {
  321. width: .9rem;
  322. height: .9rem;
  323. font-size: 1px;
  324. color: #ffffffde;
  325. --shadow-btn-close: 0 3px 3px 0 #00000026;
  326. box-shadow: var(--shadow-btn-close);
  327. }
  328.  
  329. /*设置面板-checkbox*/
  330. #CFBetter_setting_menu input[type=checkbox]:focus {
  331. outline: 0px;
  332. }
  333.  
  334. #CFBetter_setting_menu input[type="checkbox"] {
  335. margin: 0px;
  336. appearance: none;
  337. -webkit-appearance: none;
  338. width: 40px;
  339. height: 20px !important;
  340. border: 1.5px solid #D7CCC8;
  341. padding: 0px !important;
  342. border-radius: 20px;
  343. background: #efebe978;
  344. position: relative;
  345. box-sizing: border-box;
  346. }
  347.  
  348. #CFBetter_setting_menu input[type="checkbox"]::before {
  349. content: "";
  350. width: 14px;
  351. height: 14px;
  352. background: #D7CCC8;
  353. border: 1.5px solid #BCAAA4;
  354. border-radius: 50%;
  355. position: absolute;
  356. top: 0;
  357. left: 0;
  358. transform: translate(2%, 2%);
  359. transition: all 0.3s ease-in-out;
  360. }
  361.  
  362. #CFBetter_setting_menu input[type="checkbox"]::after {
  363. 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");
  364. position: absolute;
  365. top: 0;
  366. left: 24px;
  367. }
  368.  
  369. #CFBetter_setting_menu input[type="checkbox"]:checked {
  370. border: 1.5px solid #C5CAE9;
  371. background: #E8EAF6;
  372. }
  373.  
  374. #CFBetter_setting_menu input[type="checkbox"]:checked::before {
  375. background: #C5CAE9;
  376. border: 1.5px solid #7986CB;
  377. transform: translate(122%, 2%);
  378. transition: all 0.3s ease-in-out;
  379. }
  380.  
  381. #CFBetter_setting_menu input[type="text"]:focus-visible{
  382. border-width: 0.2vh;
  383. border-style: solid;
  384. border-color: #8bb2d9;
  385. outline: -webkit-focus-ring-color auto 0px;
  386. }
  387.  
  388. #CFBetter_setting_menu input[type="checkbox"]:checked::after {
  389. 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");
  390. position: absolute;
  391. top: 1.5px;
  392. left: 4.5px;
  393. }
  394.  
  395. #CFBetter_setting_menu label {
  396. font-size: 16px;
  397. }
  398.  
  399. .CFBetter_setting_list {
  400. display: flex;
  401. align-items: center;
  402. padding: 10px;
  403. margin: 5px 0px;
  404. background-color: #ffffff;
  405. border-bottom: 1px solid #c9c6c696;
  406. border-radius: 8px;
  407. justify-content: space-between;
  408. }
  409.  
  410. /*设置面板-radio*/
  411. #CFBetter_setting_menu>label {
  412. display: flex;
  413. list-style-type: none;
  414. padding-inline-start: 0px;
  415. overflow-x: auto;
  416. max-width: 100%;
  417. margin: 0px;
  418. align-items: center;
  419. margin: 3px 0px;
  420. }
  421.  
  422. .CFBetter_setting_menu_label_text {
  423. display: flex;
  424. border: 1px dashed #00aeeccc;
  425. height: 20px;
  426. width: 100%;
  427. color: gray;
  428. font-weight: 300;
  429. font-size: 14px;
  430. letter-spacing: 2px;
  431. padding: 7px;
  432. align-items: center;
  433. }
  434.  
  435. input[type="radio"]:checked+.CFBetter_setting_menu_label_text {
  436. background: #41e49930;
  437. border: 1px solid green;
  438. color: green;
  439. font-weight: 500;
  440. }
  441.  
  442. #CFBetter_setting_menu>label input[type="radio"] {
  443. -webkit-appearance: none;
  444. appearance: none;
  445. list-style: none;
  446. padding: 0px !important;
  447. margin: 0px;
  448. }
  449.  
  450. #CFBetter_setting_menu input[type="text"] {
  451. display: block;
  452. height: 25px !important;
  453. width: 100%;
  454. background-color: #ffffff;
  455. color: #727378;
  456. font-size: 12px;
  457. border-radius: 0.3rem;
  458. padding: 1px 5px !important;
  459. box-sizing: border-box;
  460. margin: 5px 0px 5px 0px;
  461. border: 1px solid #00aeeccc;
  462. box-shadow: 0 0 1px #0000004d;
  463. }
  464.  
  465. .CFBetter_setting_menu_input {
  466. width: 100%;
  467. display: grid;
  468. margin-top: 5px;
  469. }
  470.  
  471. #CFBetter_setting_menu #save {
  472. cursor: pointer;
  473. display: inline-flex;
  474. padding: 0.5rem 1rem;
  475. background-color: #1aa06d;
  476. color: #ffffff;
  477. font-size: 1rem;
  478. line-height: 1.5rem;
  479. font-weight: 500;
  480. justify-content: center;
  481. width: 100%;
  482. border-radius: 0.375rem;
  483. border: none;
  484. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  485. }
  486. #CFBetter_setting_menu button#debug_button.debug_button {
  487. width: 18%;
  488. }
  489.  
  490. #CFBetter_setting_menu span.tip {
  491. color: #999;
  492. font-size: 12px;
  493. font-weight: 500;
  494. padding: 5px 0px;
  495. }
  496. /*设置面板-tip*/
  497. .help_tip {
  498. margin-right: auto;
  499. }
  500. span.input_label {
  501. font-size: 14px;
  502. }
  503. .help_tip .tip_text {
  504. display: none;
  505. position: absolute;
  506. color: #697e91;
  507. font-weight: 400;
  508. font-size: 14px;
  509. letter-spacing: 0px;
  510. background-color: #ffffff;
  511. padding: 10px;
  512. margin: 5px 0px;
  513. border-radius: 4px;
  514. border: 1px solid #e4e7ed;
  515. box-shadow: 0px 0px 12px rgba(0, 0, 0, .12);
  516. z-index: 999;
  517. }
  518. .help_tip .tip_text p {
  519. margin-bottom: 5px;
  520. }
  521. .help_tip .tip_text:before {
  522. content: "";
  523. position: absolute;
  524. top: -20px;
  525. right: -10px;
  526. bottom: -10px;
  527. left: -10px;
  528. z-index: -1;
  529. }
  530. .help-icon {
  531. display: flex;
  532. cursor: help;
  533. width: 15px;
  534. color: #b4b9d4;
  535. margin-left: 5px;
  536. }
  537. #CFBetter_setting_menu .CFBetter_setting_menu_label_text .help_tip .help-icon {
  538. color: #7fbeb2;
  539. }
  540. .help_tip .help-icon:hover + .tip_text, .help_tip .tip_text:hover {
  541. display: block;
  542. cursor: help;
  543. width: 250px;
  544. }
  545.  
  546. /*设置面板-展开*/
  547. #is_showOpneAiAdvanced{
  548. width: 100%;
  549. background-color: aliceblue;
  550. padding: 8px;
  551. box-sizing: border-box;
  552. border-radius: 10px;
  553. }
  554. /*确认弹窗*/
  555. .wordsExceeded {
  556. z-index: 9999;
  557. box-shadow: 0px 0px 5px 1px rgb(0 0 0 / 10%), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  558. display: grid;
  559. position: fixed;
  560. top: 50%;
  561. left: 50%;
  562. transform: translate(-50%, -50%);
  563. border-radius: 4px;
  564. background-color: #ffffff;
  565. border: 1px solid #e4e7ed;
  566. color: #697e91;
  567. font-family: var(--vp-font-family-base);
  568. padding: 10px 20px 20px 20px;
  569. }
  570. .wordsExceeded button {
  571. display: inline-flex;
  572. justify-content: center;
  573. align-items: center;
  574. line-height: 1;
  575. white-space: nowrap;
  576. cursor: pointer;
  577. text-align: center;
  578. box-sizing: border-box;
  579. outline: none;
  580. transition: .1s;
  581. user-select: none;
  582. vertical-align: middle;
  583. -webkit-appearance: none;
  584. height: 24px;
  585. padding: 5px 11px;
  586. font-size: 12px;
  587. border-radius: 4px;
  588. color: #ffffff;
  589. background: #409eff;
  590. border-color: #409eff;
  591. border: none;
  592. margin-right: 12px;
  593. }
  594. .wordsExceeded button:hover{
  595. background-color:#79bbff;
  596. }
  597. .wordsExceeded .help-icon {
  598. margin: 0px 8px 0px 0px;
  599. height: 1em;
  600. width: 1em;
  601. line-height: 1em;
  602. display: inline-flex;
  603. justify-content: center;
  604. align-items: center;
  605. position: relative;
  606. fill: currentColor;
  607. font-size: inherit;
  608. }
  609. .wordsExceeded p {
  610. margin: 5px 0px;
  611. }
  612. /*更新检查*/
  613. div#update_panel {
  614. z-index: 9999;
  615. position: fixed;
  616. top: 50%;
  617. left: 50%;
  618. width: 240px;
  619. transform: translate(-50%, -50%);
  620. box-shadow: 0px 0px 4px 0px #0000004d;
  621. padding: 10px 20px 20px 20px;
  622. color: #444242;
  623. background-color: #f5f5f5;
  624. border: 1px solid #848484;
  625. border-radius: 8px;
  626. }
  627. div#update_panel #updating {
  628. cursor: pointer;
  629. display: inline-flex;
  630. padding: 3px;
  631. background-color: #1aa06d;
  632. color: #ffffff;
  633. font-size: 1rem;
  634. line-height: 1.5rem;
  635. font-weight: 500;
  636. justify-content: center;
  637. width: 100%;
  638. border-radius: 0.375rem;
  639. border: none;
  640. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  641. }
  642. div#update_panel #updating a {
  643. text-decoration: none;
  644. color: white;
  645. display: flex;
  646. position: inherit;
  647. top: 0;
  648. left: 0;
  649. width: 100%;
  650. height: 22px;
  651. font-size: 14px;
  652. justify-content: center;
  653. align-items: center;
  654. }
  655. #skip_menu {
  656. display: flex;
  657. margin-top: 10px;
  658. justify-content: flex-end;
  659. align-items: center;
  660. }
  661. #skip_menu .help_tip {
  662. margin-right: 5px;
  663. margin-left: -5px;
  664. }
  665. #skip_menu .help-icon {
  666. color: #f44336;
  667. }
  668. `);
  669.  
  670. // 工具
  671. // 获取cookie
  672. function getCookie(name) {
  673. const cookies = document.cookie.split(";");
  674. for (let i = 0; i < cookies.length; i++) {
  675. const cookie = cookies[i].trim();
  676. const [cookieName, cookieValue] = cookie.split("=");
  677.  
  678. if (cookieName === name) {
  679. return decodeURIComponent(cookieValue);
  680. }
  681. }
  682. return "";
  683. }
  684.  
  685. // 防抖函数
  686. function debounce(callback) {
  687. let timer;
  688. let immediateExecuted = false;
  689. const delay = 500;
  690. return function () {
  691. clearTimeout(timer);
  692. if (!immediateExecuted) { callback.call(this); immediateExecuted = true; }
  693. timer = setTimeout(() => { immediateExecuted = false; }, delay);
  694. };
  695. }
  696.  
  697. // 更新检查
  698. (function checkScriptVersion() {
  699. function compareVersions(version1 = "0", version2 = "0") {
  700. const v1Array = String(version1).split(".");
  701. const v2Array = String(version2).split(".");
  702. const minLength = Math.min(v1Array.length, v2Array.length);
  703. let result = 0;
  704. for (let i = 0; i < minLength; i++) {
  705. const curV1 = Number(v1Array[i]);
  706. const curV2 = Number(v2Array[i]);
  707. if (curV1 > curV2) {
  708. result = 1;
  709. break;
  710. } else if (curV1 < curV2) {
  711. result = -1;
  712. break;
  713. }
  714. }
  715. if (result === 0 && v1Array.length !== v2Array.length) {
  716. const v1IsBigger = v1Array.length > v2Array.length;
  717. const maxLenArray = v1IsBigger ? v1Array : v2Array;
  718. for (let i = minLength; i < maxLenArray.length; i++) {
  719. const curVersion = Number(maxLenArray[i]);
  720. if (curVersion > 0) {
  721. v1IsBigger ? result = 1 : result = -1;
  722. break;
  723. }
  724. }
  725. }
  726. return result;
  727. }
  728.  
  729. GM_xmlhttpRequest({
  730. method: "GET",
  731. url: "https://greasyfork.org/zh-CN/scripts/465777.json",
  732. timeout: 10 * 1e3,
  733. onload: function (response) {
  734. const scriptData = JSON.parse(response.responseText);
  735. const skipUpdate = getCookie("skipUpdate");
  736.  
  737. if (
  738. scriptData.name === GM_info.script.name &&
  739. compareVersions(scriptData.version, GM_info.script.version) === 1 &&
  740. skipUpdate !== "true"
  741. ) {
  742. const styleElement = GM_addStyle(darkenPageStyle);
  743. $("body").append(`
  744. <div id='update_panel'>
  745. <h3>${GM_info.script.name}有新版本!</h3>
  746. <hr>
  747. <div class='update_panel_menu'>
  748. <span class ='tip'>版本信息:${GM_info.script.version} ${scriptData.version}</span>
  749. </div>
  750. <br>
  751. <div id="skip_menu">
  752. <div class="help_tip">
  753. `+ helpCircleHTML + `
  754. <div class="tip_text">
  755. <p><b>更新遇到了问题?</b></p>
  756. <p>由于 Greasyfork 平台的原因,当新版本刚发布时,点击 Greasyfork 上的更新按钮<u>可能</u>会出现<u>实际更新/安装的却是上一个版本</u>的情况</p>
  757. <p>通常你只需要稍等几分钟,然后再次前往更新/安装即可</p>
  758. <p>你也可以<u>点击下方按钮,在本次浏览器会话期间将不再提示更新</u></p>
  759. <button id='skip_update' class='html2mdButton'>暂不更新</button>
  760. </div>
  761. </div>
  762. <button id='updating'><a target="_blank" href="${scriptData.url}">更新</a></button>
  763. </div>
  764. </div>
  765. `);
  766.  
  767. $("#skip_update").click(function () {
  768. document.cookie = "skipUpdate=true; expires=session; path=/";
  769. styleElement.remove();
  770. $("#update_panel").remove();
  771. });
  772. }
  773. }
  774. });
  775.  
  776. })();
  777.  
  778. // 汉化替换
  779. (function () {
  780. if (!bottomZh_CN) return;
  781. // 设置语言为zh
  782. var htmlTag = document.getElementsByTagName("html")[0];
  783. htmlTag.setAttribute("lang", "zh-CN");
  784.  
  785. // 文本节点遍历替换
  786. $(document).ready(function () {
  787. function traverseTextNodes(node, rules) {
  788. if (!node) return;
  789. if (node.nodeType === Node.TEXT_NODE) {
  790. rules.forEach(rule => {
  791. const regex = new RegExp(rule.match, 'g');
  792. node.textContent = node.textContent.replace(regex, rule.replace);
  793. });
  794. } else {
  795. $(node).contents().each((_, child) => traverseTextNodes(child, rules));
  796. }
  797. }
  798.  
  799. const rules1 = [
  800. { match: 'Virtual participation', replace: '参加虚拟重现赛' },
  801. { match: 'Enter', replace: '进入' },
  802. { match: 'Current standings', replace: '当前榜单' },
  803. { match: 'Final standings', replace: '最终榜单' },
  804. { match: 'Preliminary results', replace: '初步结果' },
  805. { match: 'open hacking:', replace: '公开黑客攻击中(即尝试提交数据加强,对已通过的代码重测)' },
  806. { match: 'School/University/City/Region Championship', replace: '学校/大学/城市/区域比赛' },
  807. { match: 'Official School Contest', replace: '学校官方比赛' },
  808. { match: 'Training Contest', replace: '训练赛' },
  809. { match: 'Training Camp Contest', replace: '训练营比赛' },
  810. { match: 'Official ICPC Contest', replace: 'ICPC官方比赛' },
  811. { match: 'Official International Personal Contest', replace: '官方国际个人赛' },
  812. { match: 'China', replace: '中国' },
  813. { match: 'Statements', replace: '题目描述' },
  814. { match: 'in Chinese', replace: '中文' },
  815. { match: 'Trainings', replace: '训练' },
  816. { match: 'Prepared by', replace: '编写人' },
  817. { match: 'Current or upcoming contests', replace: '当前或即将举行的比赛' },
  818. { match: 'Past contests', replace: '过去的比赛' },
  819. { match: 'Exclusions', replace: '排除' },
  820. { match: 'Before start', replace: '距比赛开始还有' },
  821. { match: 'Before registration', replace: '距报名开始还有' },
  822. { match: 'Until closing ', replace: '距报名结束还有' },
  823. { match: 'Before extra registration', replace: '额外报名还未开始' },
  824. { match: 'Register', replace: '报名' },
  825. { match: 'Registration completed', replace: '已报名' },
  826. { match: 'Registration closed', replace: '报名已结束' },
  827. { match: 'Problems', replace: '问题集' },
  828. { match: 'Questions about problems', replace: '关于问题的提问' },
  829. { match: 'Contest status', replace: '比赛状态' },
  830. ];
  831. traverseTextNodes($('.datatable'), rules1);
  832.  
  833. const rules2 = [
  834. { match: 'Home', replace: '主页' },
  835. { match: 'Top', replace: '热门' },
  836. { match: 'Catalog', replace: '指南目录' },
  837. { match: 'Contests', replace: '比赛' },
  838. { match: 'Gym', replace: '训练营' },
  839. { match: 'Problemset', replace: '题单' },
  840. { match: 'Groups', replace: '团体' },
  841. { match: 'Rating', replace: 'Rating(评级)排行榜' },
  842. { match: 'Edu', replace: '培训' },
  843. { match: 'Calendar', replace: '日历' },
  844. { match: 'Help', replace: '帮助' }
  845. ];
  846. traverseTextNodes($('.menu-list.main-menu-list'), rules2);
  847.  
  848. const rules3 = [
  849. { match: 'Settings', replace: '设置' },
  850. { match: 'Blog', replace: '博客' },
  851. { match: 'Teams', replace: '队伍' },
  852. { match: 'Submissions', replace: '提交' },
  853. { match: 'Favourites', replace: '收藏' },
  854. { match: 'Talks', replace: '私信' },
  855. { match: 'Contests', replace: '比赛' },
  856. ];
  857. traverseTextNodes($('.nav-links'), rules3);
  858.  
  859. const rules4 = [
  860. { match: 'Before contest', replace: '即将进行的比赛' },
  861. { match: 'Contest is running', replace: '比赛进行中' },
  862. ];
  863. traverseTextNodes($('.contest-state-phase'), rules4);
  864.  
  865. const rules5 = [
  866. { match: 'has extra registration', replace: '有额外的报名时期' },
  867. { 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分钟。' },
  868. ];
  869. traverseTextNodes($('.notice'), rules5);
  870.  
  871. const rules6 = [
  872. { match: 'Contribution', replace: '贡献' },
  873. ];
  874. traverseTextNodes($('.propertyLinks'), rules6);
  875.  
  876. const rules7 = [
  877. { match: 'Contest history', replace: '比赛历史' },
  878. ];
  879. traverseTextNodes($('.contests-table'), rules7);
  880.  
  881. const rules8 = [
  882. { match: 'Register now', replace: '现在报名' },
  883. { match: 'No tag edit access', replace: '没有标签编辑权限' },
  884. { match: 'Language:', replace: '语言:' },
  885. { match: 'Choose file:', replace: '选择文件:' },
  886. ];
  887. traverseTextNodes($('.roundbox.sidebox.borderTopRound '), rules8);
  888.  
  889. const rules9 = [
  890. { match: 'Add to exclusions', replace: '添加到排除列表' },
  891. ];
  892. traverseTextNodes($('.icon-eye-close.icon-large'), rules9);
  893.  
  894. const rules10 = [
  895. { match: 'Add to exclusions for gym contests filter', replace: '添加训练营过滤器的排除项' },
  896. ];
  897. traverseTextNodes($("._ContestFilterExclusionsManageFrame_addExclusionLink"), rules10);
  898.  
  899. const rules11 = [
  900. { match: 'Announcement', replace: '公告' },
  901. { match: 'Statements', replace: '统计报表' },
  902. { match: 'Tutorial', replace: '题解' },
  903. ];
  904. traverseTextNodes($('.roundbox.sidebox.sidebar-menu.borderTopRound '), rules11);
  905.  
  906. const rules12 = [
  907. { match: 'Problems', replace: '问题' },
  908. { match: 'Submit Code', replace: '提交代码' },
  909. { match: 'My Submissions', replace: '我的提交' },
  910. { match: 'Status', replace: '状态' },
  911. { match: 'Standings', replace: '榜单' },
  912. { match: 'Custom Invocation', replace: '自定义调试' },
  913. { match: 'Common standings', replace: '全部排行' },
  914. { match: 'Friends standings', replace: '只看朋友' },
  915. { match: 'Submit', replace: '提交' },
  916. { match: 'Hacks', replace: '黑客' },
  917. { match: 'Room', replace: '房间' },
  918. { match: 'Custom test', replace: '自定义测试' },
  919. { match: 'Blog', replace: '博客' },
  920. { match: 'Teams', replace: '队伍' },
  921. { match: 'Submissions', replace: '提交记录' },
  922. { match: 'Groups', replace: '团体' },
  923. { match: 'Favourites', replace: '收藏' },
  924. { match: 'Contests', replace: '比赛' },
  925. { match: 'Members', replace: '成员' },
  926. { match: '问题etting', replace: '参与编写的问题' },
  927. { match: 'Streams', replace: '直播' },
  928. { match: 'Gym', replace: '训练营' },
  929. { match: 'Mashups', replace: '组合混搭' },
  930. { match: 'Posts', replace: '帖子' },
  931. { match: 'Comments', replace: '回复' },
  932. { match: 'Main', replace: '主要的' },
  933. { match: 'Settings', replace: '设置' },
  934. { match: 'Lists', replace: '列表' },
  935. { match: 'General', replace: '基本' },
  936. { match: 'Sidebar', replace: '侧边栏' },
  937. { match: 'Social', replace: '社会信息' },
  938. { match: 'Address', replace: '地址' },
  939. { match: 'Wallets', replace: '钱包' },
  940. ];
  941. traverseTextNodes($('.second-level-menu'), rules12);
  942. if (is_mSite) {
  943. traverseTextNodes($('nav'), rules12);
  944. }
  945.  
  946. const rules13 = [
  947. { match: 'Expand', replace: '展开' }
  948. ];
  949. traverseTextNodes($('.topic-toggle-collapse'), rules13);
  950.  
  951. const rules14 = [
  952. { match: 'Full text and comments', replace: '阅读全文/评论' }
  953. ];
  954. traverseTextNodes($('.topic-read-more'), rules14);
  955.  
  956. const rules15 = [
  957. { match: 'Switch off editor', replace: '关闭编辑器语法高亮' }
  958. ];
  959. traverseTextNodes($('.toggleEditorCheckboxLabel'), rules15);
  960.  
  961. const rules16 = [
  962. { match: 'Registration for the contest', replace: '比赛报名' }
  963. ];
  964. traverseTextNodes($('.submit'), rules16);
  965.  
  966. const rules17 = [
  967. { match: 'Difficulty:', replace: '难度:' },
  968. ];
  969. traverseTextNodes($('._FilterByTagsFrame_difficulty'), rules17);
  970.  
  971. const rules18 = [
  972. { match: 'Add tag', replace: '添加标签' }
  973. ];
  974. traverseTextNodes($('._FilterByTagsFrame_addTagLink'), rules18);
  975.  
  976. const rules19 = [
  977. { match: 'Rating changes for last rounds are temporarily rolled back. They will be returned soon.', replace: '上一轮的评级变化暂时回滚。它们将很快恢复。' },
  978. { match: 'Reminder: in case of any technical issues, you can use the lightweight website', replace: '提醒:如果出现任何技术问题,您可以使用轻量网站' },
  979. { match: 'Please subscribe to the official Codeforces channel in Telegram via the link ', replace: '请通过链接订阅Codeforces的官方Telegram频道' }
  980. ];
  981. traverseTextNodes($('.alert'), rules19);
  982.  
  983. const rules20 = [
  984. { match: 'Enter', replace: '登录' },
  985. { match: 'Register', replace: '注册' },
  986. { match: 'Contest rating', replace: '测试 rating' },
  987. { match: 'Logout', replace: '退出登录' }
  988. ];
  989. traverseTextNodes($('.lang-chooser'), rules20);
  990.  
  991. const rules21 = [
  992. { match: 'Change photo', replace: '更换图片' },
  993. { match: 'Contest rating', replace: '比赛Rating' },
  994. { match: 'Contribution', replace: '贡献' },
  995. { match: 'My friends', replace: '我的好友' },
  996. { match: 'Change settings', replace: '改变设置' },
  997. { match: 'Last visit', replace: '最后访问' },
  998. { match: 'Registered', replace: '注册于' },
  999. { match: 'Blog entries', replace: '博客条目' },
  1000. { match: 'comments', replace: '评论' },
  1001. { match: 'Write new entry', replace: '编写新条目' },
  1002. { match: 'View my talks', replace: '查看我的私信' },
  1003. { match: 'Talks', replace: '私信' },
  1004. { match: 'Send message', replace: '发送消息' },
  1005. ];
  1006. traverseTextNodes($('.userbox'), rules21);
  1007.  
  1008. const rules22 = [
  1009. { match: 'Reset', replace: '重置' },
  1010. ];
  1011. traverseTextNodes($('#vote-reset-filterDifficultyLowerBorder'), rules22);
  1012. traverseTextNodes($('#vote-reset-filterDifficultyUpperBorder'), rules22);
  1013.  
  1014. const rules23 = [
  1015. { match: 'The problem statement has recently been changed.', replace: '题目描述最近已被更改。\n(说明:如果是进入该页面后立即显示的,这通常是Codeforces Better!插入翻译按钮导致的)' },
  1016. { match: 'View the changes.', replace: '查看更改' },
  1017. ];
  1018. traverseTextNodes($('.alert.alert-info'), rules23);
  1019.  
  1020. const rules24 = [
  1021. { match: 'Fill in the form to login into Codeforces.', replace: '填写表单以登录到Codeforces。' },
  1022. { match: 'You can use', replace: '你也可以使用' },
  1023. { match: 'as an alternative way to enter.', replace: '登录' },
  1024. ];
  1025. traverseTextNodes($('.enterPage'), rules24);
  1026.  
  1027. const rules25 = [
  1028. { match: '\\* To view the complete list, click ', replace: '* 要查看完整列表,请点击' },
  1029. ];
  1030. traverseTextNodes($('.notice.small'), rules25);
  1031.  
  1032. const rules26 = [
  1033. { match: 'Contest type:', replace: '比赛类型:' },
  1034. { match: 'Rated:', replace: '已评级:' },
  1035. { match: 'Tried:', replace: '已尝试' },
  1036. { match: 'Substring:', replace: '关键字' },
  1037. ];
  1038. traverseTextNodes($('.setting-name'), rules26);
  1039.  
  1040. });
  1041. // 元素选择替换
  1042. // 侧栏titled汉化
  1043. (function () {
  1044. var translations = {
  1045. "Pay attention": "→ 注意",
  1046. "Top rated": "→ 评级排行",
  1047. "Top contributors": "→ 贡献者排行",
  1048. "Find user": "→ 查找用户",
  1049. "Recent actions": "→ 最新动态",
  1050. "Training filter": "→ 过滤筛选",
  1051. "Find training": "→ 搜索比赛/问题",
  1052. "Virtual participation": "→ 什么是虚拟参赛",
  1053. "Contest materials": "→ 比赛相关资料",
  1054. "Settings": "→ 设置",
  1055. "Create Mashup Contest": "→ 克隆比赛到组合混搭",
  1056. "Clone Contest to Mashup": "→ 克隆比赛到组合混搭",
  1057. "Create Mashup Contest": "→ 创建混搭比赛",
  1058. "Submit": "→ 提交",
  1059. "Practice": "→ 练习",
  1060. "Problem tags": "→ 问题标签",
  1061. "Filter Problems": "→ 过滤问题",
  1062. "Attention": "→ 注意",
  1063. "Past contests filter": "→ 过去的比赛筛选",
  1064. "About Contest": "→ 关于比赛",
  1065. "Last submissions": "→ 提交历史",
  1066. "Streams": "→ 直播",
  1067. "Coach rights": "→ 教练权限",
  1068. "Advices to fill address": "→ 填写地址的建议",
  1069. "Hacks filter": "→ 黑客过滤器",
  1070. "Score table": "→ 评分表",
  1071. "Contests": "→ 比赛",
  1072. "History": "→ 编辑历史",
  1073. "Login into Codeforces": "登录 Codeforces",
  1074. };
  1075.  
  1076. $(".caption.titled").each(function () {
  1077. var tag = $(this).text();
  1078. for (var property in translations) {
  1079. if (tag.match(property)) {
  1080. $(this).addClass(property);
  1081. $(this).text(translations[property]);
  1082. break;
  1083. }
  1084. }
  1085. });
  1086. })();
  1087. // 题目Tag汉化
  1088. (function () {
  1089. var parentElement = $('._FilterByTagsFrame_addTagLabel');
  1090. var selectElement = parentElement.find('select');
  1091. var translations = {
  1092. "*combine tags by OR": "*按逻辑或组合我选择的标签",
  1093. "combine-tags-by-or": "*按逻辑或组合我选择的标签(combine-tags-by-or)",
  1094. "2-sat": "二分图可满足性问题(2-sat)",
  1095. "binary search": "二分搜索(binary search)",
  1096. "bitmasks": "位掩码(bitmasks)",
  1097. "brute force": "暴力枚举(brute force)",
  1098. "chinese remainder theorem": "中国剩余定理(chinese remainder theorem)",
  1099. "combinatorics": "组合数学(combinatorics)",
  1100. "constructive algorithms": "构造算法(constructive algorithms)",
  1101. "data structures": "数据结构(data structures)",
  1102. "dfs and similar": "深度优先搜索及其变种(dfs and similar)",
  1103. "divide and conquer": "分治算法(divide and conquer)",
  1104. "dp": "动态规划(dp)",
  1105. "dsu": "并查集(dsu)",
  1106. "expression parsing": "表达式解析(expression parsing)",
  1107. "fft": "快速傅里叶变换(fft)",
  1108. "flows": "流(flows)",
  1109. "games": "博弈论(games)",
  1110. "geometry": "计算几何(geometry)",
  1111. "graph matchings": "图匹配(graph matchings)",
  1112. "graphs": "图论(graphs)",
  1113. "greedy": "贪心策略(greedy)",
  1114. "hashing": "哈希表(hashing)",
  1115. "implementation": "实现问题,编程技巧,模拟(implementation)",
  1116. "interactive": "交互性问题(interactive)",
  1117. "math": "数学(math)",
  1118. "matrices": "矩阵(matrices)",
  1119. "meet-in-the-middle": "meet-in-the-middle算法(meet-in-the-middle)",
  1120. "number theory": "数论(number theory)",
  1121. "probabilities": "概率论(probabilities)",
  1122. "schedules": "调度算法(schedules)",
  1123. "shortest paths": "最短路算法(shortest paths)",
  1124. "sortings": "排序算法(sortings)",
  1125. "string suffix structures": "字符串后缀结构(string suffix structures)",
  1126. "strings": "字符串处理(strings)",
  1127. "ternary search": "三分搜索(ternary search)",
  1128. "trees": "树形结构(trees)",
  1129. "two pointers": "双指针算法(two pointers)"
  1130. };
  1131. selectElement.find("option").each(function () {
  1132. var optionValue = $(this).val();
  1133. if (translations[optionValue]) {
  1134. $(this).text(translations[optionValue]);
  1135. }
  1136. });
  1137. $("._FilterByTagsFrame_tagBoxCaption").each(function () {
  1138. var tag = $(this).text();
  1139. if (tag in translations) {
  1140. $(this).text(translations[tag]);
  1141. }
  1142. });
  1143. $(".notice").each(function () {
  1144. var tag = $(this).text();
  1145. if (tag in translations) {
  1146. $(this).text(translations[tag]);
  1147. }
  1148. });
  1149. $(".tag-box").each(function () {
  1150. var tag = $(this).text();
  1151. for (var property in translations) {
  1152. property = property.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
  1153. if (tag.match(property)) {
  1154. $(this).text(translations[property]);
  1155. break;
  1156. }
  1157. }
  1158. });
  1159. })();
  1160. // 题目过滤器选项汉化
  1161. (function () {
  1162. var parentElement = $('#gym-filter-form');
  1163. var selectElement = parentElement.find('div');
  1164. var translations = {
  1165. "Contest type:": "比赛类型:",
  1166. "ICPC region:": "ICPC地区:",
  1167. "Contest format:": "比赛形式:",
  1168. "Order by:": "排序方式:",
  1169. "Secondary order by:": "次要排序方式:",
  1170. "Hide, if participated:": "隐藏我参加过的:",
  1171. };
  1172. selectElement.find("label").each(function () {
  1173. var optionValue = $(this).text();
  1174. if (translations[optionValue]) {
  1175. $(this).text(translations[optionValue]);
  1176. }
  1177. });
  1178. translations = {
  1179. "Season:": "时间范围(年度)",
  1180. "Duration, hours:": "持续时间(小时):",
  1181. "Difficulty:": "难度:"
  1182. };
  1183. selectElement.each(function () {
  1184. var optionValue = $(this).text();
  1185. if (translations[optionValue]) {
  1186. $(this).text(translations[optionValue]);
  1187. }
  1188. });
  1189. })();
  1190. (function () {
  1191. var parentElement = $('.setting-value');
  1192. var selectElement = parentElement.find('select');
  1193. var translations = {
  1194. "Official ACM-ICPC Contest": "ICPC官方比赛",
  1195. "Official School Contest": "学校官方比赛",
  1196. "Opencup Contest": "Opencup比赛",
  1197. "School/University/City/Region Championship": "学校/大学/城市/地区锦标赛",
  1198. "Training Camp Contest": "训练营比赛",
  1199. "Official International Personal Contest": "官方国际个人赛",
  1200. "Training Contest": "训练比赛",
  1201. "ID_ASC": "创建时间(升序)",
  1202. "ID_DESC": "创建时间(降序)",
  1203. "RATING_ASC": "评分(升序)",
  1204. "RATING_DESC": "评分(降序)",
  1205. "DIFFICULTY_ASC": "难度(升序)",
  1206. "DIFFICULTY_DESC": "难度(降序)",
  1207. "START_TIME_ASC": "开始时间(升序)",
  1208. "START_TIME_DESC": "开始时间(降序)",
  1209. "DURATION_ASC": "持续时间(升序)",
  1210. "DURATION_DESC": "持续时间(降序)",
  1211. "POPULARITY_ASC": "热度(升序)",
  1212. "POPULARITY_DESC": "热度(降序)",
  1213. "UPDATE_TIME_ASC": "更新时间(升序)",
  1214. "UPDATE_TIME_DESC": "更新时间(降序)"
  1215. };
  1216. selectElement.find("option").each(function () {
  1217. var optionValue = $(this).val();
  1218. if (translations[optionValue]) {
  1219. $(this).text(translations[optionValue]);
  1220. }
  1221. });
  1222. parentElement = $('.setting-last-value');
  1223. selectElement = parentElement.find('select');
  1224. selectElement.find("option").each(function () {
  1225. var optionValue = $(this).val();
  1226. if (translations[optionValue]) {
  1227. $(this).text(translations[optionValue]);
  1228. }
  1229. });
  1230. })();
  1231. // 比赛过滤器选项汉化
  1232. (function () {
  1233. var parentElement = $('.options');
  1234. var selectElement = parentElement.find('li');
  1235. var translations = {
  1236. "Educational": "教育性",
  1237. "Global": "全球",
  1238. "VK Cup": "VK杯",
  1239. "Long Rounds": "长期回合",
  1240. "April Fools": "愚人节",
  1241. "Team Contests": "团队比赛",
  1242. "ICPC Scoring": "ICPC计分",
  1243. "Doesn't matter": "无关紧要",
  1244. "Any": "所有",
  1245. "Yes": "是",
  1246. "No": "否",
  1247. "No submission(s)": "无提交",
  1248. "Have submission(s)": "有提交",
  1249. "No solved problem(s)": "无解决问题",
  1250. "Have solved problem(s)": "有解决问题"
  1251. };
  1252. selectElement.find('label').each(function () {
  1253. var optionValue = $(this).text();
  1254. if (translations[optionValue]) {
  1255. $(this).text(translations[optionValue]);
  1256. }
  1257. });
  1258. $('.CaptionCont').find('span').each(function () {
  1259. var optionValue = $(this).text();
  1260. if (translations[optionValue]) {
  1261. $(this).text(translations[optionValue]);
  1262. }
  1263. });
  1264. })();
  1265. // 右侧sidebox通用汉化
  1266. (function () {
  1267. var parentElement = $('.sidebox');
  1268. var selectElement = parentElement.find('div');
  1269. var translations = {
  1270. "Show tags for unsolved problems": "显示未解决问题的标签",
  1271. "Hide solved problems": "隐藏已解决的问题",
  1272. };
  1273. selectElement.find("label").each(function () {
  1274. var optionValue = $(this).text();
  1275. if (translations[optionValue]) {
  1276. $(this).text(translations[optionValue]);
  1277. }
  1278. });
  1279. })();
  1280. // 表单字段名汉化
  1281. (function () {
  1282. var translations = {
  1283. "Problem:": "题目:",
  1284. "Language:": "语言:",
  1285. "Source code:": "源代码:",
  1286. "Or choose file:": "或者选择文件:",
  1287. "Choose file:": "选择文件:",
  1288. "Notice:": "注意:",
  1289. "virtual participation:": "虚拟参与:",
  1290. "Registration for the contest:": "比赛报名:",
  1291. "Take part:": "参与:",
  1292. "as individual participant:": "作为个人参与者:",
  1293. "as a team member:": "作为团队成员:",
  1294. "Virtual start time:": "虚拟开始时间:",
  1295. "Complete problemset:": "完整的问题集:",
  1296. "First name (English)": "名字(英文)",
  1297. "Last name (English)": "姓氏(英文)",
  1298. "First name (Native)": "名字(本地语言)",
  1299. "Last name (Native)": "姓氏(本地语言)",
  1300. "Birth date": "出生日期",
  1301. "Country": "国家",
  1302. "City": "城市",
  1303. "Organization": "组织",
  1304. "Handle/Email": "账号/邮箱",
  1305. "Password": "密码",
  1306. };
  1307. $(".field-name").each(function () {
  1308. var optionValue = $(this).text();
  1309. if (translations[optionValue]) {
  1310. $(this).text(translations[optionValue]);
  1311. }
  1312. });
  1313. })();
  1314. (function () {
  1315. var translations = {
  1316. "Terms of agreement:": "协议条款:",
  1317. "Choose team:": "选择团队:"
  1318. };
  1319. $(".field-name label").each(function () {
  1320. var optionValue = $(this).text();
  1321. if (translations[optionValue]) {
  1322. $(this).text(translations[optionValue]);
  1323. }
  1324. });
  1325. })();
  1326. (function () {
  1327. var translations = {
  1328. "Hide sidebar block \"Find user\"": "隐藏侧边栏块“查找用户”",
  1329. "Hide sidebar block \"Current user\"": "隐藏侧边栏块“当前用户”",
  1330. "Hide sidebar block \"Recent аctions\"": "隐藏侧边栏块“最新动态”",
  1331. "Hide sidebar block \"Favourite groups\"": "隐藏侧边栏块“收藏组”",
  1332. "Hide sidebar block \"Top contributors\"": "隐藏侧边栏块“贡献者排行”",
  1333. "Hide sidebar block \"Top rated\"": "隐藏侧边栏块“评级排行”",
  1334. "Hide sidebar block \"Streams\"": "隐藏侧边栏块“直播”",
  1335. "Old password": "旧密码",
  1336. "New password": "新密码",
  1337. "Confirm new password": "确认新密码",
  1338. "Contest email notification": "比赛邮件通知",
  1339. "Send email on new user talk": "在有新用户对话时发送电子邮件",
  1340. "Send email on new comment": "在有新评论时发送电子邮件",
  1341. "Hide contact information": "隐藏联系人信息",
  1342. "Remember me by Gmail, Facebook and etc": "通过 Gmail、Facebook 等记住我",
  1343. "Show tags for unsolved problems": "显示未解决问题的标签",
  1344. "Hide solved problems from problemset": "从问题集中隐藏已解决的问题",
  1345. "Hide low rated blogs": "隐藏评级较低的博客",
  1346. "Offer to publish great rating rises": "提供展示Rating显著提升的机会",
  1347. "Enforce https": "强制 HTTPS",
  1348. "Show private activity in the profile": "在个人资料中显示私人活动",
  1349. "Show diagnostics": "显示诊断信息"
  1350. };
  1351. $(".field-name").each(function () {
  1352. var tag = $(this).text();
  1353. for (var property in translations) {
  1354. property = property.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
  1355. if (tag.match(property)) {
  1356. $(this).text(translations[property]);
  1357. break;
  1358. }
  1359. }
  1360. });
  1361. })();
  1362. (function () {
  1363. var translations = {
  1364. "Postal/zip code": "邮政编码/邮编",
  1365. "Country (English)": "国家(英文)",
  1366. "State (English)": "州/省份(英文)",
  1367. "City (English)": "城市(英文)",
  1368. "Address (English)": "地址(英文)",
  1369. "Recipient (English)": "收件人姓名(英文)",
  1370. "Country (Native)": "国家(本地语言)",
  1371. "State (Native)": "州/省份(本地语言)",
  1372. "City (Native)": "城市(本地语言)",
  1373. "Address (Native)": "地址(本地语言)",
  1374. "Recipient (Native)": "收件人姓名(本地语言)",
  1375. "Phone": "电话",
  1376. "TON Wallet:": "TON 钱包:",
  1377. "Secret Code:": "验证码:"
  1378. };
  1379. $("td.field-name label").each(function () {
  1380. var optionValue = $(this).text();
  1381. if (translations[optionValue]) {
  1382. $(this).text(translations[optionValue]);
  1383. }
  1384. });
  1385. })();
  1386.  
  1387. // 按钮汉化input[type="submit"]
  1388. (function () {
  1389. var translations = {
  1390. "Register for virtual participation": "报名虚拟参赛",
  1391. "Register for practice": "登录以开始练习",
  1392. "Apply": "应用",
  1393. "Register": "报名",
  1394. "Login": "登录",
  1395. "Run": "运行",
  1396. "Start virtual contest": "开始虚拟参赛",
  1397. "Clone Contest": "克隆比赛",
  1398. "Submit": "提交",
  1399. "Save changes": "保存设置",
  1400. "Filter": "过滤",
  1401. "Find": "查找",
  1402. "Create Mashup Contest": "创建混搭比赛"
  1403. };
  1404. $('input[type="submit"]').each(function () {
  1405. var optionValue = $(this).val();
  1406. if (translations[optionValue]) {
  1407. $(this).val(translations[optionValue]);
  1408. }
  1409. });
  1410. })();
  1411. (function () {
  1412. var translations = {
  1413. "Reset": "重置",
  1414. };
  1415. $('input[type="button"]').each(function () {
  1416. var optionValue = $(this).val();
  1417. if (translations[optionValue]) {
  1418. $(this).val(translations[optionValue]);
  1419. }
  1420. });
  1421. })();
  1422.  
  1423. // 选项汉化input[type="radio"]
  1424. (function () {
  1425. var translations = {
  1426. "as individual participant": "个人",
  1427. "as a team member": "作为一个团队成员",
  1428. };
  1429. $('input[type="radio"]').each(function () {
  1430. var tag = $(this).parent().contents().filter(function () {
  1431. return this.nodeType === Node.TEXT_NODE;
  1432. });
  1433. for (var i = 0; i < tag.length; i++) {
  1434. var text = tag[i].textContent.trim();
  1435. if (translations.hasOwnProperty(text)) {
  1436. $(this).addClass(text);
  1437. tag[i].replaceWith(translations[text]);
  1438. break;
  1439. }
  1440. }
  1441. });
  1442. })();
  1443.  
  1444.  
  1445. // 杂项
  1446. (function () {
  1447. var translations = {
  1448. "(standard input\/output)": "标准输入/输出",
  1449. };
  1450. $("div.notice").each(function () {
  1451. var tag = $(this).children().eq(0).text();
  1452. for (var property in translations) {
  1453. if (tag.match(property)) {
  1454. $(this).children().eq(0).text(translations[property]);
  1455. break;
  1456. }
  1457. }
  1458. });
  1459. })();
  1460. (function () {
  1461. var translations = {
  1462. "Ask a question": "提一个问题",
  1463. };
  1464. $(".ask-question-link").each(function () {
  1465. var optionValue = $(this).text();
  1466. if (translations[optionValue]) {
  1467. $(this).text(translations[optionValue]);
  1468. }
  1469. });
  1470. })();
  1471.  
  1472. // 轻量站特殊
  1473. if (is_mSite) {
  1474. (function () {
  1475. var translations = {
  1476. "Announcements": "公告",
  1477. "Submissions": "提交记录",
  1478. "Contests": "比赛",
  1479. };
  1480. $(".caption").each(function () {
  1481. var optionValue = $(this).text();
  1482. if (translations[optionValue]) {
  1483. $(this).text(translations[optionValue]);
  1484. }
  1485. });
  1486. })();
  1487. }
  1488. })();
  1489.  
  1490. // 设置面板
  1491. $("div[class='lang-chooser']").each(function () {
  1492. $(this).before(
  1493. "<button class='html2mdButton CFBetter_setting'>CodeforcesBetter设置</button>"
  1494. );
  1495. });
  1496. $("div[class='enter-or-register-box']").each(function () {
  1497. $(this).after(
  1498. "<button class='html2mdButton CFBetter_setting'>CodeforcesBetter设置</button>"
  1499. );
  1500. });
  1501. $(document).ready(function () {
  1502. const $settingBtns = $(".CFBetter_setting");
  1503. $settingBtns.click(() => {
  1504. const styleElement = GM_addStyle(darkenPageStyle);
  1505. $settingBtns.prop("disabled", true).addClass("open")
  1506. $("body").append(`
  1507. <div id='CFBetter_setting_menu'>
  1508. <div class="tool-box">
  1509. <button class="btn-close">×</button>
  1510. </div>
  1511. <h3>基本设置</h3>
  1512. <hr>
  1513. <div class='CFBetter_setting_list'>
  1514. <label for="bottomZh_CN">界面汉化</label>
  1515. <input type="checkbox" id="bottomZh_CN" name="bottomZh_CN">
  1516. </div>
  1517. <div class='CFBetter_setting_list'>
  1518. <label for="showLoading">显示加载提示信息</label>
  1519. <div class="help_tip">
  1520. `+ helpCircleHTML + `
  1521. <div class="tip_text">
  1522. <p>当你开启 显示加载信息 时,每次加载页面时会在上方显示加载信息提示:“Codeforces Better! —— xxx”</p>
  1523. <p>这用于了解脚本当前的工作情况,<strong>如果你不想看到,可以选择关闭</strong></p>
  1524. <p><u>需要说明的是,如果你需要反馈脚本的任何加载问题,请开启该选项后再截图,以便于分析问题</u></p>
  1525. </div>
  1526. </div>
  1527. <input type="checkbox" id="showLoading" name="showLoading">
  1528. </div>
  1529. <div class='CFBetter_setting_list'>
  1530. <label for="showLoading">显示目标区域范围</label>
  1531. <div class="help_tip">
  1532. `+ helpCircleHTML + `
  1533. <div class="tip_text">
  1534. <p>开启后当鼠标悬浮在 MD视图/复制/翻译 按钮上时,会显示其目标区域的范围</p>
  1535. </div>
  1536. </div>
  1537. <input type="checkbox" id="hoverTargetAreaDisplay" name="hoverTargetAreaDisplay">
  1538. </div>
  1539. <div class='CFBetter_setting_list'>
  1540. <label for="expandFoldingblocks">自动展开折叠块</label>
  1541. <input type="checkbox" id="expandFoldingblocks" name="expandFoldingblocks">
  1542. </div>
  1543. <div class='CFBetter_setting_list'>
  1544. <label for="enableSegmentedTranslation">分段翻译</label>
  1545. <div class="help_tip">
  1546. `+ helpCircleHTML + `
  1547. <div class="tip_text">
  1548. <p>分段翻译会对区域内的每一个&#60;&#112;&#47;&#62;和&#60;&#105;&#47;&#62;标签依次进行翻译,</p>
  1549. <p>这通常在翻译<strong>长篇博客</strong>或者<strong>超长的题目</strong>时很有用。</p>
  1550. <p><u>注意:开启分段翻译会产生如下问题:</u></p>
  1551. <p>- 使得翻译接口无法知晓整个文本的上下文信息,会降低翻译质量。</p>
  1552. <p>- 会有<strong>部分内容不会被翻译</strong>,因为它们不是&#60;&#112;&#47;&#62;或&#60;&#105;&#47;&#62;标签</p>
  1553. </div>
  1554. </div>
  1555. <input type="checkbox" id="enableSegmentedTranslation" name="enableSegmentedTranslation">
  1556. </div>
  1557. <div class='CFBetter_setting_list'>
  1558. <label for="showJumpToLuogu">显示跳转到洛谷</label>
  1559. <div class="help_tip">
  1560. `+ helpCircleHTML + `
  1561. <div class="tip_text">
  1562. <p>洛谷OJ上收录了Codeforces的部分题目,一些题目有翻译和题解</p>
  1563. <p>开启显示后,如果当前题目被收录,则会在题目的右上角显示洛谷标志,</p>
  1564. <p>点击即可一键跳转到该题洛谷的对应页面。</strong></p>
  1565. </div>
  1566. </div>
  1567. <input type="checkbox" id="showJumpToLuogu" name="showJumpToLuogu">
  1568. </div>
  1569. <div class='CFBetter_setting_list'>
  1570. <label for="loaded"><span style="font-size: 14px;">兼容选项-不等待页面资源加载</span></label>
  1571. <div class="help_tip">
  1572. `+ helpCircleHTML + `
  1573. <div class="tip_text">
  1574. <p>为了防止在页面资源未加载完成前(主要是各种js)执行脚本产生意外的错误,脚本默认会等待 window.onload 事件</p>
  1575. <p>如果您的页面上方的加载信息始终停留在:“等待页面资源加载”,即使页面已经完成加载</p>
  1576. <p><u>您首先应该确认是否是网络问题,</u></p>
  1577. <p>如果不是,那这可能是由于 window.onload 事件在您的浏览器中触发过早(早于document.ready),</p>
  1578. <p>您可以尝试开启该选项来不再等待 window.onload 事件</p>
  1579. <p><u>注意:如果没有上述问题,请不要开启该选项</u></p>
  1580. </div>
  1581. </div>
  1582. <input type="checkbox" id="loaded" name="loaded">
  1583. </div>
  1584. <h3>翻译设置</h3>
  1585. <hr>
  1586. <label>
  1587. <input type='radio' name='translation' value='deepl'>
  1588. <span class='CFBetter_setting_menu_label_text'>deepl翻译</span>
  1589. </label>
  1590. <label>
  1591. <input type='radio' name='translation' value='youdao'>
  1592. <span class='CFBetter_setting_menu_label_text'>有道翻译</span>
  1593. </label>
  1594. <label>
  1595. <input type='radio' name='translation' value='google'>
  1596. <span class='CFBetter_setting_menu_label_text'>Google翻译</span>
  1597. </label>
  1598. <label>
  1599. <input type='radio' name='translation' value='openai'>
  1600. <span class='CFBetter_setting_menu_label_text'>使用ChatGPT翻译(API)
  1601. <div class="help_tip">
  1602. `+ helpCircleHTML + `
  1603. <div class="tip_text">
  1604. <p><b>请确保你能够正常访问OpenAIapi</b></p>
  1605. <p>Codeforces Better!默认使用 gpt-3.5-turbo 模型进行翻译,脚本的所有请求均在本地完成</p>
  1606. <p>你需要输入自己的OpenAI KEY,<a target="_blank" href="https://platform.openai.com/account/usage">官网</a></p>
  1607. </div>
  1608. </div>
  1609. </span>
  1610. </label>
  1611. <label>
  1612. <input type='radio' name='translation' value='api2d'>
  1613. <span class='CFBetter_setting_menu_label_text'>使用api2d翻译(API)
  1614. <div class="help_tip">
  1615. `+ helpCircleHTML + `
  1616. <div class="tip_text">
  1617. <p>api2d是国内的一家提供代理直连访问OpenAIapi的服务商,相当于OpenAIapi的套壳</p>
  1618. <p>Codeforces Better!默认使用 gpt-3.5-turbo 模型进行翻译,脚本的所有请求均在本地完成</p>
  1619. <p>你需要输入自己的api2d KEY,<a target="_blank" href="https://api2d.com/profile">官网</a></p>
  1620. </div>
  1621. </div>
  1622. </span>
  1623. </label>
  1624. <div class='CFBetter_setting_menu_input' id='openai' style='display: none;'>
  1625. <label for='openai_model'>
  1626. <div style="display: flex;align-items: center;">
  1627. <span class="input_label">模型:</span>
  1628. <div class="help_tip">
  1629. `+ helpCircleHTML + `
  1630. <div class="tip_text">
  1631. <p>默认为:gpt-3.5-turbo</p>
  1632. <p>如需更换,请查阅<a target="_blank" href="https://platform.openai.com/docs/models">官方文档</a></p>
  1633. <p><strong>如果你使用的是服务商提供的代理API,请确认服务商是否支持对应模型</strong></p>
  1634. </div>
  1635. </div>
  1636. </div>
  1637. </label>
  1638. <input type='text' id='openai_model'>
  1639. <label for='openai_key'>
  1640. <span class="input_label">KEY:</span>
  1641. </label>
  1642. <input type='text' id='openai_key'>
  1643. <div class='CFBetter_setting_list'>
  1644. <label for="showOpneAiAdvanced">使用代理API</label>
  1645. <div class="help_tip">
  1646. `+ helpCircleHTML + `
  1647. <div class="tip_text">
  1648. <p>使用你指定的API来代理访问OpenAI进行翻译,脚本的所有请求均在本地完成</p>
  1649. <p>如果你使用的是OpenAI的官方KEY,建议你自建代理,而不是使用他人公开的代理,那是危险的</p>
  1650. <p>如果你使用的是服务商提供的代理和KEY,则这里应该填写其提供的<strong>完整</strong>API地址,<br>
  1651. 这里以<a target="_blank" href="https://console.closeai-asia.com/">CloseAI</a>为例,其提供了API Base: https://api.closeai-proxy.xyz,<br>
  1652. 那么这里实际应该填写的就是https://api.closeai-proxy.xyz/v1/chat/\ncompletions,而上面的KEY则应该填写CloseAI提供的API Key</p>
  1653. <p><strong>由于你指定了自定义的APITampermonkey会对你的跨域请求进行警告,请自行授权</strong></p>
  1654. </div>
  1655. </div>
  1656. <input type="checkbox" id="showOpneAiAdvanced" name="showOpneAiAdvanced">
  1657. </div>
  1658. <div id="is_showOpneAiAdvanced">
  1659. <label for='openai_proxy'>
  1660. <span class="input_label">Proxy API:</span>
  1661. </label>
  1662. <input type='text' id='openai_proxy'>
  1663. </div>
  1664. </div>
  1665. <div class='CFBetter_setting_menu_input' id='api2d' style='display: none;'>
  1666. <label for='api2d_model'>
  1667. <div style="display: flex;align-items: center;">
  1668. <span class="input_label">模型:</span>
  1669. <div class="help_tip">
  1670. `+ helpCircleHTML + `
  1671. <div class="tip_text">
  1672. <p>默认为:gpt-3.5-turbo</p>
  1673. <p>如需更换,请查阅<a target="_blank" href="https://api2d.com/wiki/doc">官方文档</a></p>
  1674. </div>
  1675. </div>
  1676. </div>
  1677. </label>
  1678. <input type='text' id='api2d_model'>
  1679. <label for='api2d_key'>
  1680. <span class="input_label">KEY:</span>
  1681. </label>
  1682. <input type='text' id='api2d_key'>
  1683. <label for='api2d_request_entry'>
  1684. <div style="display: flex;align-items: center;">
  1685. <span class="input_label">请求入口:</span>
  1686. <div class="help_tip">
  1687. `+ helpCircleHTML + `
  1688. <div class="tip_text">
  1689. <p>如果发现请求报错超时未响应,请查看<a target="_blank" href="https://api2d.com/wiki/doc">官方文档</a>以及<a target="_blank" href="https://support.qq.com/product/544571">API2D反馈论坛</a>尝试更换请求入口</p>
  1690. <p>默认为:https://openai.api2d.net</p>
  1691. <p>注意格式,末尾没有“斜杠/”</p>
  1692. </div>
  1693. </div>
  1694. </div>
  1695. </label>
  1696. <input type='text' id='api2d_request_entry'>
  1697. <div class='CFBetter_setting_list'>
  1698. <label for="x_api2d_no_cache">使用缓存</label>
  1699. <div class="help_tip">
  1700. `+ helpCircleHTML + `
  1701. <div class="tip_text">
  1702. <p>API2D 的服务器会对请求结果做缓存,如果请求体的hash值相同,会直接返回缓存的结果。缓存命中之后,本次请求不会扣除任何点数。</p>
  1703. <p>缓存会保存 24 小时,如果不想使用缓存,你可以关闭“使用缓存”来跳过缓存,强制 API2D 服务器发送新请求。<a target="_blank" href="https://api2d.com/wiki/doc">详请阅读官方文档</a></p>
  1704. </div>
  1705. </div>
  1706. <input type="checkbox" id="x_api2d_no_cache" name="x_api2d_no_cache">
  1707. </div>
  1708. </div>
  1709. <br>
  1710. <button id='save'>保存</button>
  1711. </div>
  1712. `);
  1713. $("#bottomZh_CN").prop("checked", GM_getValue("bottomZh_CN") === true);
  1714. $("#showLoading").prop("checked", GM_getValue("showLoading") === true);
  1715. $("#expandFoldingblocks").prop("checked", GM_getValue("expandFoldingblocks") === true);
  1716. $("#enableSegmentedTranslation").prop("checked", GM_getValue("enableSegmentedTranslation") === true);
  1717. $("#showJumpToLuogu").prop("checked", GM_getValue("showJumpToLuogu") === true);
  1718. $("#loaded").prop("checked", GM_getValue("loaded") === true);
  1719. $("#x_api2d_no_cache").prop("checked", GM_getValue("x_api2d_no_cache") === true);
  1720. $("#showOpneAiAdvanced").prop("checked", GM_getValue("showOpneAiAdvanced") === true);
  1721. $("#hoverTargetAreaDisplay").prop("checked", GM_getValue("hoverTargetAreaDisplay") === true);
  1722. $("input[name='translation'][value='" + translation + "']").prop("checked", true);
  1723. $("input[name='translation']").css("color", "gray");
  1724. if (translation == "openai") {
  1725. $("#openai").show();
  1726. $("#openai_model").val(openai_model);
  1727. $("#openai_key").val(GM_getValue("openai_key"));
  1728. $("#openai_proxy").val(GM_getValue("openai_proxy"));
  1729. $("#openai_key").css("color", "gray");
  1730. if (showOpneAiAdvanced) $("#is_showOpneAiAdvanced").show();
  1731. else $("#is_showOpneAiAdvanced").hide();
  1732. } else if (translation == "api2d") {
  1733. $("#api2d").show();
  1734. $("#api2d_model").val(api2d_model);
  1735. $("#api2d_key").val(GM_getValue("api2d_key"));
  1736. $("#api2d_request_entry").val(api2d_request_entry);
  1737. $("#api2d_key").css("color", "gray");
  1738. }
  1739. // 当单选框被选中时,显示对应的输入框,同时隐藏其他输入框
  1740. $("input[name='translation']").change(function () {
  1741. var selected = $(this).val(); // 获取当前选中的值
  1742. if (selected === "openai") {
  1743. $("#openai").show();
  1744. $("#openai_model").val(openai_model);
  1745. $("#openai_key").val(GM_getValue("openai_key"));
  1746. $("#showOpneAiAdvanced").prop("checked", showOpneAiAdvanced);
  1747. if (showOpneAiAdvanced) {
  1748. $("#is_showOpneAiAdvanced").show();
  1749. $("#openai_proxy").val(GM_getValue("openai_proxy"));
  1750. }
  1751. else $("#is_showOpneAiAdvanced").hide();
  1752. $("#api2d").hide();
  1753. } else if (selected === "api2d") {
  1754. $("#api2d").show();
  1755. $("#api2d_model").val(api2d_model);
  1756. $("#api2d_key").val(GM_getValue("api2d_key"));
  1757. $("#api2d_request_entry").val(api2d_request_entry);
  1758. $("#x_api2d_no_cache").prop("checked", GM_getValue("x_api2d_no_cache"));
  1759. $("#openai").hide();
  1760. } else {
  1761. $("#openai, #api2d").hide();
  1762. }
  1763. });
  1764.  
  1765. // ChatGPT高级选项
  1766. $("input[name='showOpneAiAdvanced']").change(function () {
  1767. var isChecked = $(this).is(":checked");
  1768. if (isChecked) {
  1769. $("#is_showOpneAiAdvanced").show();
  1770. } else {
  1771. $("#is_showOpneAiAdvanced").hide();
  1772. }
  1773. });
  1774.  
  1775. const $settingMenu = $("#CFBetter_setting_menu");
  1776.  
  1777. $("#save").click(debounce(function () {
  1778. const settings = {
  1779. bottomZh_CN: $("#bottomZh_CN").prop("checked"),
  1780. showLoading: $("#showLoading").prop("checked"),
  1781. loaded: $("#loaded").prop("checked"),
  1782. expandFoldingblocks: $("#expandFoldingblocks").prop("checked"),
  1783. enableSegmentedTranslation: $("#enableSegmentedTranslation").prop("checked"),
  1784. showJumpToLuogu: $("#showJumpToLuogu").prop("checked"),
  1785. showOpneAiAdvanced: $("#showOpneAiAdvanced").prop("checked"),
  1786. hoverTargetAreaDisplay: $("#hoverTargetAreaDisplay").prop("checked"),
  1787. translation: $("input[name='translation']:checked").val()
  1788. };
  1789. if (settings.translation === "openai") {
  1790. GM_setValue("openai_model", $("#openai_model").val());
  1791. GM_setValue("openai_key", $("#openai_key").val());
  1792. GM_setValue("openai_proxy", $("#openai_proxy").val());
  1793. } else if (settings.translation === "api2d") {
  1794. GM_setValue("api2d_model", $("#api2d_model").val());
  1795. GM_setValue("api2d_key", $("#api2d_key").val());
  1796. GM_setValue("api2d_request_entry", $("#api2d_request_entry").val());
  1797. GM_setValue("x_api2d_no_cache", $("#x_api2d_no_cache").prop("checked"));
  1798. }
  1799. for (const [key, value] of Object.entries(settings)) {
  1800. GM_setValue(key, value);
  1801. }
  1802.  
  1803. $settingMenu.remove();
  1804. $(styleElement).remove();
  1805. location.reload();
  1806. }));
  1807.  
  1808. // 关闭
  1809. $settingMenu.on("click", ".btn-close", () => {
  1810. $settingMenu.remove();
  1811. $settingBtns.prop("disabled", false).removeClass("open");
  1812. $(styleElement).remove();
  1813. });
  1814. });
  1815. });
  1816.  
  1817. // 说明为旧的latex渲染
  1818. if (is_oldLatex) {
  1819. var newElement = $("<div></div>").addClass("alert alert-warning").html(`
  1820. 注意:当前页面存在使用非 MathJax 库渲染为 HTML Latex 公式(这通常是一道古老的题目),这导致 CodeforcesBetter! 无法将其还原回 Latex,因此当前页面部分功能不适用。
  1821. <br>此外当前页面的翻译功能采用了特别的实现方式,因此可能会出现排版错位的情况。
  1822. `).css({
  1823. "margin": "1em",
  1824. "text-align": "center",
  1825. "position": "relative"
  1826. });
  1827. $(".menu-box:first").next().after(newElement);
  1828. }
  1829.  
  1830. // html2md转换/处理规则
  1831. var turndownService = new TurndownService({ bulletListMarker: '-' });
  1832. var turndown = turndownService.turndown;
  1833.  
  1834. // 保留原始
  1835. turndownService.keep(['del']);
  1836.  
  1837. // 丢弃
  1838. turndownService.addRule('remove-by-class', {
  1839. filter: function (node) {
  1840. return node.classList.contains('sample-tests') ||
  1841. node.classList.contains('header') ||
  1842. node.classList.contains('overlay') ||
  1843. node.classList.contains('html2md-panel');
  1844. },
  1845. replacement: function (content, node) {
  1846. return "";
  1847. }
  1848. });
  1849. turndownService.addRule('remove-script', {
  1850. filter: function (node, options) {
  1851. return node.tagName.toLowerCase() == "script" && node.type.startsWith("math/tex");
  1852. },
  1853. replacement: function (content, node) {
  1854. return "";
  1855. }
  1856. });
  1857.  
  1858. // inline math
  1859. turndownService.addRule('inline-math', {
  1860. filter: function (node, options) {
  1861. return node.tagName.toLowerCase() == "span" && node.className == "MathJax";
  1862. },
  1863. replacement: function (content, node) {
  1864. var latex = $(node).next().text();
  1865. latex = latex.replace(/</g, "&lt;").replace(/>/g, "&gt;");
  1866. return "$" + latex + "$";
  1867. }
  1868. });
  1869.  
  1870. // block math
  1871. turndownService.addRule('block-math', {
  1872. filter: function (node, options) {
  1873. return node.tagName.toLowerCase() == "div" && node.className == "MathJax_Display";
  1874. },
  1875. replacement: function (content, node) {
  1876. var latex = $(node).next().text();
  1877. latex = latex.replace(/</g, "&lt;").replace(/>/g, "&gt;");
  1878. return "\n$$\n" + latex + "\n$$\n";
  1879. }
  1880. });
  1881.  
  1882. // texFontStyle
  1883. turndownService.addRule('texFontStyle', {
  1884. filter: function (node) {
  1885. return (
  1886. node.nodeName === 'SPAN' &&
  1887. node.classList.contains('tex-font-style-bf')
  1888. )
  1889. },
  1890. replacement: function (content) {
  1891. return '**' + content + '**'
  1892. }
  1893. })
  1894.  
  1895. // sectionTitle
  1896. turndownService.addRule('sectionTitle', {
  1897. filter: function (node) {
  1898. return (
  1899. node.nodeName === 'DIV' &&
  1900. node.classList.contains('section-title')
  1901. )
  1902. },
  1903. replacement: function (content) {
  1904. return '**' + content + '**'
  1905. }
  1906. })
  1907.  
  1908. // bordertable
  1909. turndownService.addRule('bordertable', {
  1910. filter: 'table',
  1911. replacement: function (content, node) {
  1912. if (node.classList.contains('bordertable')) {
  1913. var output = [],
  1914. thead = '',
  1915. trs = node.querySelectorAll('tr');
  1916. if (trs.length > 0) {
  1917. var ths = trs[0].querySelectorAll('td,th');
  1918. if (ths.length > 0) {
  1919. thead = '| ' + Array.from(ths).map(th => turndownService.turndown(th.innerHTML.trim())).join(' | ') + ' |\n'
  1920. + '| ' + Array.from(ths).map(() => ' --- ').join('|') + ' |\n';
  1921. }
  1922. }
  1923. var rows = node.querySelectorAll('tr');
  1924. Array.from(rows).forEach(function (row, i) {
  1925. if (i > 0) {
  1926. var cells = row.querySelectorAll('td,th');
  1927. var trow = '| ' + Array.from(cells).map(cell => turndownService.turndown(cell.innerHTML.trim())).join(' | ') + ' |';
  1928. output.push(trow);
  1929. }
  1930. });
  1931. return thead + output.join('\n');
  1932. } else {
  1933. return content;
  1934. }
  1935. }
  1936. });
  1937.  
  1938. // 随机数生成
  1939. function getRandomNumber(numDigits) {
  1940. let min = Math.pow(10, numDigits - 1);
  1941. let max = Math.pow(10, numDigits) - 1;
  1942. return Math.floor(Math.random() * (max - min + 1)) + min;
  1943. }
  1944.  
  1945. // 题目markdown转换/翻译面板
  1946. function addButtonPanel(parent, suffix, type, is_simple = false) {
  1947. let htmlString = `<div class='html2md-panel'>
  1948. <button class='html2mdButton html2md-view${suffix}'>MarkDown视图</button>
  1949. <button class='html2mdButton html2md-cb${suffix}'>Copy</button>
  1950. <button class='html2mdButton translateButton${suffix}'>翻译</button>
  1951. </div>`;
  1952. if (type === "this_level") {
  1953. $(parent).before(htmlString);
  1954. } else if (type === "child_level") {
  1955. $(parent).prepend(htmlString);
  1956. }
  1957. if (is_simple) {
  1958. $('.html2md-panel').find('.html2mdButton.html2md-view' + suffix + ', .html2mdButton.html2md-cb' + suffix).remove();
  1959. }
  1960. }
  1961. function addButtonWithHTML2MD(parent, suffix, type) {
  1962. if (is_oldLatex) {
  1963. $(".html2md-view" + suffix).css({
  1964. "cursor": "not-allowed",
  1965. "background-color": "#ffffff",
  1966. "color": "#a8abb2",
  1967. "border": "1px solid #e4e7ed"
  1968. });
  1969. $(".html2md-view" + suffix).prop("disabled", true);
  1970. }
  1971. $(document).on("click", ".html2md-view" + suffix, debounce(function () {
  1972. var target, removedChildren = $();
  1973. if (type === "this_level") {
  1974. target = $(".html2md-view" + suffix).parent().next().get(0);
  1975. } else if (type === "child_level") {
  1976. target = $(".html2md-view" + suffix).parent().parent().get(0);
  1977. removedChildren = $(".html2md-view" + suffix).parent().parent().children(':first').detach();
  1978. }
  1979. if (target.viewmd) {
  1980. target.viewmd = false;
  1981. $(this).text("MarkDown视图");
  1982. $(this).removeClass("mdViewed");
  1983. $(target).html(target.original_html);
  1984. } else {
  1985. target.viewmd = true;
  1986. if (!target.original_html) {
  1987. target.original_html = $(target).html();
  1988. }
  1989. if (!target.markdown) {
  1990. target.markdown = turndownService.turndown($(target).html());
  1991. }
  1992. $(this).text("原始内容");
  1993. $(this).addClass("mdViewed");
  1994. $(target).html(`<span class="mdViewContent" oninput="$(this).parent().get(0).markdown=this.value;" style="width:auto; height:auto;">${target.markdown}</span>`);
  1995. }
  1996. // 恢复删除的元素
  1997. if (removedChildren) $(target).prepend(removedChildren);
  1998. }));
  1999.  
  2000. if (hoverTargetAreaDisplay) {
  2001. $(document).on("mouseover", ".html2md-view" + suffix, function () {
  2002. var target;
  2003.  
  2004. if (type === "this_level") {
  2005. target = $(".html2md-view" + suffix).parent().next().get(0);
  2006. } else if (type === "child_level") {
  2007. target = $(".html2md-view" + suffix).parent().parent().get(0);
  2008. }
  2009.  
  2010. $(target).append('<div class="overlay">目标转换区域</div>');
  2011. $(target).css({
  2012. "position": "relative",
  2013. "display": "block"
  2014. });
  2015. $(".html2md-view" + suffix).parent().css({
  2016. "position": "relative",
  2017. "z-index": "99999"
  2018. })
  2019. });
  2020.  
  2021. $(document).on("mouseout", ".html2md-view" + suffix, function () {
  2022. var target;
  2023.  
  2024. if (type === "this_level") {
  2025. target = $(".html2md-view" + suffix).parent().next().get(0);
  2026. } else if (type === "child_level") {
  2027. target = $(".html2md-view" + suffix).parent().parent().get(0);
  2028. }
  2029.  
  2030. $(target).find('.overlay').remove();
  2031. $(target).css({
  2032. "position": "",
  2033. "display": ""
  2034. });
  2035. $(".html2md-view" + suffix).parent().css({
  2036. "position": "static"
  2037. })
  2038. });
  2039. }
  2040. }
  2041.  
  2042. function addButtonWithCopy(parent, suffix, type) {
  2043. if (is_oldLatex) {
  2044. $(".html2md-cb" + suffix).css({
  2045. "cursor": "not-allowed",
  2046. "background-color": "#ffffff",
  2047. "color": "#a8abb2",
  2048. "border": "1px solid #e4e7ed"
  2049. });
  2050. $(".html2md-cb" + suffix).prop("disabled", true);
  2051. }
  2052. $(document).on("click", ".html2md-cb" + suffix, debounce(function () {
  2053. var target, removedChildren;
  2054. if (type === "this_level") {
  2055. target = $(".translateButton" + suffix).parent().next().eq(0).clone();
  2056. } else if (type === "child_level") {
  2057. target = $(".translateButton" + suffix).parent().parent().eq(0).clone();
  2058. $(target).children(':first').remove();
  2059. }
  2060. if ($(target).find('.mdViewContent').length <= 0) {
  2061. text = turndownService.turndown($(target).html());
  2062. } else {
  2063. text = $(target).find('.mdViewContent').text();
  2064. }
  2065. GM_setClipboard(text);
  2066. $(this).addClass("copied");
  2067. $(this).text("Copied");
  2068. // 更新复制按钮文本
  2069. setTimeout(() => {
  2070. $(this).removeClass("copied");
  2071. $(this).text("Copy");
  2072. }, 2000);
  2073. $(target).remove();
  2074. }));
  2075.  
  2076. if (hoverTargetAreaDisplay) {
  2077. $(document).on("mouseover", ".html2md-cb" + suffix, function () {
  2078. var target;
  2079.  
  2080. if (type === "this_level") {
  2081. target = $(".html2md-cb" + suffix).parent().next().get(0);
  2082. } else if (type === "child_level") {
  2083. target = $(".html2md-cb" + suffix).parent().parent().get(0);
  2084. }
  2085.  
  2086. $(target).append('<div class="overlay">目标复制区域</div>');
  2087. $(target).css({
  2088. "position": "relative",
  2089. "display": "block"
  2090. });
  2091. $(".html2md-cb" + suffix).parent().css({
  2092. "position": "relative",
  2093. "z-index": "99999"
  2094. })
  2095. });
  2096.  
  2097. $(document).on("mouseout", ".html2md-cb" + suffix, function () {
  2098. var target;
  2099.  
  2100. if (type === "this_level") {
  2101. target = $(".html2md-cb" + suffix).parent().next().get(0);
  2102. } else if (type === "child_level") {
  2103. target = $(".html2md-cb" + suffix).parent().parent().get(0);
  2104. }
  2105.  
  2106. $(target).find('.overlay').remove();
  2107. $(target).css({
  2108. "position": "",
  2109. "display": ""
  2110. });
  2111. $(".html2md-cb" + suffix).parent().css({
  2112. "position": "static"
  2113. })
  2114. });
  2115. }
  2116. }
  2117.  
  2118. async function addButtonWithTranslation(parent, suffix, type) {
  2119. var result;
  2120. $(document).on('click', '.translateButton' + suffix, debounce(async function () {
  2121. $(this).removeClass("translated");
  2122. $(this).text("翻译中");
  2123. $(this).css("cursor", "not-allowed");
  2124. var target, element_node, block, errerNum = 0, is_x_api2d_no_cache = false;
  2125. if (type === "this_level") block = $(".translateButton" + suffix).parent().next();
  2126. else if (type === "child_level") block = $(".translateButton" + suffix).parent().parent();
  2127.  
  2128. // 重新翻译
  2129. if (result) {
  2130. if (result.translateDiv) {
  2131. $(result.translateDiv).remove();
  2132. }
  2133. if (!is_oldLatex) {
  2134. if (result.copyDiv) {
  2135. $(result.copyDiv).remove();
  2136. }
  2137. if (result.copyButton) {
  2138. $(result.copyButton).remove();
  2139. }
  2140. }
  2141. // 重新翻译时暂时关闭 x_api2d_no_cache
  2142. if (x_api2d_no_cache) {
  2143. x_api2d_no_cache = false;
  2144. is_x_api2d_no_cache = true;
  2145. }
  2146. // 移除旧的事件
  2147. $(document).off("mouseover", ".translateButton" + suffix);
  2148. $(document).off("mouseout", ".translateButton" + suffix);
  2149. // 重新绑定悬停事件
  2150. if (hoverTargetAreaDisplay) bindHoverEvents(suffix, type);
  2151. }
  2152.  
  2153. // 分段翻译
  2154. if (enableSegmentedTranslation) {
  2155. var pElements = block.find("p, li");
  2156. for (let i = 0; i < pElements.length; i++) {
  2157. target = $(pElements[i]).eq(0).clone();
  2158. if (type === "child_level") $(target).children(':first').remove();
  2159. element_node = pElements[i];
  2160. if (type === "child_level") {
  2161. $(pElements[i]).append("<div></div>");
  2162. element_node = $(pElements[i]).find("div:last-child").get(0);
  2163. }
  2164. result = await blockProcessing(target, element_node, $(".translateButton" + suffix));
  2165. if (result.status) errerNum += 1;
  2166. $(target).remove();
  2167. if (translation == "deepl") await new Promise(resolve => setTimeout(resolve, 2000));
  2168. }
  2169. } else {
  2170. target = block.eq(0).clone();
  2171. if (type === "child_level") $(target).children(':first').remove();
  2172. element_node = $(block).get(0);
  2173. if (type === "child_level") {
  2174. $(parent).append("<div></div>");
  2175. element_node = $(parent).find("div:last-child").get(0);
  2176. }
  2177. //是否跳过折叠块
  2178. if ($(target).find('.spoiler').length > 0) {
  2179. const shouldSkip = await skiFoldingBlocks();
  2180. if (shouldSkip) {
  2181. $(target).find('.spoiler').remove();
  2182. } else {
  2183. $(target).find('.html2md-panel').remove();
  2184. }
  2185. }
  2186. result = await blockProcessing(target, element_node, $(".translateButton" + suffix));
  2187. if (result.status) errerNum += 1;
  2188. $(target).remove();
  2189. }
  2190. if (!errerNum) {
  2191. $(this).addClass("translated")
  2192. .text("已翻译")
  2193. .css("cursor", "pointer")
  2194. .removeClass("error");
  2195. }
  2196.  
  2197. // 恢复x_api2d_no_cache设置
  2198. if (is_x_api2d_no_cache) x_api2d_no_cache = true;
  2199.  
  2200. // 重新翻译
  2201. let currentText, is_error;
  2202. $(document).on("mouseover", ".translateButton" + suffix, function () {
  2203. currentText = $(this).text();
  2204. $(this).text("重新翻译");
  2205. if ($(this).hasClass("error")) {
  2206. is_error = true;
  2207. $(this).removeClass("error");
  2208. }
  2209. });
  2210.  
  2211. $(document).on("mouseout", ".translateButton" + suffix, function () {
  2212. $(this).text(currentText);
  2213. if (is_error) $(this).addClass("error");
  2214. });
  2215. }));
  2216.  
  2217. // 目标区域指示
  2218. function bindHoverEvents(suffix, type) {
  2219. $(document).on("mouseover", ".translateButton" + suffix, function () {
  2220. var target;
  2221.  
  2222. if (type === "this_level") {
  2223. target = $(".translateButton" + suffix).parent().next().get(0);
  2224. } else if (type === "child_level") {
  2225. target = $(".translateButton" + suffix).parent().parent().get(0);
  2226. }
  2227.  
  2228. $(target).append('<div class="overlay">目标翻译区域</div>');
  2229. $(target).css({
  2230. "position": "relative",
  2231. "display": "block"
  2232. });
  2233. $(".translateButton" + suffix).parent().css({
  2234. "position": "relative",
  2235. "z-index": "99999"
  2236. });
  2237. });
  2238.  
  2239. $(document).on("mouseout", ".translateButton" + suffix, function () {
  2240. var target;
  2241.  
  2242. if (type === "this_level") {
  2243. target = $(".translateButton" + suffix).parent().next().get(0);
  2244. } else if (type === "child_level") {
  2245. target = $(".translateButton" + suffix).parent().parent().get(0);
  2246. }
  2247.  
  2248. $(target).find('.overlay').remove();
  2249. $(target).css({
  2250. "position": "",
  2251. "display": ""
  2252. });
  2253. $(".translateButton" + suffix).parent().css({
  2254. "position": "static"
  2255. });
  2256. });
  2257. }
  2258.  
  2259. if (hoverTargetAreaDisplay) bindHoverEvents(suffix, type);
  2260. }
  2261.  
  2262. // 块处理
  2263. async function blockProcessing(target, element_node, button) {
  2264. if (is_oldLatex) {
  2265. $(target).find('.overlay').remove();
  2266. target.markdown = $(target).html();
  2267. } else if (!target.markdown) {
  2268. target.markdown = turndownService.turndown($(target).html());
  2269. }
  2270. const textarea = document.createElement('textarea');
  2271. textarea.value = target.markdown;
  2272. var result = await translateProblemStatement(textarea.value, element_node, $(button));
  2273. //
  2274. if (result.status == 1) {
  2275. $(button).addClass("error")
  2276. .text("翻译中止")
  2277. .css("cursor", "pointer")
  2278. .prop("disabled", false);
  2279. $(result.translateDiv).remove();
  2280. $(target).remove();
  2281. } else if (result.status == 2) {
  2282. result.translateDiv.classList.add("error_translate");
  2283. $(button).addClass("error")
  2284. .text("翻译出错")
  2285. .css("cursor", "pointer")
  2286. .prop("disabled", false);
  2287. $(target).remove();
  2288. }
  2289. return result;
  2290. }
  2291.  
  2292. function addConversionButton() {
  2293. // 题目页添加按钮
  2294. if (window.location.href.includes("problem")) {
  2295. var exContentsPageClasses = ["sample-tests",];
  2296. $('.problem-statement').children('div').each(function () {
  2297. var className = $(this).attr('class');
  2298. if (!exContentsPageClasses.includes(className)) {
  2299. var id = "_" + getRandomNumber(8);
  2300. addButtonPanel(this, id, "this_level");
  2301. addButtonWithHTML2MD(this, id, "this_level");
  2302. addButtonWithCopy(this, id, "this_level");
  2303. addButtonWithTranslation(this, id, "this_level");
  2304. }
  2305. });
  2306. }
  2307. // 添加按钮到ttypography部分
  2308. $(".ttypography").each(function () {
  2309. // 题目页特判
  2310. if (!$(this).parent().hasClass('problemindexholder')) {
  2311. let id = "_comment_" + getRandomNumber(8);
  2312. addButtonPanel(this, id, "this_level");
  2313. addButtonWithHTML2MD(this, id, "this_level");
  2314. addButtonWithCopy(this, id, "this_level");
  2315. addButtonWithTranslation(this, id, "this_level");
  2316. }
  2317. });
  2318.  
  2319. // 添加按钮到spoiler部分
  2320. $('.spoiler-content').each(function () {
  2321. if ($(this).find('.html2md-panel').length === 0) {
  2322. let id = "_spoiler_" + getRandomNumber(8);
  2323. addButtonPanel(this, id, "child_level");
  2324. addButtonWithHTML2MD(this, id, "child_level");
  2325. addButtonWithCopy(this, id, "child_level");
  2326. addButtonWithTranslation(this, id, "child_level");
  2327. }
  2328. });
  2329.  
  2330. // 添加按钮到titled部分
  2331. (function () {
  2332. var elements = [".Virtual.participation", ".Attention", ".Practice"];//只为部分titled添加
  2333. $.each(elements, function (index, value) {
  2334. $(value).each(function () {
  2335. let id = "_titled_" + getRandomNumber(8);
  2336. var $nextDiv = $(this).next().children().get(0);
  2337. addButtonPanel($nextDiv, id, "child_level", true);
  2338. addButtonWithTranslation($nextDiv, id, "child_level");
  2339. });
  2340. });
  2341. })();
  2342. if (is_mSite) {
  2343. $("div[class='_IndexPage_notice']").each(function () {
  2344. let id = "_titled_" + getRandomNumber(8);
  2345. addButtonPanel(this, id, "this_level", true);
  2346. addButtonWithTranslation(this, id, "this_level");
  2347. });
  2348. }
  2349.  
  2350. // 添加按钮到比赛QA部分
  2351. $(".question-response").each(function () {
  2352. let id = "_question_" + getRandomNumber(8);
  2353. addButtonPanel(this, id, "this_level", true);
  2354. addButtonWithTranslation(this, id, "this_level");
  2355. });
  2356. if (is_mSite) {
  2357. $("div._ProblemsPage_announcements table tbody tr:gt(0)").each(function () {
  2358. var $nextDiv = $(this).find("td:first");
  2359. let id = "_question_" + getRandomNumber(8);
  2360. addButtonPanel($nextDiv, id, "this_level", true);
  2361. addButtonWithTranslation($nextDiv, id, "this_level");
  2362. });
  2363. }
  2364.  
  2365. // 添加按钮到弹窗confirm-proto部分
  2366. $(".confirm-proto").each(function () {
  2367. let id = "_titled_" + getRandomNumber(8);
  2368. var $nextDiv = $(this).children().get(0);
  2369. addButtonPanel($nextDiv, id, "this_level", true);
  2370. addButtonWithTranslation($nextDiv, id, "this_level");
  2371. });
  2372.  
  2373. // 添加按钮到_CatalogHistorySidebarFrame_item部分
  2374. $("._CatalogHistorySidebarFrame_item").each(function () {
  2375. let id = "_history_sidebar_" + getRandomNumber(8);
  2376. addButtonPanel(this, id, "this_level", true);
  2377. addButtonWithTranslation(this, id, "this_level");
  2378. });
  2379.  
  2380. $(".problem-lock-link").on("click", function () {
  2381. // 找到.popup中的所有子孙div,并添加按钮
  2382. $(".popup .content div").each(function () {
  2383. let id = "_popup_" + getRandomNumber(8);
  2384. addButtonPanel(this, id, "this_level", true);
  2385. addButtonWithTranslation(this, id, "this_level");
  2386. });
  2387. });
  2388. };
  2389.  
  2390. //弹窗翻译
  2391. function alertZh() {
  2392. var _alert = window.alert;
  2393. window.alert = async function (msg) {
  2394. _alert(msg + "\n=========翻译=========\n" + await translate_deepl(msg));
  2395. return true;
  2396. }
  2397. };
  2398.  
  2399.  
  2400. // 展开折叠块
  2401. function ExpandFoldingblocks() {
  2402. if (expandFoldingblocks) {
  2403. $('.spoiler').addClass('spoiler-open');
  2404. $('.spoiler-content').attr('style', '');
  2405. }
  2406. };
  2407.  
  2408. // 跳转洛谷
  2409. async function CF2luogu() {
  2410. const getProblemId = () => {
  2411. const url = window.location.href;
  2412. const regex = url.includes('/contest/')
  2413. ? /\/contest\/(\d+)\/problem\/([A-Za-z\d]+)/
  2414. : /\/problemset\/problem\/(\d+)\/([A-Za-z\d]+)/;
  2415. const matchResult = url.match(regex);
  2416. return matchResult && matchResult.length >= 3
  2417. ? `${matchResult[1]}${matchResult[2]}`
  2418. : '';
  2419. };
  2420.  
  2421. const checkLinkExistence = (url) => {
  2422. return new Promise((resolve, reject) => {
  2423. GM.xmlHttpRequest({
  2424. method: "GET",
  2425. url,
  2426. headers: { "Range": "bytes=0-9999" }, // 获取前10KB数据
  2427. onload(response) {
  2428. if (response.responseText.match(/题目未找到/g)) {
  2429. resolve(false);
  2430. } else {
  2431. resolve(true);
  2432. }
  2433. },
  2434. onerror(error) {
  2435. reject(error);
  2436. }
  2437. });
  2438. });
  2439. };
  2440. const panelElement = $("<div>")
  2441. .addClass("html2md-panel")
  2442. .attr("id", "CF2luoguPanel")
  2443. .insertBefore('.problemindexholder');
  2444.  
  2445. const url = `https://www.luogu.com.cn/problem/CF${getProblemId()}`;
  2446. const result = await checkLinkExistence(url);
  2447. if (getProblemId() && result) {
  2448. const problemLink = $("<a>")
  2449. .attr("id", "problemLink")
  2450. .attr("href", url)
  2451. .attr("target", "_blank")
  2452. .html(`<button style="height: 25px;" class="html2mdButton"><img style="width:45px; margin-right:2px;" src="https://cdn.luogu.com.cn/fe/logo.png"></button>`);
  2453. panelElement.append(problemLink);
  2454. }
  2455. }
  2456.  
  2457. // 等待Latex渲染队列全部完成
  2458. function waitUntilIdleThenDo(callback) {
  2459. var intervalId = setInterval(function () {
  2460. var queue = MathJax.Hub.queue;
  2461. if (queue.pending === 0 && queue.running === 0) {
  2462. clearInterval(intervalId);
  2463. callback();
  2464. }
  2465. }, 100);
  2466. }
  2467.  
  2468. $(document).ready(function () {
  2469. var newElement = $("<div></div>")
  2470. .addClass("alert alert-info")
  2471. .html(`Codeforces Better! —— 正在等待页面资源加载……`)
  2472. .css({
  2473. "margin": "1em",
  2474. "text-align": "center",
  2475. "font-weight": "600",
  2476. "position": "relative"
  2477. });
  2478. var tip_SegmentedTranslation = $("<div></div>")
  2479. .addClass("alert alert-error")
  2480. .html(`Codeforces Better! —— 注意!分段翻译已开启,这会造成负面效果,
  2481. <p>除非你现在需要翻译超长篇的博客或者题目,否则请前往设置关闭分段翻译</p>`)
  2482. .css({
  2483. "margin": "1em",
  2484. "text-align": "center",
  2485. "font-weight": "600",
  2486. "position": "relative"
  2487. });
  2488.  
  2489. function processPage() {
  2490. if (showLoading) newElement.html('Codeforces Better! —— 正在等待Latex渲染队列全部完成……');
  2491. waitUntilIdleThenDo(function () {
  2492. if (enableSegmentedTranslation) $(".menu-box:first").next().after(tip_SegmentedTranslation); //显示分段翻译警告
  2493. if (showJumpToLuogu) CF2luogu();
  2494. ExpandFoldingblocks();
  2495. addConversionButton();
  2496. alertZh();
  2497. if (showLoading) {
  2498. newElement.html('Codeforces Better! —— 加载已完成');
  2499. newElement.removeClass('alert-info').addClass('alert-success');
  2500. setTimeout(function () {
  2501. newElement.remove();
  2502. }, 3000);
  2503. }
  2504. });
  2505. }
  2506.  
  2507. if (showLoading) $(".menu-box:first").next().after(newElement);
  2508.  
  2509. if (loaded) {
  2510. processPage();
  2511. } else {
  2512. // 页面完全加载完成后执行
  2513. window.onload = function () {
  2514. processPage();
  2515. };
  2516. }
  2517. })
  2518.  
  2519. // 字数超限确认
  2520. function showWordsExceededDialog(button) {
  2521. return new Promise(resolve => {
  2522. const styleElement = GM_addStyle(darkenPageStyle);
  2523. $(button).removeClass("translated");
  2524. $(button).text("字数超限");
  2525. $(button).css("cursor", "not-allowed");
  2526. $(button).prop("disabled", true);
  2527. let htmlString = `
  2528. <div class="wordsExceeded">
  2529. <h2>字数超限!</h2>
  2530. <p>注意,即将翻译的内容字数超过了4950个字符,您可能选择了错误的翻译按钮</p>
  2531. <div style="display:flex; padding:5px 0px; align-items: center;">
  2532. `+ helpCircleHTML + `
  2533. <p>
  2534. 由于实现方式,区域中会出现多个翻译按钮,请点击更小的子区域中的翻译按钮,
  2535. <br>或者在设置面板中开启 分段翻译 后重试。
  2536. </p>
  2537. </div>
  2538. <p>对于免费的接口,大量请求可能导致你的IP被暂时禁止访问,对于GPT,会消耗大量的token</p>
  2539. <p>您确定要继续翻译吗?</p>
  2540. <div style="display:flex; padding-top:10px">
  2541. <button id="continueButton">继续</button><button id="cancelButton">取消</button>
  2542. </div>
  2543. </div>
  2544. `;
  2545. $('body').before(htmlString);
  2546. $("#continueButton").click(function () {
  2547. $(styleElement).remove();
  2548. $('.wordsExceeded').remove();
  2549. resolve(true);
  2550. });
  2551. $("#cancelButton").click(function () {
  2552. $(styleElement).remove();
  2553. $('.wordsExceeded').remove();
  2554. resolve(false);
  2555. });
  2556. });
  2557. }
  2558.  
  2559. //跳过折叠块确认
  2560. function skiFoldingBlocks() {
  2561. return new Promise(resolve => {
  2562. const styleElement = GM_addStyle(darkenPageStyle);
  2563. let htmlString = `
  2564. <div class="wordsExceeded">
  2565. <h2>是否跳过折叠块?</h2>
  2566. <p></p>
  2567. <div style="display:grid; padding:5px 0px; align-items: center;">
  2568. <p>
  2569. 即将翻译的区域中包含折叠块,折叠块可能是代码,通常不需要翻译,现在您需要选择是否跳过这些折叠块,
  2570. </p>
  2571. <p>
  2572. 如果其中有您需要翻译的折叠块,可以稍后再单独点击这些折叠块内的翻译按钮进行翻译
  2573. </p>
  2574. </div>
  2575. <p>要跳过折叠块吗?(建议选择跳过)</p>
  2576. <div style="display:flex; padding-top:10px">
  2577. <button id="cancelButton">否</button><button id="skipButton">跳过</button>
  2578. </div>
  2579. </div>
  2580. `;
  2581. $('body').before(htmlString);
  2582. $("#skipButton").click(function () {
  2583. $(styleElement).remove();
  2584. $('.wordsExceeded').remove();
  2585. resolve(true);
  2586. });
  2587. $("#cancelButton").click(function () {
  2588. $(styleElement).remove();
  2589. $('.wordsExceeded').remove();
  2590. resolve(false);
  2591. });
  2592. });
  2593. }
  2594.  
  2595. // 翻译框/翻译处理器
  2596. var translatedText = "";
  2597. async function translateProblemStatement(text, element_node, button) {
  2598. let status = 0;
  2599. let id = getRandomNumber(8);
  2600. let matches = [];
  2601. let replacements = {};
  2602. // 创建元素并放在element_node的后面
  2603. const translateDiv = document.createElement('div');
  2604. translateDiv.setAttribute('id', id);
  2605. translateDiv.classList.add('translate-problem-statement');
  2606. const spanElement = document.createElement('span');
  2607. translateDiv.appendChild(spanElement);
  2608. element_node.insertAdjacentElement('afterend', translateDiv);
  2609. // 替换latex公式
  2610. if (is_oldLatex) {
  2611. //去除开头结尾的<p>标签
  2612. text = text.replace(/^<p>/i, "");
  2613. text = text.replace(/<\/p>$/i, "");
  2614. //
  2615. let i = 0;
  2616. let regex = /<span\s+class="tex-span">.*?<\/span>/gi;
  2617. matches = text.match(regex);
  2618. try {
  2619. for (i; i < matches.length; i++) {
  2620. let match = matches[i];
  2621. text = text.replace(match, `【${i + 1}】`);
  2622. replacements[`【${i + 1}】`] = match;
  2623. }
  2624. } catch (e) { }
  2625. } else if (translation != "api2d" && translation != "openai") {
  2626. // 使用GPT翻译时不必替换latex公式
  2627. let i = 0;
  2628. // 块公式
  2629. matches = matches.concat(text.match(/\$\$([\s\S]*?)\$\$/g));
  2630. try {
  2631. for (i; i < matches.length; i++) {
  2632. let match = matches[i];
  2633. text = text.replace(match, `【${i + 1}】`);
  2634. replacements[`【${i + 1}】`] = match;
  2635. }
  2636. } catch (e) { }
  2637. // 行内公式
  2638. matches = matches.concat(text.match(/\$(.*?)\$/g));
  2639. try {
  2640. for (i; i < matches.length; i++) {
  2641. let match = matches[i];
  2642. text = text.replace(match, `【${i + 1}】`);
  2643. replacements[`【${i + 1}】`] = match;
  2644. }
  2645. } catch (e) { }
  2646. }
  2647.  
  2648. console.log(text.length);
  2649.  
  2650. if (text.length > 4950) {
  2651. const shouldContinue = await showWordsExceededDialog(button);
  2652. if (!shouldContinue) {
  2653. status = 1;
  2654. return {
  2655. translateDiv: translateDiv,
  2656. status: status
  2657. };
  2658. }
  2659. }
  2660. // 翻译
  2661. if (translation == "deepl") {
  2662. translateDiv.innerHTML = "正在翻译中……请稍等";
  2663. translatedText = await translate_deepl(text);
  2664. } else if (translation == "youdao") {
  2665. translateDiv.innerHTML = "正在翻译中……请稍等";
  2666. translatedText = await translate_youdao_mobile(text);
  2667. } else if (translation == "google") {
  2668. translateDiv.innerHTML = "正在翻译中……请稍等";
  2669. translatedText = await translate_gg(text);
  2670. } else if (translation == "openai") {
  2671. try {
  2672. translateDiv.innerHTML = "正在翻译中……<br><br>使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待";
  2673. translatedText = await translate_openai(text);
  2674. } catch (error) {
  2675. status = 2;
  2676. translatedText = error;
  2677. }
  2678. } else if (translation == "api2d") {
  2679. try {
  2680. translateDiv.innerHTML = "正在翻译中……<br><br>使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待";
  2681. translatedText = await translate_api2d(text);
  2682. } catch (error) {
  2683. status = 2;
  2684. translatedText = error;
  2685. }
  2686. }
  2687. if (/^翻译出错/.test(translatedText)) status = 2;
  2688. // 还原latex公式
  2689. if (is_oldLatex) {
  2690. translatedText = "<p>" + translatedText;
  2691. translatedText += "</p>";
  2692. try {
  2693. for (let i = 0; i < matches.length; i++) {
  2694. let match = matches[i];
  2695. let replacement = replacements[`【${i + 1}】`];
  2696. let regex;
  2697. regex = new RegExp(`【\\s*${i + 1}\\s*】`, 'g');
  2698. translatedText = translatedText.replace(regex, replacement);
  2699. regex = new RegExp(`\\[\\s*${i + 1}\\s*\\]`, 'g');
  2700. translatedText = translatedText.replace(regex, replacement);
  2701. regex = new RegExp(`【\\s*${i + 1}[^】\\d]`, 'g');
  2702. translatedText = translatedText.replace(regex, replacement);
  2703. regex = new RegExp(`[^【\\d]${i + 1}\\s*】`, 'g');
  2704. translatedText = translatedText.replace(regex, " " + replacement);
  2705. }
  2706. } catch (e) { }
  2707. }
  2708. else if (translation != "api2d" && translation != "openai") {
  2709. try {
  2710. for (let i = 0; i < matches.length; i++) {
  2711. let match = matches[i];
  2712. let replacement = replacements[`【${i + 1}】`];
  2713. let regex;
  2714. regex = new RegExp(`【\\s*${i + 1}\\s*】`, 'g');
  2715. translatedText = translatedText.replace(regex, replacement);
  2716. regex = new RegExp(`\\[\\s*${i + 1}\\s*\\]`, 'g');
  2717. translatedText = translatedText.replace(regex, replacement);
  2718. regex = new RegExp(`【\\s*${i + 1}[^】\\d]`, 'g');
  2719. translatedText = translatedText.replace(regex, replacement);
  2720. regex = new RegExp(`[^【\\d]${i + 1}\\s*】`, 'g');
  2721. translatedText = translatedText.replace(regex, " " + replacement);
  2722. }
  2723. } catch (e) { }
  2724. }
  2725.  
  2726. // 结果复制按钮
  2727. if (!is_oldLatex) {
  2728. // 创建一个隐藏的元素来保存 translatedText 的值
  2729. var textElement = document.createElement("div");
  2730. textElement.style.display = "none";
  2731. textElement.textContent = translatedText;
  2732. translateDiv.parentNode.insertBefore(textElement, translateDiv);
  2733.  
  2734. // 按钮
  2735. var copyButton = document.createElement("button");
  2736. copyButton.textContent = "Copy";
  2737. var wrapperDiv = document.createElement("div");
  2738. $(wrapperDiv).css({
  2739. display: "flex",
  2740. justifyContent: "flex-end"
  2741. });
  2742. $(wrapperDiv).append(copyButton);
  2743. $(copyButton).addClass("html2mdButton html2md-cb");
  2744.  
  2745. copyButton.addEventListener("click", function () {
  2746. var translatedText = textElement.textContent;
  2747. GM_setClipboard(translatedText);
  2748. $(this).addClass("copied").text("Copied");
  2749. // 更新复制按钮文本
  2750. setTimeout(() => {
  2751. $(this).removeClass("copied");
  2752. $(this).text("Copy");
  2753. }, 2000);
  2754. });
  2755. translateDiv.parentNode.insertBefore(wrapperDiv, translateDiv);
  2756. }
  2757.  
  2758. // 转义LaTex中的特殊符号
  2759. if (!is_oldLatex) {
  2760. const escapeRules = [
  2761. { pattern: /(?<!\\)>(?!\s)/g, replacement: " &gt; " }, // >符号
  2762. { pattern: /(?<!\\)</g, replacement: " &lt; " }, // <符号
  2763. { pattern: /(?<!\\)\*/g, replacement: " &#42; " }, // *符号
  2764. { pattern: /(?<!\\)& /g, replacement: "\\&" }, // &符号
  2765. ];
  2766.  
  2767. let latexMatches = [...translatedText.matchAll(/\$\$([\s\S]*?)\$\$|\$(.*?)\$/g)];
  2768.  
  2769. for (const match of latexMatches) {
  2770. const matchedText = match[0];
  2771.  
  2772. for (const rule of escapeRules) {
  2773. const escapedText = matchedText.replaceAll(rule.pattern, rule.replacement);
  2774. translatedText = translatedText.replace(matchedText, escapedText);
  2775. }
  2776. }
  2777. }
  2778.  
  2779. // 使符合mathjx的转换语法
  2780. const ruleMap = [
  2781. { pattern: /(\s_[\u4e00-\u9fa5]+_)([\u4e00-\u9fa5]+)/g, replacement: "$1 $2" }, // 斜体
  2782. { pattern: /(_[\u4e00-\u9fa5]+_\s)([\u4e00-\u9fa5]+)/g, replacement: " $1$2" },
  2783. { pattern: /(_[\u4e00-\u9fa5]+_)([\u4e00-\u9fa5]+)/g, replacement: " $1 $2" },
  2784. { pattern: /(\$\$[\r\n])/g, replacement: "$$$$$$$$$$$$" }, // $$ 行间
  2785. { pattern: /(?<!\$)\$(?!\$)/g, replacement: "$$$$$" }, // $ 内联
  2786. ];
  2787. ruleMap.forEach(({ pattern, replacement }) => {
  2788. translatedText = translatedText.replace(pattern, replacement);
  2789. });
  2790.  
  2791. // 更新
  2792. if (is_oldLatex) {
  2793. // oldlatex
  2794. translatedText = $.parseHTML(translatedText);
  2795. $(translateDiv).empty().append($(translatedText));
  2796. return {
  2797. translateDiv: translateDiv,
  2798. status: status
  2799. };
  2800. } else {
  2801. // 渲染MarkDown
  2802. var md = window.markdownit();
  2803. var html = md.render(translatedText);
  2804. translateDiv.innerHTML = html;
  2805. // // 渲染Latex
  2806. MathJax.Hub.Queue(["Typeset", MathJax.Hub, translateDiv]);
  2807. return {
  2808. translateDiv: translateDiv,
  2809. status: status,
  2810. copyDiv: textElement,
  2811. copyButton: copyButton
  2812. };
  2813. }
  2814.  
  2815. }
  2816.  
  2817. // ChatGPT
  2818. async function translate_openai(raw) {
  2819. var openai_key = GM_getValue("openai_key");
  2820. var openai_retext = "";
  2821. var data;
  2822. if (is_oldLatex) {
  2823. data = {
  2824. model: openai_model,
  2825. messages: [{
  2826. role: "user",
  2827. content: "(请将下面的文本翻译为中文,这是一道编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的【】、HTML标签本身以及其中的内容不翻译不变动,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw + ")"
  2828. }],
  2829. temperature: 0.7
  2830. };
  2831. } else {
  2832. data = {
  2833. model: openai_model,
  2834. messages: [{
  2835. role: "user",
  2836. content: "(请将下面的文本翻译为中文,这是一道编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw + ")"
  2837. }],
  2838. temperature: 0.7
  2839. };
  2840. };
  2841. return new Promise(function (resolve, reject) {
  2842. GM_xmlhttpRequest({
  2843. method: 'POST',
  2844. url: (showOpneAiAdvanced && GM_getValue("openai_proxy") !== null && GM_getValue("openai_proxy") !== "") ? GM_getValue("openai_proxy") : 'https://api.openai.com/v1/chat/completions', // Use the chat endpoint here
  2845.  
  2846. data: JSON.stringify(data),
  2847. headers: {
  2848. 'Content-Type': 'application/json',
  2849. 'Authorization': 'Bearer ' + GM_getValue("openai_key")
  2850. },
  2851. responseType: 'json',
  2852. onload: function (response) {
  2853. if (!response.response) {
  2854. reject("发生了未知的错误,如果你启用了代理API,请确认是否填写正确,并确保代理能够正常工作。\n\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈 请注意打码响应报文的敏感部分\n\n响应报文:" + JSON.stringify(response));
  2855. }
  2856. else if (!response.response.choices || response.response.choices.length < 1 || !response.response.choices[0].message) {
  2857. resolve("翻译出错,请重试\n\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈 \n\n报错信息:" + JSON.stringify(response.response, null, '\n'));
  2858. } else {
  2859. openai_retext = response.response.choices[0].message.content;
  2860. resolve(openai_retext);
  2861. }
  2862. },
  2863. onerror: function (response) {
  2864. reject("发生了未知的错误,请确认你是否能正常访问OpenAi的接口,如果使用代理API,请检查是否正常工作\n\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈 请注意打码响应报文的敏感部分\n\n响应报文:" + JSON.stringify(response));
  2865. },
  2866. });
  2867. });
  2868. }
  2869.  
  2870. // api2d
  2871. async function translate_api2d(raw) {
  2872. var api2d_key = GM_getValue("api2d_key");
  2873. var api2d_retext = "";
  2874. var postData;
  2875. if (is_oldLatex) {
  2876. postData = JSON.stringify({
  2877. model: api2d_model,
  2878. messages: [{ role: 'user', content: '请帮我将下面的文本翻译为中文,这是一道编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的【】、HTML标签本身以及其中的内容不翻译不变动,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n' + raw }],
  2879. temperature: 0.7
  2880. });
  2881. } else {
  2882. postData = JSON.stringify({
  2883. model: api2d_model,
  2884. messages: [{ role: 'user', content: '请帮我将下面的文本翻译为中文,这是一道编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n' + raw }],
  2885. temperature: 0.7
  2886. });
  2887. }
  2888. const options = {
  2889. method: 'POST',
  2890. headers: {
  2891. 'Content-Type': 'application/json',
  2892. 'Authorization': 'Bearer ' + api2d_key,
  2893. ...(x_api2d_no_cache ? {} : { 'x-api2d-no-cache': 1 })
  2894. },
  2895. data: postData,
  2896. };
  2897.  
  2898. return new Promise(function (resolve, reject) {
  2899. GM_xmlhttpRequest({
  2900. method: options.method,
  2901. url: api2d_request_entry + `/v1/chat/completions`,
  2902. headers: options.headers,
  2903. data: options.data,
  2904. responseType: 'json',
  2905. onload: function (response) {
  2906. if (!response.response.choices || response.response.choices.length < 1 || !response.response.choices[0].message) {
  2907. resolve("翻译出错,请重试\n\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈 \n\n报错信息:" + JSON.stringify(response.response, null, '\n'));
  2908. } else {
  2909. api2d_retext = response.response.choices[0].message.content;
  2910. resolve(api2d_retext);
  2911. }
  2912. },
  2913. onerror: function (response) {
  2914. reject("发生了未知的错误,请检查请求入口地址是否正确,能否正常访问\n\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈 请注意打码响应报文的敏感部分\n\n响应报文:" + JSON.stringify(response));
  2915. },
  2916. });
  2917. });
  2918. }
  2919. //
  2920.  
  2921. //--谷歌翻译--start
  2922. async function translate_gg(raw) {
  2923. return new Promise((resolve, reject) => {
  2924. const url = 'https://translate.google.com/m';
  2925. const params = `tl=zh-CN&q=${encodeURIComponent(raw)}`;
  2926.  
  2927. GM_xmlhttpRequest({
  2928. method: 'GET',
  2929. url: `${url}?${params}`,
  2930. onload: function (response) {
  2931. const html = response.responseText;
  2932. const translatedText = $(html).find('.result-container').text();
  2933. resolve(translatedText);
  2934. },
  2935. onerror: function (error) {
  2936. console.error('Error:', error);
  2937. reject(error);
  2938. }
  2939. });
  2940. });
  2941. }
  2942. //--谷歌翻译--end
  2943.  
  2944. //--有道翻译m--start
  2945. async function translate_youdao_mobile(raw) {
  2946. const options = {
  2947. method: "POST",
  2948. url: 'http://m.youdao.com/translate',
  2949. data: "inputtext=" + encodeURIComponent(raw) + "&type=AUTO",
  2950. anonymous: true,
  2951. headers: {
  2952. "Content-Type": "application/x-www-form-urlencoded",
  2953. 'Host': 'm.youdao.com',
  2954. 'Origin': 'http://m.youdao.com',
  2955. 'Referer': 'http://m.youdao.com/translate',
  2956. }
  2957. }
  2958. return await BaseTranslate('有道翻译mobile', raw, options, res => /id="translateResult">\s*?<li>([\s\S]*?)<\/li>\s*?<\/ul/.exec(res)[1])
  2959. }
  2960. //--有道翻译m--end
  2961.  
  2962. //--Deepl翻译--start
  2963. function getTimeStamp(iCount) {
  2964. const ts = Date.now();
  2965. if (iCount !== 0) {
  2966. iCount = iCount + 1;
  2967. return ts - (ts % iCount) + iCount;
  2968. } else {
  2969. return ts;
  2970. }
  2971. }
  2972.  
  2973. async function translate_deepl(raw) {
  2974. const id = (Math.floor(Math.random() * 99999) + 100000) * 1000;
  2975. const data = {
  2976. jsonrpc: '2.0',
  2977. method: 'LMT_handle_texts',
  2978. id,
  2979. params: {
  2980. splitting: 'newlines',
  2981. lang: {
  2982. source_lang_user_selected: 'auto',
  2983. target_lang: 'ZH',
  2984. },
  2985. texts: [{
  2986. text: raw,
  2987. requestAlternatives: 3
  2988. }],
  2989. timestamp: getTimeStamp(raw.split('i').length - 1)
  2990. }
  2991. }
  2992. let postData = JSON.stringify(data);
  2993. if ((id + 5) % 29 === 0 || (id + 3) % 13 === 0) {
  2994. postData = postData.replace('"method":"', '"method" : "');
  2995. } else {
  2996. postData = postData.replace('"method":"', '"method": "');
  2997. }
  2998. const options = {
  2999. method: 'POST',
  3000. url: 'https://www2.deepl.com/jsonrpc',
  3001. data: postData,
  3002. headers: {
  3003. 'Content-Type': 'application/json',
  3004. 'Host': 'www2.deepl.com',
  3005. 'Origin': 'https://www.deepl.com',
  3006. 'Referer': 'https://www.deepl.com/',
  3007. },
  3008. anonymous: true,
  3009. nocache: true,
  3010. }
  3011. return await BaseTranslate('Deepl翻译', raw, options, res => JSON.parse(res).result.texts[0].text)
  3012. }
  3013.  
  3014. //--Deepl翻译--end
  3015.  
  3016. //--异步请求包装工具--start
  3017. async function PromiseRetryWrap(task, options, ...values) {
  3018. const { RetryTimes, ErrProcesser } = options || {};
  3019. let retryTimes = RetryTimes || 5;
  3020. const usedErrProcesser = ErrProcesser || (err => { throw err });
  3021. if (!task) return;
  3022. while (true) {
  3023. try {
  3024. return await task(...values);
  3025. } catch (err) {
  3026. if (!--retryTimes) {
  3027. console.log(err);
  3028. return usedErrProcesser(err);
  3029. }
  3030. }
  3031. }
  3032. }
  3033.  
  3034. async function BaseTranslate(name, raw, options, processer) {
  3035. let errtext;
  3036. const toDo = async () => {
  3037. var tmp;
  3038. try {
  3039. const data = await Request(options);
  3040. tmp = data.responseText;
  3041. const result = await processer(tmp);
  3042. if (result) sessionStorage.setItem(name + '-' + raw, result);
  3043. return result
  3044. } catch (err) {
  3045. errtext = tmp;
  3046. throw {
  3047. responseText: tmp,
  3048. err: err
  3049. }
  3050. }
  3051. }
  3052. return await PromiseRetryWrap(toDo, { RetryTimes: 3, ErrProcesser: () => "翻译出错,请重试或更换翻译接口\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈 请注意打码报错信息的敏感部分\n\n报错信息:" + errtext })
  3053. }
  3054.  
  3055. function Request(options) {
  3056. return new Promise((reslove, reject) => GM_xmlhttpRequest({ ...options, onload: reslove, onerror: reject }))
  3057. }
  3058.  
  3059. //--异步请求包装工具--end