Codeforces Better!

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

目前为 2023-07-30 提交的版本。查看 最新版本

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