Codeforces Better!

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

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

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