Codeforces Better!

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

目前为 2023-06-14 提交的版本。查看 最新版本

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