Codeforces Better!

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

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

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