Codeforces Better!

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

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

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