Codeforces Better!

Codeforces界面汉化、题目翻译,markdown视图,一键复制题目

当前为 2023-05-23 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Codeforces Better!
  3. // @namespace https://gf.qytechs.cn/users/747162
  4. // @version 1.28
  5. // @description Codeforces界面汉化、题目翻译,markdown视图,一键复制题目
  6. // @author 北极小狐
  7. // @match https://codeforces.com/*
  8. // @connect www2.deepl.com
  9. // @connect m.youdao.com
  10. // @connect openai.api2d.net
  11. // @connect api.openai.com
  12. // @grant GM_xmlhttpRequest
  13. // @grant GM_info
  14. // @grant GM_setValue
  15. // @grant GM_getValue
  16. // @connect gf.qytechs.cn
  17. // @icon https://aowuucdn.oss-cn-beijing.aliyuncs.com/codeforces.png
  18. // @require https://cdn.staticfile.org/turndown/7.1.2/turndown.min.js
  19. // @require https://cdn.staticfile.org/markdown-it/13.0.1/markdown-it.min.js
  20. // @license MIT
  21. // ==/UserScript==
  22. // 样式
  23. function loadCssCode(code) {
  24. var style = document.createElement('style');
  25. style.type = 'text/css';
  26. style.rel = 'stylesheet';
  27. style.appendChild(document.createTextNode(code));
  28. var head = document.getElementsByTagName('head')[0];
  29. head.appendChild(style);
  30. }
  31. loadCssCode(`
  32. span.mdViewContent {
  33. white-space: pre-wrap;
  34. }
  35. /*翻译div*/
  36. .translate-problem-statement {
  37. display: grid;
  38. justify-items: start;
  39. white-space: pre-wrap;
  40. letter-spacing: 1.4px;
  41. border: 1px dashed #00aeeccc;
  42. border-radius: 0.3rem;
  43. padding: 5px;
  44. margin: 10px 0px;
  45. font-size: 13px;
  46. }
  47. .translate-problem-statement a {
  48. color: #4d87c7;
  49. background: 0 0;
  50. text-decoration: none;
  51. }
  52. .translate-problem-statement a:hover {
  53. background-color: #800;
  54. color: #fff;
  55. text-decoration: none;
  56. }
  57. .html2md-panel {
  58. display: flex;
  59. justify-content: flex-end;
  60. }
  61. button.html2mdButton {
  62. cursor: pointer;
  63. background-color: #e6e6e6;
  64. color: #727378;
  65. height: 22px;
  66. width: auto;
  67. font-size: 13px;
  68. border-radius: 0.3rem;
  69. border: none;
  70. padding: 1px 5px;
  71. margin: 5px;
  72. box-shadow: 0 0 1px #0000004d;
  73. }
  74. button.html2mdButton.copied {
  75. background-color: #07e65196;
  76. color: #104f2b;
  77. }
  78. button.html2mdButton.mdViewed {
  79. background-color: #ff980057;
  80. color: #5a3a0c;
  81. }
  82. button.translated {
  83. cursor: not-allowed;
  84. background-color: #2a6dc296;
  85. color: #fffdfd;
  86. }
  87. button.html2mdButton.reTranslation {
  88. background-color: #faebd7;
  89. }
  90. .translate-problem-statement table {
  91. border: 1px #ccc solid;
  92. border-collapse: collapse;
  93. margin: 1.3571em 0 0;
  94. color: #222;
  95. }
  96. .translate-problem-statement table td {
  97. border-right: 1px solid #ccc;
  98. border-top: 1px solid #ccc;
  99. padding: 0.7143em 0.5em;
  100. }
  101. .translate-problem-statement table th {
  102. padding: 0.7143em 0.5em;
  103. }
  104. .translate-problem-statement p:not(:first-child) {
  105. margin: 1.5em 0 0;
  106. }
  107. /*设置面板*/
  108. button.html2mdButton.CFBetter_setting {
  109. float: right;
  110. height: 30px;
  111. background: #60a5fa;
  112. color: white;
  113. box-shadow: 0px 0px 1px 1px #0000004d;
  114. margin: 10px;
  115. }
  116. #CFBetter_setting_menu {
  117. z-index: 9999;
  118. border-radius: 0.5rem;
  119. box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  120. display: grid;
  121. position: fixed;
  122. top: 50%;
  123. left: 50%;
  124. width: 270px;
  125. transform: translate(-50%, -50%);
  126. border-radius: 16px;
  127. background-color: #ecf0ff;
  128. border: 6px solid #ffffff;
  129. color: #697e91;
  130. padding: 10px 20px 20px 20px;
  131. }
  132.  
  133. /*设置面板-关闭按钮*/
  134. #CFBetter_setting_menu .tool-box {
  135. position: absolute;
  136. display: flex;
  137. align-items: center;
  138. justify-content: center;
  139. width: 2.5rem;
  140. height: 2.5rem;
  141. top: 3px;
  142. right: 3px;
  143. }
  144.  
  145. #CFBetter_setting_menu .btn-close {
  146. display: flex;
  147. align-items: center;
  148. justify-content: center;
  149. text-align: center;
  150. width: 2rem;
  151. height: 2rem;
  152. color: transparent;
  153. font-size: 0;
  154. cursor: pointer;
  155. background-color: #ff000080;
  156. border: none;
  157. border-radius: 10px;
  158. transition: .2s ease all;
  159. }
  160.  
  161. #CFBetter_setting_menu .btn-close:hover {
  162. width: 2rem;
  163. height: 2rem;
  164. font-size: 1rem;
  165. color: #ffffff;
  166. background-color: #ff0000cc;
  167. box-shadow: 0 5px 5px 0 #00000026;
  168. }
  169.  
  170. #CFBetter_setting_menu .btn-close:active {
  171. width: .9rem;
  172. height: .9rem;
  173. font-size: .9rem;
  174. color: #ffffffde;
  175. --shadow-btn-close: 0 3px 3px 0 #00000026;
  176. box-shadow: var(--shadow-btn-close);
  177. }
  178.  
  179. /*设置面板-checkbox*/
  180. #CFBetter_setting_menu input[type=checkbox]:focus {
  181. outline: 0px;
  182. }
  183.  
  184. #CFBetter_setting_menu input[type="checkbox"] {
  185. margin: 0px;
  186. appearance: none;
  187. width: 48px;
  188. height: 24px;
  189. border: 2px solid #6b8092;
  190. border-radius: 20px;
  191. background: #f1e1e1;
  192. position: relative;
  193. box-sizing: border-box;
  194. }
  195.  
  196. #CFBetter_setting_menu input[type="checkbox"]::before {
  197. content: "";
  198. width: 16px;
  199. height: 16px;
  200. background: #6b80927a;
  201. border: 2px solid #6b8092;
  202. border-radius: 50%;
  203. position: absolute;
  204. top: 0;
  205. left: 0;
  206. transform: translate(0%, 0%);
  207. transition: all 0.3s ease-in-out;
  208. }
  209.  
  210. #CFBetter_setting_menu input[type="checkbox"]::after {
  211. 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");
  212. position: absolute;
  213. top: 0;
  214. left: 24px;
  215. }
  216.  
  217. #CFBetter_setting_menu input[type="checkbox"]:checked {
  218. border: 2px solid #02c202;
  219. background: #e2f1e1;
  220. }
  221.  
  222. #CFBetter_setting_menu input[type="checkbox"]:checked::before {
  223. background: rgba(2, 194, 2, 0.5);
  224. border: 2px solid #02c202;
  225. transform: translate(119%, 0%);
  226. transition: all 0.3s ease-in-out;
  227. }
  228.  
  229. #CFBetter_setting_menu input[type="checkbox"]:checked::after {
  230. content: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='15' height='13' 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='%2302C202' fill-opacity='0.9'/%3E%3C/svg%3E");
  231. position: absolute;
  232. top: 3px;
  233. left: 4px;
  234. }
  235.  
  236. #CFBetter_setting_menu input[type="checkbox"] + label {
  237. margin: 0px 0px 0px 10px !important;
  238. font-size: 16px;
  239. }
  240.  
  241. .CFBetter_setting_list {
  242. display: flex;
  243. align-items: center;
  244. margin-bottom: 18px;
  245. }
  246.  
  247. /*设置面板-radio*/
  248. #CFBetter_setting_menu>label {
  249. display: flex;
  250. list-style-type: none;
  251. padding-inline-start: 0px;
  252. overflow-x: auto;
  253. max-width: 100%;
  254. margin: 0px;
  255. align-items: center;
  256. margin: 3px 0px;
  257. }
  258.  
  259. .CFBetter_setting_menu_label_text {
  260. border: 1px dashed #00aeeccc;
  261. display: block;
  262. height: 20px;
  263. width: 100%;
  264. color: gray;
  265. font-weight: 300;
  266. font-size: 14px;
  267. letter-spacing: 2px;
  268. padding: 7px;
  269. }
  270.  
  271. input[type="radio"]:checked+.CFBetter_setting_menu_label_text {
  272. background: #41e49930;
  273. border: 1px solid green;
  274. color: green;
  275. font-weight: 500;
  276. }
  277.  
  278. #CFBetter_setting_menu>label input[type="radio"] {
  279. -webkit-appearance: none;
  280. appearance: none;
  281. list-style: none;
  282. margin: 0px;
  283. }
  284.  
  285. #CFBetter_setting_menu input[type="text"] {
  286. display: block;
  287. height: 25px;
  288. background-color: #ffffff;
  289. color: #727378;
  290. font-size: 10px;
  291. border-radius: 0.3rem;
  292. padding: 1px 5px;
  293. margin: 5px 0px 5px 0px;
  294. border: 1px solid #00aeeccc;
  295. box-shadow: 0 0 1px #0000004d;
  296. }
  297.  
  298. .CFBetter_setting_menu_input {
  299. width: 100%;
  300. display: grid;
  301. justify-content: start;
  302. }
  303.  
  304. #CFBetter_setting_menu #save {
  305. cursor: pointer;
  306. display: inline-flex;
  307. padding: 0.5rem 1rem;
  308. background-color: #1aa06d;
  309. color: #ffffff;
  310. font-size: 1rem;
  311. line-height: 1.5rem;
  312. font-weight: 500;
  313. justify-content: center;
  314. width: 100%;
  315. border-radius: 0.375rem;
  316. border: none;
  317. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  318. }
  319.  
  320. #CFBetter_setting_menu span.tip {
  321. color: red;
  322. font-size: 2px;
  323. font-weight: 500;
  324. padding: 0px 0px 10px 0px;
  325. }
  326. /*更新检查*/
  327. div#update_panel {
  328. position: fixed;
  329. top: 50%;
  330. left: 50%;
  331. width: 240px;
  332. transform: translate(-50%, -50%);
  333. background-color: #fdfdfd;
  334. border: 1px solid #00aeeccc;
  335. border-radius: 5px;
  336. box-shadow: 2px 2px 3px 1px #0000004d;
  337. padding: 10px 20px 20px 20px;
  338. color: #444242;
  339. background-color: #ecf0ff;
  340. border: 6px solid #ffffff;
  341. border-radius: 16px;
  342. }
  343. div#update_panel #updating {
  344. cursor: pointer;
  345. display: inline-flex;
  346. padding: 0px;
  347. background-color: #1aa06d;
  348. color: #ffffff;
  349. font-size: 1rem;
  350. line-height: 1.5rem;
  351. font-weight: 500;
  352. justify-content: center;
  353. width: 100%;
  354. border-radius: 0.375rem;
  355. border: none;
  356. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  357. }
  358. div#update_panel #updating a {
  359. text-decoration: none;
  360. color: white;
  361. display: flex;
  362. position: inherit;
  363. top: 0;
  364. left: 0;
  365. width: 100%;
  366. height: 22px;
  367. font-size: 14px;
  368. justify-content: center;
  369. align-items: center;
  370. }
  371. `);
  372.  
  373. // 更新检查
  374. (function checkScriptVersion() {
  375. function compareVersions(version1 = "0", version2 = "0") {
  376. const v1Array = String(version1).split(".");
  377. const v2Array = String(version2).split(".");
  378. const minLength = Math.min(v1Array.length, v2Array.length);
  379. let result = 0;
  380. for (let i = 0; i < minLength; i++) {
  381. const curV1 = Number(v1Array[i]);
  382. const curV2 = Number(v2Array[i]);
  383. if (curV1 > curV2) {
  384. result = 1;
  385. break;
  386. } else if (curV1 < curV2) {
  387. result = -1;
  388. break;
  389. }
  390. }
  391. if (result === 0 && v1Array.length !== v2Array.length) {
  392. const v1IsBigger = v1Array.length > v2Array.length;
  393. const maxLenArray = v1IsBigger ? v1Array : v2Array;
  394. for (let i = minLength; i < maxLenArray.length; i++) {
  395. const curVersion = Number(maxLenArray[i]);
  396. if (curVersion > 0) {
  397. v1IsBigger ? result = 1 : result = -1;
  398. break;
  399. }
  400. }
  401. }
  402. return result;
  403. }
  404.  
  405. GM_xmlhttpRequest({
  406. method: "GET",
  407. url: "https://gf.qytechs.cn/zh-CN/scripts/465777.json",
  408. timeout: 10 * 1e3,
  409. onload: function (response) {
  410. const scriptData = JSON.parse(response.responseText);
  411. if (scriptData.name === GM_info.script.name && compareVersions(scriptData.version, GM_info.script.version) === 1) {
  412. $("body").append(`
  413. <div id='update_panel'>
  414. <h3>${GM_info.script.name}有新版本!</h3>
  415. <hr>
  416. <div class='update_panel_menu'>
  417. <span class ='tip'>版本信息:${GM_info.script.version} ${scriptData.version}</span>
  418. </div>
  419. <br>
  420. <button id='updating'><a target="_blank" href="${scriptData.url}">更新</a></button>
  421. </div>
  422. `);
  423. }
  424. }
  425. });
  426. })();
  427.  
  428. // 汉化替换
  429. (function () {
  430. if (GM_getValue("bottomZh_CN") === ''||GM_getValue("bottomZh_CN") === undefined) GM_setValue("bottomZh_CN", true);
  431. if (GM_getValue("bottomZh_CN") != true) return;
  432. // 设置语言为zh
  433. var htmlTag = document.getElementsByTagName("html")[0];
  434. htmlTag.setAttribute("lang", "zh-CN");
  435.  
  436. // 暴力html替换
  437. const classData = {
  438. '.menu-list.main-menu-list': [
  439. { match: 'Help', replace: '帮助' },
  440. { match: 'Calendar', replace: '日历' },
  441. { match: 'Edu', replace: '培训' },
  442. { match: 'Rating', replace: '积分榜' },
  443. { match: 'Groups', replace: '团体' },
  444. { match: 'Problemset', replace: '题单' },
  445. { match: 'Gym', replace: '训练营(过去的大型比赛)' },
  446. { match: 'Contests', replace: '比赛' },
  447. { match: 'Catalog', replace: '指南目录' },
  448. { match: 'Top', replace: '热门' },
  449. { match: 'Home', replace: '主页' },
  450. ],
  451. '.personal-sidebar ': [
  452. { match: 'Contribution', replace: '贡献' },
  453. { match: 'Settings', replace: '设置' },
  454. { match: 'Blog', replace: '博客' },
  455. { match: 'Teams', replace: '队伍' },
  456. { match: 'Submissions', replace: '提交' },
  457. { match: 'Favourites', replace: '收藏' },
  458. { match: 'Talks', replace: '私信' },
  459. { match: 'Contests', replace: '比赛' },
  460. ],
  461. '.contest-state-phase': [
  462. { match: 'Before contest', replace: '即将进行的比赛' },
  463. { match: 'Contest is running', replace: '比赛进行中' },
  464. ],
  465. '.notice': [
  466. { match: 'has extra registration', replace: '有额外的报名时期' },
  467. { 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分钟。' },
  468. ],
  469. '.act-item': [
  470. { match: 'Submit', replace: '提交' },
  471. ],
  472. '.datatable': [
  473. { match: 'Virtual participation', replace: '参加虚拟重现赛' },
  474. { match: 'Enter', replace: '进入' },
  475. { match: 'Current standings', replace: '当前榜单' },
  476. { match: 'Final standings', replace: '榜单' },
  477. { match: 'School/University/City/Region Championship', replace: '学校/大学/城市/区域比赛' },
  478. { match: 'Official School Contest', replace: '学校官方比赛' },
  479. { match: 'Training Contest', replace: '训练赛' },
  480. { match: 'Training Camp Contest', replace: '训练营比赛' },
  481. { match: 'Official ICPC Contest', replace: 'ICPC官方比赛' },
  482. { match: 'Official International Personal Contest', replace: '官方国际个人赛' },
  483. { match: 'China', replace: '中国' },
  484. { match: 'Statements', replace: '题目描述' },
  485. { match: 'in Chinese', replace: '中文' },
  486. { match: 'Trainings', replace: '训练' },
  487. { match: 'Prepared by', replace: '编写人' },
  488. { match: 'Current or upcoming contests', replace: '当前或即将举行的比赛' },
  489. { match: 'Past contests', replace: '过去的比赛' },
  490. { match: 'Exclusions', replace: '排除' },
  491. { match: 'Before start', replace: '还有' },
  492. { match: 'Before registration', replace: '报名还有' },
  493. { match: 'Until closing ', replace: '结束报名' },
  494. { match: 'Register', replace: '报名' },
  495. { match: 'Registration completed', replace: '已报名' },
  496. ],
  497. '.contests-table': [
  498. { match: 'Contest history', replace: '比赛历史' },
  499. ],
  500. '.roundbox.sidebox.borderTopRound ': [
  501. { match: 'Register now', replace: '现在报名' },
  502. ],
  503. '.icon-eye-close.icon-large': [
  504. { match: 'Add to exclusions', replace: '添加到排除列表' },
  505. ],
  506. '._ContestFilterExclusionsManageFrame_addExclusionLink': [
  507. { match: 'Add to exclusions for gym contests filter', replace: '添加训练营过滤器的排除项' },
  508. ],
  509. '.roundbox.sidebox.sidebar-menu.borderTopRound ': [
  510. { match: 'Announcement', replace: '公告' },
  511. { match: 'Statements', replace: '统计报表' },
  512. { match: 'Tutorial', replace: '题解' },
  513. ],
  514. '.second-level-menu ': [
  515. { match: 'Problems', replace: '问题' },
  516. { match: 'Submit Code', replace: '提交代码' },
  517. { match: 'My Submissions', replace: '我的提交' },
  518. { match: 'Status', replace: '状态' },
  519. { match: 'Standings', replace: '榜单' },
  520. { match: 'Custom Invocation', replace: '自定义调试' },
  521. { match: 'Common standings', replace: '全部排行' },
  522. { match: 'Friends standings', replace: '只看朋友' },
  523. { match: 'Submit', replace: '提交' },
  524. { match: 'Custom test', replace: '自定义测试' },
  525. { match: 'Blog', replace: '博客' },
  526. { match: 'Teams', replace: '队伍' },
  527. { match: 'Submissions', replace: '提交' },
  528. { match: 'Groups', replace: '团体' },
  529. { match: 'Favourites', replace: '收藏' },
  530. { match: 'Contests', replace: '比赛' },
  531. { match: '问题etting', replace: '参与编写的问题' },
  532. { match: 'Gym', replace: '训练营' },
  533. { match: 'Mashups', replace: '组合混搭' },
  534. { match: 'Posts', replace: '帖子' },
  535. { match: '>Comments<', replace: '>回复<' },
  536. { match: 'Main', replace: '主要' },
  537. { match: 'Settings', replace: '设置' },
  538. { match: 'Lists', replace: '列表' },
  539. { match: 'General', replace: '基本' },
  540. { match: 'Sidebar', replace: '侧边栏' },
  541. { match: 'Social', replace: '社会信息' },
  542. { match: 'Address', replace: '地址' },
  543. { match: 'Wallets', replace: '钱包' },
  544. { match: 'Talks', replace: '对话' },
  545. { match: 'Dialogues', replace: '对话' },
  546. ],
  547. '.topic-toggle-collapse': [
  548. { match: 'Expand', replace: '展开' },
  549. ],
  550. '.topic-read-more': [
  551. { match: 'Full text and comments', replace: '阅读全文/评论' },
  552. ],
  553. '.toggleEditorCheckboxLabel': [
  554. { match: 'Switch off editor', replace: '关闭编辑器语法高亮' },
  555. ],
  556. '.submit': [
  557. { match: 'Registration for the contest', replace: '比赛报名' },
  558. ],
  559. };
  560. for (const className in classData) {
  561. const elements = document.querySelectorAll(className);
  562. elements.forEach((element) => {
  563. let html = element.outerHTML;
  564. const parent = element.parentNode;
  565. const childIndex = Array.from(parent.children).indexOf(element);
  566. let matched = false;
  567. classData[className].forEach((rule) => {
  568. if (html.match(new RegExp(rule.match, 'g'))) {
  569. matched = true;
  570. html = html.replace(new RegExp(rule.match, 'g'), rule.replace);
  571. const temp = document.createElement('div');
  572. temp.innerHTML = html.trim();
  573. const newElement = element.cloneNode(true);
  574. newElement.innerHTML = temp.firstChild.innerHTML;
  575. parent.replaceChild(newElement, parent.children[childIndex]);
  576. }
  577. });
  578. });
  579. }
  580.  
  581. // 元素选择替换
  582. // 侧栏titled汉化
  583. (function () {
  584. var translations = {
  585. "Pay attention": "→ 注意",
  586. "Top rated": "→ 评级排行",
  587. "Top contributors": "→ 贡献者排行",
  588. "Find user": "→ 查找用户",
  589. "Recent actions": "→ 最新动态",
  590. "Training filter": "→ 过滤筛选",
  591. "Find training": "→ 搜索比赛/问题",
  592. "Virtual participation": "→ 什么是虚拟参赛",
  593. "Contest materials": "→ 比赛相关资料",
  594. "Settings": "→ 设置",
  595. "Clone Contest to Mashup": "→ Clone比赛到组合混搭",
  596. "Submit": "→ 提交",
  597. "Practice": "→ 练习",
  598. "Problem tags": "→ 问题标签",
  599. "Filter Problems": "→ 过滤问题",
  600. "Attention": "→ 注意",
  601. "About Contest": "→ 关于比赛",
  602. "Last submissions": "→ 上次提交",
  603. "Streams": "→ 直播",
  604. "Coach rights": "→ 教练权限",
  605. "Advices to fill address": "→ 填写地址的建议",
  606. };
  607.  
  608. $(".caption.titled").each(function () {
  609. var tag = $(this).text();
  610. for (var property in translations) {
  611. if (tag.match(property)) {
  612. $(this).addClass(property);
  613. $(this).text(translations[property]);
  614. break;
  615. }
  616. }
  617. });
  618. })();
  619. // 题目Tag汉化
  620. (function () {
  621. var parentElement = $('._FilterByTagsFrame_addTagLabel');
  622. var selectElement = parentElement.find('select');
  623. var translations = {
  624. "*combine tags by OR": "*按逻辑或组合我选择的标签",
  625. "combine-tags-by-or": "*按逻辑或组合我选择的标签(combine-tags-by-or)",
  626. "2-sat": "二分图可满足性问题(2-sat)",
  627. "binary search": "二分搜索(binary search)",
  628. "bitmasks": "位掩码(bitmasks)",
  629. "brute force": "暴力枚举(brute force)",
  630. "chinese remainder theorem": "中国剩余定理(chinese remainder theorem)",
  631. "combinatorics": "组合数学(combinatorics)",
  632. "constructive algorithms": "构造算法(constructive algorithms)",
  633. "data structures": "数据结构(data structures)",
  634. "dfs and similar": "深度优先搜索及其变种(dfs and similar)",
  635. "divide and conquer": "分治算法(divide and conquer)",
  636. "dp": "动态规划(dp)",
  637. "dsu": "并查集(dsu)",
  638. "expression parsing": "表达式解析(expression parsing)",
  639. "fft": "快速傅里叶变换(fft)",
  640. "flows": "流(flows)",
  641. "games": "博弈论(games)",
  642. "geometry": "计算几何(geometry)",
  643. "graph matchings": "图匹配(graph matchings)",
  644. "graphs": "图论(graphs)",
  645. "greedy": "贪心策略(greedy)",
  646. "hashing": "哈希表(hashing)",
  647. "implementation": "实现问题,编程技巧,模拟(implementation)",
  648. "interactive": "交互性问题(interactive)",
  649. "math": "数学(math)",
  650. "matrices": "矩阵(matrices)",
  651. "meet-in-the-middle": "meet-in-the-middle算法(meet-in-the-middle)",
  652. "number theory": "数论(number theory)",
  653. "probabilities": "概率论(probabilities)",
  654. "schedules": "调度算法(schedules)",
  655. "shortest paths": "最短路算法(shortest paths)",
  656. "sortings": "排序算法(sortings)",
  657. "string suffix structures": "字符串后缀结构(string suffix structures)",
  658. "strings": "字符串处理(strings)",
  659. "ternary search": "三分搜索(ternary search)",
  660. "trees": "树形结构(trees)",
  661. "two pointers": "双指针算法(two pointers)"
  662. };
  663. selectElement.find("option").each(function () {
  664. var optionValue = $(this).val();
  665. if (translations[optionValue]) {
  666. $(this).text(translations[optionValue]);
  667. }
  668. });
  669. $("._FilterByTagsFrame_tagBoxCaption").each(function () {
  670. var tag = $(this).text();
  671. if (tag in translations) {
  672. $(this).text(translations[tag]);
  673. }
  674. });
  675. $(".notice").each(function () {
  676. var tag = $(this).text();
  677. if (tag in translations) {
  678. $(this).text(translations[tag]);
  679. }
  680. });
  681. $(".tag-box").each(function () {
  682. var tag = $(this).text();
  683. for (var property in translations) {
  684. property = property.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
  685. if (tag.match(property)) {
  686. $(this).text(translations[property]);
  687. break;
  688. }
  689. }
  690. });
  691. })();
  692. // 题目过滤器选项汉化
  693. (function () {
  694. var parentElement = $('#gym-filter-form');
  695. var selectElement = parentElement.find('div');
  696. var translations = {
  697. "Contest type:": "比赛类型:",
  698. "ICPC region:": "ICPC地区:",
  699. "Contest format:": "比赛形式:",
  700. "Order by:": "排序方式:",
  701. "Secondary order by:": "次要排序方式:",
  702. "Hide, if participated:": "隐藏我参加过的:",
  703. };
  704. selectElement.find("label").each(function () {
  705. var optionValue = $(this).text();
  706. if (translations[optionValue]) {
  707. $(this).text(translations[optionValue]);
  708. }
  709. });
  710. translations = {
  711. "Season:": "时间范围(年度)",
  712. "Duration, hours:": "持续时间(小时):",
  713. "Difficulty:": "难度:"
  714. };
  715. selectElement.each(function () {
  716. var optionValue = $(this).text();
  717. if (translations[optionValue]) {
  718. $(this).text(translations[optionValue]);
  719. }
  720. });
  721. })();
  722. (function () {
  723. var parentElement = $('.setting-value');
  724. var selectElement = parentElement.find('select');
  725. var translations = {
  726. "Official ACM-ICPC Contest": "ICPC官方比赛",
  727. "Official School Contest": "学校官方比赛",
  728. "Opencup Contest": "Opencup比赛",
  729. "School/University/City/Region Championship": "学校/大学/城市/地区锦标赛",
  730. "Training Camp Contest": "训练营比赛",
  731. "Official International Personal Contest": "官方国际个人赛",
  732. "Training Contest": "训练比赛",
  733. "ID_ASC": "创建时间(升序)",
  734. "ID_DESC": "创建时间(降序)",
  735. "RATING_ASC": "评分(升序)",
  736. "RATING_DESC": "评分(降序)",
  737. "DIFFICULTY_ASC": "难度(升序)",
  738. "DIFFICULTY_DESC": "难度(降序)",
  739. "START_TIME_ASC": "开始时间(升序)",
  740. "START_TIME_DESC": "开始时间(降序)",
  741. "DURATION_ASC": "持续时间(升序)",
  742. "DURATION_DESC": "持续时间(降序)",
  743. "POPULARITY_ASC": "热度(升序)",
  744. "POPULARITY_DESC": "热度(降序)",
  745. "UPDATE_TIME_ASC": "更新时间(升序)",
  746. "UPDATE_TIME_DESC": "更新时间(降序)"
  747. };
  748. selectElement.find("option").each(function () {
  749. var optionValue = $(this).val();
  750. if (translations[optionValue]) {
  751. $(this).text(translations[optionValue]);
  752. }
  753. });
  754. parentElement = $('.setting-last-value');
  755. selectElement = parentElement.find('select');
  756. selectElement.find("option").each(function () {
  757. var optionValue = $(this).val();
  758. if (translations[optionValue]) {
  759. $(this).text(translations[optionValue]);
  760. }
  761. });
  762. })();
  763. // 右侧sidebox通用汉化
  764. (function () {
  765. var parentElement = $('.sidebox');
  766. var selectElement = parentElement.find('div');
  767. var translations = {
  768. "Show tags for unsolved problems": "显示未解决问题的标签",
  769. "Hide solved problems": "隐藏已解决的问题",
  770. };
  771. selectElement.find("label").each(function () {
  772. var optionValue = $(this).text();
  773. if (translations[optionValue]) {
  774. $(this).text(translations[optionValue]);
  775. }
  776. });
  777. })();
  778. // 表单字段名汉化
  779. (function () {
  780. var translations = {
  781. "Problem:": "题目:",
  782. "Language:": "语言:",
  783. "Source code:": "源代码:",
  784. "Or choose file:": "或者选择文件:",
  785. "Choose file:": "选择文件:",
  786. "Notice:": "注意:",
  787. "virtual participation:": "虚拟参与:",
  788. "Registration for the contest:": "比赛报名:",
  789. "Terms of agreement:": "协议条款:",
  790. "Take part:": "参与:",
  791. "as individual participant:": "作为个人参与者:",
  792. "as a team member:": "作为团队成员:",
  793. "Virtual start time:": "虚拟开始时间:",
  794. "Complete problemset:": "完整的问题集:",
  795. "First name (English)": "名字(英文)",
  796. "Last name (English)": "姓氏(英文)",
  797. "First name (Native)": "名字(本地语言)",
  798. "Last name (Native)": "姓氏(本地语言)",
  799. "Birth date": "出生日期",
  800. "Country": "国家",
  801. "City": "城市",
  802. "Organization": "组织"
  803. };
  804. $(".field-name").each(function () {
  805. var optionValue = $(this).text();
  806. if (translations[optionValue]) {
  807. $(this).text(translations[optionValue]);
  808. }
  809. });
  810. })();
  811. (function () {
  812. var translations = {
  813. "Hide sidebar block \"Find user\"": "隐藏侧边栏块“查找用户”",
  814. "Hide sidebar block \"Current user\"": "隐藏侧边栏块“当前用户”",
  815. "Hide sidebar block \"Recent аctions\"": "隐藏侧边栏块“最新动态”",
  816. "Hide sidebar block \"Favourite groups\"": "隐藏侧边栏块“收藏组”",
  817. "Hide sidebar block \"Top contributors\"": "隐藏侧边栏块“贡献者排行”",
  818. "Hide sidebar block \"Top rated\"": "隐藏侧边栏块“评级排行”",
  819. "Hide sidebar block \"Streams\"": "隐藏侧边栏块“直播”",
  820. "Old password": "旧密码",
  821. "New password": "新密码",
  822. "Confirm new password": "确认新密码",
  823. "Contest email notification": "比赛邮件通知",
  824. "Send email on new user talk": "在有新用户对话时发送电子邮件",
  825. "Send email on new comment": "在有新评论时发送电子邮件",
  826. "Hide contact information": "隐藏联系人信息",
  827. "Remember me by Gmail, Facebook and etc": "通过 Gmail、Facebook 等记住我",
  828. "Show tags for unsolved problems": "显示未解决问题的标签",
  829. "Hide solved problems from problemset": "从问题集中隐藏已解决的问题",
  830. "Hide low rated blogs": "隐藏评级较低的博客",
  831. "Offer to publish great rating rises": "提供展示Rating显著提升的机会",
  832. "Enforce https": "强制 HTTPS",
  833. "Show private activity in the profile": "在个人资料中显示私人活动",
  834. "Show diagnostics": "显示诊断信息"
  835. };
  836. $(".field-name").each(function () {
  837. var tag = $(this).text();
  838. for (var property in translations) {
  839. property = property.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
  840. if (tag.match(property)) {
  841. $(this).text(translations[property]);
  842. break;
  843. }
  844. }
  845. });
  846. })();
  847. (function () {
  848. var translations = {
  849. "Postal/zip code": "邮政编码/邮编",
  850. "Country (English)": "国家(英文)",
  851. "State (English)": "州/省份(英文)",
  852. "City (English)": "城市(英文)",
  853. "Address (English)": "地址(英文)",
  854. "Recipient (English)": "收件人姓名(英文)",
  855. "Country (Native)": "国家(本地语言)",
  856. "State (Native)": "州/省份(本地语言)",
  857. "City (Native)": "城市(本地语言)",
  858. "Address (Native)": "地址(本地语言)",
  859. "Recipient (Native)": "收件人姓名(本地语言)",
  860. "Phone": "电话",
  861. "TON Wallet:": "TON 钱包:",
  862. "Secret Code:": "验证码:"
  863. };
  864. $("td.field-name label").each(function () {
  865. var optionValue = $(this).text();
  866. if (translations[optionValue]) {
  867. $(this).text(translations[optionValue]);
  868. }
  869. });
  870. })();
  871. // 按钮汉化
  872. (function () {
  873. var translations = {
  874. "Register for virtual participation": "报名虚拟参赛"
  875. };
  876. $(".submit").each(function () {
  877. var optionValue = $(this).val();
  878. if (translations[optionValue]) {
  879. $(this).val(translations[optionValue]);
  880. }
  881. });
  882. })();
  883. // 杂项汉化
  884. (function () {
  885. var translations = {
  886. "(standard input\/output)": "标准输入/输出",
  887. };
  888. $("div.notice").each(function () {
  889. var tag = $(this).children().eq(0).text();
  890. for (var property in translations) {
  891. if (tag.match(property)) {
  892. $(this).children().eq(0).text(translations[property]);
  893. break;
  894. }
  895. }
  896. });
  897. })();
  898. (function () {
  899. var translations = {
  900. "Ask a question": "提一个问题",
  901. };
  902. $(".ask-question-link").each(function () {
  903. var optionValue = $(this).text();
  904. if (translations[optionValue]) {
  905. $(this).text(translations[optionValue]);
  906. }
  907. });
  908. })();
  909. })();
  910.  
  911. // 设置面板
  912.  
  913. $("div[class='lang-chooser']").each(function () {
  914. $(this).before(
  915. "<button class='html2mdButton CFBetter_setting'>CodeforcesBetter设置</button>"
  916. );
  917. });
  918. $(document).ready(function () {
  919. $(".CFBetter_setting").click(function () {
  920. $(".CFBetter_setting").attr("disabled", true);
  921. $(".CFBetter_setting").css("background-color", "#e6e6e6");
  922. $(".CFBetter_setting").css("color", "#727378");
  923. $(".CFBetter_setting").css("cursor", "not-allowed");
  924. $("body").append(`
  925. <div id='CFBetter_setting_menu'>
  926. <div class="tool-box">
  927. <button class="btn-close">×</button>
  928. </div>
  929. <h3>基本设置</h3>
  930. <hr>
  931. <div class='CFBetter_setting_list'>
  932. <input type="checkbox" id="bottomZh_CN" name="bottomZh_CN" checked>
  933. <label for="bottomZh_CN">界面汉化</label>
  934. </div>
  935. <h3>翻译设置</h3>
  936. <hr>
  937. <label>
  938. <input type='radio' name='translation' value='deepl'>
  939. <span class='CFBetter_setting_menu_label_text'>deepl翻译</span>
  940. </label>
  941. <label>
  942. <input type='radio' name='translation' value='youdao'>
  943. <span class='CFBetter_setting_menu_label_text'>有道翻译</span>
  944. </label>
  945. <label>
  946. <input type='radio' name='translation' value='openai'>
  947. <span class='CFBetter_setting_menu_label_text'>使用ChatGPT翻译(API)</span>
  948. </label>
  949. <label>
  950. <input type='radio' name='translation' value='api2d'>
  951. <span class='CFBetter_setting_menu_label_text'>使用api2d翻译(API)</span>
  952. </label><br>
  953. <div class='CFBetter_setting_menu_input' id='baidu' style='display: none;'>
  954. <label for='baidu_uid'>APP ID:</label><input type='text' id='baidu_uid'>
  955. <label for='baidu_key'>KEY:</label><input type='text' id='baidu_key'>
  956. </div>
  957. <div class='CFBetter_setting_menu_input' id='openai' style='display: none;'>
  958. <span class ='tip'>提示:<br>请确保你能够正常访问OpenAIapi<br></span>
  959. <span class ='tip'>使用ChatGPT-3.5进行翻译,脚本的所有请求均在本地完成,</span>
  960. <span class ='tip'>你需要输入自己的OpenAI KEY,<a target="_blank" href="https://platform.openai.com/account/usage">官网</a></span>
  961. <label for='openai_key'>KEY:</label><input type='text' id='openai_key'>
  962. </div>
  963. <div class='CFBetter_setting_menu_input' id='api2d' style='display: none;'>
  964. <span class ='tip'>提示:<br>api2d是国内的一家提供代理直连访问OpenAIapi的服务商,相当于OpenAIapi的套壳<br></span>
  965. <span class ='tip'>使用ChatGPT-3.5进行翻译,脚本的所有请求均在本地完成<br></span>
  966. <span class ='tip'>你需要输入自己的api2d KEY,<a target="_blank" href="https://api2d.com/profile">官网</a></span>
  967. <label for='api2d_key'>KEY:</label><input type='text' id='api2d_key'>
  968. </div>
  969. <br>
  970. <button id='save'>保存</button>
  971. </div>
  972. `);
  973. var translation = GM_getValue("translation");
  974. $("#bottomZh_CN").prop("checked", GM_getValue("bottomZh_CN") === true);
  975. if (!translation) {
  976. GM_setValue("translation", "deepl");
  977. $("input[name='translation'][value='deepl']").prop("checked", true);
  978. } else {
  979. $("input[name='translation'][value='" + translation + "']").prop("checked", true);
  980. $("input[name='translation']").css("color", "gray");
  981. if (translation == "baidu") {
  982. $("#baidu").show();
  983. $("#baidu_uid").val(GM_getValue("baidu_uid"));
  984. $("#baidu_key").val(GM_getValue("baidu_key"));
  985. $("#baidu_uid").css("color", "gray");
  986. $("#baidu_key").css("color", "gray");
  987. } else if (translation == "openai") {
  988. $("#openai").show();
  989. $("#openai_key").val(GM_getValue("openai_key"));
  990. $("#openai_key").css("color", "gray");
  991. } else if (translation == "api2d") {
  992. $("#api2d").show();
  993. $("#api2d_key").val(GM_getValue("api2d_key"));
  994. $("#api2d_key").css("color", "gray");
  995. }
  996. }
  997.  
  998.  
  999. // 当单选框被选中时,显示对应的输入框,同时隐藏其他输入框
  1000. $("input[name='translation']").change(function () {
  1001. var selected = $(this).val(); // 获取当前选中的值
  1002. if (selected === "baidu") {
  1003. $("#baidu").show();
  1004. $("#baidu_uid").val(GM_getValue("baidu_uid"));
  1005. $("#baidu_key").val(GM_getValue("baidu_key"));
  1006. $("#openai, #api2d").hide();
  1007. } else if (selected === "openai") {
  1008. $("#openai").show();
  1009. $("#openai_key").val(GM_getValue("openai_key"));
  1010. $("#baidu, #api2d").hide();
  1011. } else if (selected === "api2d") {
  1012. $("#api2d").show();
  1013. $("#api2d_key").val(GM_getValue("api2d_key"));
  1014. $("#baidu, #openai").hide();
  1015. } else {
  1016. $("#baidu, #openai, #api2d").hide();
  1017. }
  1018. });
  1019.  
  1020.  
  1021. $("#save").click(function () {
  1022. var translation = $("input[name='translation']:checked").val();
  1023. var baidu_uid = $("#baidu_uid").val();
  1024. var baidu_key = $("#baidu_key").val();
  1025. var openai_key = $("#openai_key").val();
  1026. var api2d_key = $("#api2d_key").val();
  1027. GM_setValue("translation", translation);
  1028. if (translation == "baidu") {
  1029. GM_setValue("baidu_uid", baidu_uid);
  1030. GM_setValue("baidu_key", baidu_key);
  1031. } else if (translation == "openai") {
  1032. GM_setValue("openai_key", openai_key);
  1033. } else if (translation == "api2d") {
  1034. GM_setValue("api2d_key", api2d_key);
  1035. }
  1036. GM_setValue("bottomZh_CN", $("#bottomZh_CN").prop("checked"));
  1037. location.reload();
  1038.  
  1039. /* 切换汉化
  1040. if(JSON.parse(GM_getValue("bottomZh_CN")) != $("#bottomZh_CN").prop("checked")){
  1041. GM_setValue("bottomZh_CN", $("#bottomZh_CN").prop("checked"), 3650);
  1042. location.reload();
  1043. }else{
  1044. $("#CFBetter_setting_menu .btn-close").click();
  1045. }*/
  1046. });
  1047.  
  1048. // 关闭
  1049. $("#CFBetter_setting_menu .btn-close").click(function () {
  1050. $("#CFBetter_setting_menu").remove();
  1051. $(".CFBetter_setting").attr("disabled", false);
  1052. $(".CFBetter_setting").css("background-color", "#60a5fa");
  1053. $(".CFBetter_setting").css("color", "white");
  1054. $(".CFBetter_setting").css("cursor", "pointer");
  1055. });
  1056. });
  1057. });
  1058.  
  1059. // 是否为旧的latex渲染
  1060. var is_oldLatex = false;
  1061. if ($('.tex-span').length) {
  1062. is_oldLatex = true;
  1063. var newElement = $("<div></div>").addClass("alert alert-warning").html(`
  1064. 注意:当前页面存在使用非 MathJax 库渲染为 HTML Latex 公式(这通常是一道古老的题目),这导致 CodeforcesBetter 无法将其还原回 Latex,因此当前页面部分功能不适用。
  1065. <br>此外当前页面的翻译功能采用了特别的实现方式,因此可能会出现排版错位的情况。
  1066. `).css({
  1067. "margin": "1em",
  1068. "text-align": "center",
  1069. "position": "relative"
  1070. });
  1071. $(".menu-box:first").next().after(newElement);
  1072. }
  1073.  
  1074. // md2html转换/处理规则
  1075. var turndownService = new TurndownService({bulletListMarker: '-'});
  1076. var turndown = turndownService.turndown;
  1077.  
  1078. // 保留原始
  1079. turndownService.keep(['del']);
  1080.  
  1081. // 丢弃
  1082. turndownService.addRule('ignore-sample-tests', {
  1083. filter: function (node) {
  1084. return node.classList.contains('sample-tests') || node.classList.contains('header');
  1085. },
  1086. replacement: function (content, node) {
  1087. return "";
  1088. }
  1089. });
  1090. turndownService.addRule('remove-script', {
  1091. filter: function (node, options) {
  1092. return node.tagName.toLowerCase() == "script" && node.type.startsWith("math/tex");
  1093. },
  1094. replacement: function (content, node) {
  1095. return "";
  1096. }
  1097. });
  1098.  
  1099. // inline math
  1100. turndownService.addRule('inline-math', {
  1101. filter: function (node, options) {
  1102. return node.tagName.toLowerCase() == "span" && node.className == "MathJax";
  1103. },
  1104. replacement: function (content, node) {
  1105. return "$ " + $(node).next().text() + " $";
  1106. }
  1107. });
  1108.  
  1109. // block math
  1110. turndownService.addRule('block-math', {
  1111. filter: function (node, options) {
  1112. return node.tagName.toLowerCase() == "div" && node.className == "MathJax_Display";
  1113. },
  1114. replacement: function (content, node) {
  1115. return "\n$$\n" + $(node).next().text() + "\n$$\n";
  1116. }
  1117. });
  1118.  
  1119. // 表格
  1120. turndownService.addRule('bordertable', {
  1121. filter: 'table',
  1122. replacement: function (content, node) {
  1123. if (node.classList.contains('bordertable')) {
  1124. var output = [],
  1125. thead = '',
  1126. trs = node.querySelectorAll('tr');
  1127. if (trs.length > 0) {
  1128. var ths = trs[0].querySelectorAll('th');
  1129. if (ths.length > 0) {
  1130. thead = '| ' + Array.from(ths).map(th => turndownService.turndown(th.innerHTML.trim())).join(' | ') + ' |\n'
  1131. + '| ' + Array.from(ths).map(() => ' --- ').join('|') + ' |\n';
  1132. }
  1133. }
  1134. var rows = node.querySelectorAll('tr');
  1135. Array.from(rows).forEach(function (row, i) {
  1136. if (i > 0) {
  1137. var cells = row.querySelectorAll('td,th');
  1138. var trow = '| ' + Array.from(cells).map(cell => turndownService.turndown(cell.innerHTML.trim())).join(' | ') + ' |';
  1139. output.push(trow);
  1140. }
  1141. });
  1142. return thead + output.join('\n');
  1143. } else {
  1144. return content;
  1145. }
  1146. }
  1147. });
  1148.  
  1149. // 题目markdown转换/翻译面板
  1150. function addButtonPanel(parent, suffix, type, is_simple = false) {
  1151. if (type === "upper_level_2" || type === "problem") {
  1152. $(parent).children(':eq(1)').before(
  1153. "<div class='html2md-panel'> <button class='html2mdButton html2md-view" + suffix + "'>MarkDown视图</button> <button class='html2mdButton html2md-cb" + suffix + "'>Copy</button> <button class='html2mdButton translateButton" + suffix + "'>翻译</button> </div>");
  1154. } else if (is_simple) {
  1155. $(parent).before(
  1156. "<div class='html2md-panel'><button class='html2mdButton translateButton" + suffix + "'>翻译</button> </div>");
  1157. } else {
  1158. $(parent).before(
  1159. "<div class='html2md-panel'> <button class='html2mdButton html2md-view" + suffix + "'>MarkDown视图</button> <button class='html2mdButton html2md-cb" + suffix + "'>Copy</button> <button class='html2mdButton translateButton" + suffix + "'>翻译</button> </div>");
  1160. }
  1161. }
  1162. function addButtonWithHTML2MD(parent, suffix, type) {
  1163. if(is_oldLatex){
  1164. $(".html2md-view" + suffix).css({
  1165. "cursor": "not-allowed",
  1166. "background-color": "#e6e6e638",
  1167. "color": "#72737896",
  1168. });
  1169. $(".html2md-view" + suffix).prop("disabled", true);
  1170. }
  1171. $(".html2md-view" + suffix).click(function () {
  1172. var target, removedChildren;
  1173. if (type === "problem") {
  1174. target = $(parent).children().next().next().get(0);
  1175. } else if (type === "problem_QA") {
  1176. target = $(this).parent().parent().get(0);
  1177. removedChildren = $(this).parent().parent().children().eq(0).detach();
  1178. } else if (type === "upper_level_2") {
  1179. target = parent;
  1180. removedChildren = $(parent).children().slice(0, 2).detach();
  1181. } else {
  1182. target = parent;
  1183. }
  1184. if (target.viewmd) {
  1185. target.viewmd = false;
  1186. $(this).text("MarkDown视图");
  1187. $(this).removeClass("mdViewed");
  1188. $(target).html(target.original_html);
  1189. } else {
  1190. target.viewmd = true;
  1191. if (!target.original_html) {
  1192. target.original_html = $(target).html();
  1193. }
  1194. if (!target.markdown) {
  1195. target.markdown = turndownService.turndown($(target).html());
  1196. }
  1197. $(this).text("原始内容");
  1198. $(this).addClass("mdViewed");
  1199. $(target).html(`<span class="mdViewContent" oninput="$(this).parent().get(0).markdown=this.value;" style="width:auto; height:auto;">${target.markdown}</span>`);
  1200. }
  1201. // 恢复删除的元素
  1202. if (type === "problem_QA" || type === "upper_level_2") $(target).prepend(removedChildren);
  1203. });
  1204. }
  1205.  
  1206. function addButtonWithCopy(parent, suffix, type) {
  1207. if(is_oldLatex){
  1208. $(".html2md-cb" + suffix).css({
  1209. "cursor": "not-allowed",
  1210. "background-color": "#e6e6e638",
  1211. "color": "#72737896",
  1212. });
  1213. $(".html2md-cb" + suffix).prop("disabled", true);
  1214. }
  1215. $(".html2md-cb" + suffix).click(function () {
  1216. var target, removedChildren;
  1217. if (type === "problem") {
  1218. target = $($(parent).children().next().next().get(0)).clone();
  1219. } else if (type === "problem_QA") {
  1220. target = $(this).parent().parent().eq(0).clone();
  1221. $(target).children(':first').remove();
  1222. } else if (type === "upper_level_2") {
  1223. target = $(parent).clone();
  1224. $(target).children(':first').remove(); // 删除前两个元素(标题和按钮面板)
  1225. $(target).children(':first').remove();
  1226. } else {
  1227. target = $(parent).clone();
  1228. }
  1229. if (!target.markdown) {
  1230. target.markdown = turndownService.turndown($(target).html());
  1231. }
  1232. const textarea = document.createElement('textarea');
  1233. textarea.value = target.markdown;
  1234. document.body.appendChild(textarea);
  1235. textarea.select();
  1236. document.execCommand('copy');
  1237. document.body.removeChild(textarea);
  1238. $(this).addClass("copied");
  1239. $(this).text("Copied");
  1240. // 更新复制按钮文本
  1241. setTimeout(() => {
  1242. $(this).removeClass("copied");
  1243. $(this).text("Copy");
  1244. }, 2000);
  1245. $(target).remove();
  1246. });
  1247. }
  1248.  
  1249. function addButtonWithTranslation(parent, suffix, type) {
  1250. $(".translateButton" + suffix).click(async function () {
  1251. var target, removedChildren;
  1252. if (type === "problem") {
  1253. target = $($(parent).children().next().next().get(0)).clone();
  1254. } else if (type === "problem_QA") {
  1255. target = $(this).parent().parent().eq(0).clone();
  1256. $(target).children(':first').remove();
  1257. } else if (type === "upper_level_2") {
  1258. target = $(parent).clone();
  1259. $(target).children(':first').remove(); // 删除前两个元素(标题和按钮面板)
  1260. $(target).children(':first').remove();
  1261. } else {
  1262. target = $(parent).clone();
  1263. }
  1264. if (is_oldLatex) {
  1265. target.markdown = $(target).html();
  1266. } else if (!target.markdown) {
  1267. target.markdown = turndownService.turndown($(target).html());
  1268. }
  1269. const textarea = document.createElement('textarea');
  1270. textarea.value = target.markdown;
  1271. // 翻译处理
  1272. $(this).removeClass("translated");
  1273. $(this).text("翻译中");
  1274. $(this).css("cursor", "not-allowed");
  1275. var element_node;
  1276. if (type === "problem") {
  1277. element_node = $(parent).children()[2]; // 题面特殊处理
  1278. } else if (type === "problem_QA") {
  1279. element_node = $(parent).children().last().get(0);
  1280. } else {
  1281. element_node = parent;
  1282. }
  1283. var translateDiv = await translateProblemStatement(textarea.value, element_node);
  1284. //
  1285. $(this).addClass("translated");
  1286. $(this).text("已翻译");
  1287. $(this).prop("disabled", true);
  1288. $(target).remove();
  1289. // 重新翻译
  1290. if ($(this).next('.reTranslation').length === 0) {
  1291. const reTranslateBtn = $('<button>').addClass('html2mdButton reTranslation').html('&circlearrowright;').attr('title', '重新翻译');
  1292. reTranslateBtn.on('click', function() {
  1293. $(translateDiv).remove();
  1294. $(this).prev().click();
  1295. });
  1296. $(this).after(reTranslateBtn);
  1297. }else {
  1298. const reTranslateBtn = $(this).next('.reTranslation');
  1299. reTranslateBtn.off('click').on('click', function() {
  1300. $(translateDiv).remove();
  1301. $(this).prev().click();
  1302. });
  1303. }
  1304. });
  1305. }
  1306.  
  1307.  
  1308. window.onload = function () {
  1309. // 添加按钮到题面部分
  1310. $("div[class='problem-statement']").each(function () {
  1311. var problem_id = "_comment_" + getRandomNumber(8);
  1312. addButtonPanel(this, problem_id, "problem");
  1313. addButtonWithHTML2MD(this, problem_id, "problem");
  1314. addButtonWithCopy(this, problem_id, "problem");
  1315. addButtonWithTranslation(this, problem_id, "problem");
  1316. });
  1317.  
  1318. // 添加按钮到input部分
  1319. $("div[class='input-specification']").each(function () {
  1320. var id = "_" + getRandomNumber(8);
  1321. addButtonPanel(this, id, "upper_level_2");
  1322. addButtonWithHTML2MD(this, id, "upper_level_2");
  1323. addButtonWithCopy(this, id, "upper_level_2");
  1324. addButtonWithTranslation(this, id, "upper_level_2");
  1325. });
  1326.  
  1327. // 添加按钮到output部分
  1328. $("div[class='output-specification']").each(function () {
  1329. var id = "_" + getRandomNumber(8);
  1330. addButtonPanel(this, id, "upper_level_2");
  1331. addButtonWithHTML2MD(this, id, "upper_level_2");
  1332. addButtonWithCopy(this, id, "upper_level_2");
  1333. addButtonWithTranslation(this, id, "upper_level_2");
  1334. });
  1335.  
  1336. // 添加按钮到note部分
  1337. $("div[class='note']").each(function () {
  1338. var id = "_" + getRandomNumber(8);
  1339. addButtonPanel(this, id, "upper_level_2");
  1340. addButtonWithHTML2MD(this, id, "upper_level_2");
  1341. addButtonWithCopy(this, id, "upper_level_2");
  1342. addButtonWithTranslation(this, id, "upper_level_2");
  1343. });
  1344.  
  1345. // 添加按钮到ttypography部分
  1346. $(".ttypography").each(function () {
  1347. // 题目页特判
  1348. if (!$(this).parent().hasClass('problemindexholder')) {
  1349. var comment_id = "_comment_" + getRandomNumber(8);
  1350. addButtonPanel(this, comment_id, "this_level");
  1351. addButtonWithHTML2MD(this, comment_id, "this_level");
  1352. addButtonWithCopy(this, comment_id, "this_level");
  1353. addButtonWithTranslation(this, comment_id, "this_level");
  1354. }
  1355. });
  1356.  
  1357. // 添加按钮到titled部分
  1358. (function () {
  1359. var elements = [".Virtual.participation", ".Attention", ".Practice"];//只为部分titled添加
  1360. $.each(elements, function (index, value) {
  1361. $(value).each(function () {
  1362. var titled_id = "_titled_" + getRandomNumber(8);
  1363. var $nextDiv = $(this).next().get(0);
  1364. addButtonPanel($nextDiv, titled_id, "this_level", true);
  1365. addButtonWithTranslation($nextDiv, titled_id, "this_level");
  1366. });
  1367. });
  1368. })();
  1369.  
  1370. // 添加按钮到比赛QA部分
  1371. $(".question-requestText-td").each(function () {
  1372. var $nextDiv = $(this).children().get(0);
  1373. var question_id = "_question_" + getRandomNumber(8);
  1374. addButtonPanel($nextDiv, question_id, "problem_QA", true);
  1375. addButtonWithTranslation(this, question_id, "problem_QA");
  1376. });
  1377. };
  1378.  
  1379. // 翻译框/翻译处理器
  1380. var translatedText = "";
  1381. async function translateProblemStatement(text, element_node) {
  1382. let id = Math.floor(Date.now() / 1000);
  1383. let matches = [];
  1384. let replacements = {};
  1385. // 创建元素并放在element_node的后面
  1386. const translateDiv = document.createElement('div');
  1387. translateDiv.setAttribute('id', id);
  1388. translateDiv.classList.add('translate-problem-statement');
  1389. const spanElement = document.createElement('span');
  1390. translateDiv.appendChild(spanElement);
  1391. element_node.insertAdjacentElement('afterend', translateDiv);
  1392. // 替换latex公式
  1393. if (is_oldLatex) {
  1394. //去除开头结尾的<p>标签
  1395. text = text.replace(/^<p>/i, "");
  1396. text = text.replace(/<\/p>$/i, "");
  1397. //
  1398. let i = 0;
  1399. let regex = /<span\s+class="tex-span">.*?<\/span>/gi;
  1400. matches = text.match(regex);
  1401. try {
  1402. for (i; i < matches.length; i++) {
  1403. let match = matches[i];
  1404. text = text.replace(match, `【${i + 1}】`);
  1405. replacements[`【${i + 1}】`] = match;
  1406. }
  1407. } catch (e) { }
  1408. } else if (GM_getValue("translation") != "api2d" && GM_getValue("translation") != "openai") {
  1409. // 使用GPT翻译时不必替换latex公式
  1410. let i = 0;
  1411. // 块公式
  1412. matches = matches.concat(text.match(/\$\$([\s\S]*?)\$\$/g));
  1413. try {
  1414. for (i; i < matches.length; i++) {
  1415. let match = matches[i];
  1416. text = text.replace(match, `【${i + 1}】`);
  1417. replacements[`【${i + 1}】`] = match;
  1418. }
  1419. } catch (e) { }
  1420. // 行内公式
  1421. matches = matches.concat(text.match(/\$(.*?)\$/g));
  1422. try {
  1423. for (i; i < matches.length; i++) {
  1424. let match = matches[i];
  1425. text = text.replace(match, `【${i + 1}】`);
  1426. replacements[`【${i + 1}】`] = match;
  1427. }
  1428. } catch (e) { }
  1429. }
  1430. // 翻译
  1431. var translation = GM_getValue("translation");
  1432. if (translation === 'undefined' || translation === '') {
  1433. GM_setValue("translation", "deepl");
  1434. translation = "deepl";
  1435. }
  1436. if (translation == "deepl") {
  1437. translateDiv.textContent = "正在翻译中……请耐心等待,\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1438. translatedText = await translate_deepl(text);
  1439. } else if (translation == "youdao") {
  1440. translateDiv.textContent = "正在翻译中……请耐心等待,\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1441. translatedText = await translate_youdao_mobile(text);
  1442. } else if (translation == "baidu") {
  1443. var baidu_appid = GM_getValue("baidu_uid");
  1444. var baidu_key = GM_getValue("baidu_key");
  1445. } else if (translation == "openai") {
  1446. translateDiv.textContent = "正在翻译中……请稍等\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1447. translatedText = await translate_openai(text);
  1448. } else if (translation == "api2d") {
  1449. translateDiv.textContent = "正在翻译中……请稍等\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1450. translatedText = await translate_api2d(text);
  1451. }
  1452. // 还原latex公式
  1453. if (is_oldLatex) {
  1454. translatedText = "<p>" + translatedText;
  1455. translatedText += "</p>";
  1456. try {
  1457. for (let i = 0; i < matches.length; i++) {
  1458. let match = matches[i];
  1459. let replacement = replacements[`【${i + 1}】`];
  1460. translatedText = translatedText.replace(`【${i + 1}】`, replacement);
  1461. }
  1462. } catch (e) { }
  1463. }
  1464. else if (GM_getValue("translation") != "api2d" && GM_getValue("translation") != "openai") {
  1465. try {
  1466. for (let i = 0; i < matches.length; i++) {
  1467. let match = matches[i];
  1468. let replacement = replacements[`【${i + 1}】`];
  1469. translatedText = translatedText.replace(`【${i + 1}】`, replacement);
  1470. }
  1471. } catch (e) { }
  1472. }
  1473. // 使符合mathjx的转换语法
  1474. translatedText = translatedText.replace(/(\$\$)/g, "");
  1475. translatedText = translatedText.replace(/(?<!\$)\$(?!\$)/g, "$$$$$");
  1476. // 更新
  1477. if (is_oldLatex) {
  1478. // oldlatex
  1479. translatedText = $.parseHTML(translatedText);
  1480. $(translateDiv).empty().append($(translatedText));
  1481. } else {
  1482. translateDiv.innerHTML = translatedText;
  1483. // 渲染MarkDown
  1484. var md = window.markdownit();
  1485. var html = md.render(translateDiv.innerText);
  1486. translateDiv.innerHTML = html;
  1487. // 渲染Latex
  1488. MathJax.Hub.Queue(["Typeset", MathJax.Hub, document.getElementById(id)]);
  1489. }
  1490. return translateDiv;
  1491. }
  1492.  
  1493. // ChatGPT
  1494. async function translate_openai(raw) {
  1495. var openai_key = GM_getValue("openai_key");
  1496. var openai_retext = "";
  1497. var data;
  1498. if (is_oldLatex) {
  1499. data = {
  1500. prompt: "(You:请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的【】、HTML标签本身以及其中的内容不翻译不变动,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw + ")",
  1501. max_tokens: 2048,
  1502. model: "text-davinci-003",
  1503. };
  1504. } else {
  1505. data = {
  1506. prompt: "(You:请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw + ")",
  1507. max_tokens: 2048,
  1508. model: "text-davinci-003",
  1509. };
  1510. };
  1511. return new Promise(function (resolve, reject) {
  1512. GM_xmlhttpRequest({
  1513. method: 'POST',
  1514. url: 'https://api.openai.com/v1/completions',
  1515. data: JSON.stringify(data),
  1516. headers: {
  1517. 'Content-Type': 'application/json',
  1518. 'Authorization': 'Bearer ' + GM_getValue("openai_key") + ''
  1519. },
  1520. responseType: 'json',
  1521. onload: function (res) {
  1522. if (res.status === 200) {
  1523. openai_retext = res.response.choices[0].text;
  1524. openai_retext = openai_retext.replace(/^\s+/, '');
  1525. resolve(openai_retext);
  1526. }
  1527. else {
  1528. console.error(res.statusText);
  1529. reject(res.statusText);
  1530. }
  1531. }
  1532. });
  1533. });
  1534. }
  1535.  
  1536. // api2d
  1537. async function translate_api2d(raw) {
  1538. var api2d_key = GM_getValue("api2d_key");
  1539. var api2d_retext = "";
  1540. var postData;
  1541. if (is_oldLatex) {
  1542. postData = JSON.stringify({
  1543. model: 'gpt-3.5-turbo',
  1544. messages: [{ role: 'user', content: '请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的【】、HTML标签本身以及其中的内容不翻译不变动,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n' + raw }],
  1545. });
  1546. } else {
  1547. postData = JSON.stringify({
  1548. model: 'gpt-3.5-turbo',
  1549. messages: [{ role: 'user', content: '请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n' + raw }],
  1550. });
  1551. }
  1552. const options = {
  1553. method: 'POST',
  1554. headers: {
  1555. 'Content-Type': 'application/json',
  1556. Authorization: 'Bearer ' + api2d_key,
  1557. },
  1558. data: postData,
  1559. };
  1560.  
  1561. return new Promise(function (resolve, reject) {
  1562. GM_xmlhttpRequest({
  1563. method: options.method,
  1564. url: `https://openai.api2d.net/v1/chat/completions`,
  1565. headers: options.headers,
  1566. data: options.data,
  1567. responseType: 'json',
  1568. onload: function (response) {
  1569. api2d_retext = response.response.choices[0].message.content;
  1570. resolve(api2d_retext);
  1571. },
  1572. onerror: function (response) {
  1573. console.error(response.statusText);
  1574. reject(response.statusText);
  1575. },
  1576. });
  1577. });
  1578. }
  1579. //
  1580.  
  1581. //--有道翻译m--start
  1582. async function translate_youdao_mobile(raw) {
  1583. const options = {
  1584. method: "POST",
  1585. url: 'http://m.youdao.com/translate',
  1586. data: "inputtext=" + encodeURIComponent(raw) + "&type=AUTO",
  1587. anonymous: true,
  1588. headers: {
  1589. "Content-Type": "application/x-www-form-urlencoded"
  1590. }
  1591. }
  1592. return await BaseTranslate('有道翻译mobile', raw, options, res => /id="translateResult">\s*?<li>([\s\S]*?)<\/li>\s*?<\/ul/.exec(res)[1])
  1593. }
  1594. //--有道翻译m--end
  1595.  
  1596. //--Deepl翻译--start
  1597. function getTimeStamp(iCount) {
  1598. const ts = Date.now();
  1599. if (iCount !== 0) {
  1600. iCount = iCount + 1;
  1601. return ts - (ts % iCount) + iCount;
  1602. } else {
  1603. return ts;
  1604. }
  1605. }
  1606.  
  1607. async function translate_deepl(raw) {
  1608. const id = (Math.floor(Math.random() * 99999) + 100000) * 1000;
  1609. const data = {
  1610. jsonrpc: '2.0',
  1611. method: 'LMT_handle_texts',
  1612. id,
  1613. params: {
  1614. splitting: 'newlines',
  1615. lang: {
  1616. source_lang_user_selected: 'auto',
  1617. target_lang: 'ZH',
  1618. },
  1619. texts: [{
  1620. text: raw,
  1621. requestAlternatives: 3
  1622. }],
  1623. timestamp: getTimeStamp(raw.split('i').length - 1)
  1624. }
  1625. }
  1626. let postData = JSON.stringify(data);
  1627. if ((id + 5) % 29 === 0 || (id + 3) % 13 === 0) {
  1628. postData = postData.replace('"method":"', '"method" : "');
  1629. } else {
  1630. postData = postData.replace('"method":"', '"method": "');
  1631. }
  1632. const options = {
  1633. method: 'POST',
  1634. url: 'https://www2.deepl.com/jsonrpc',
  1635. data: postData,
  1636. headers: {
  1637. 'Content-Type': 'application/json',
  1638. 'Host': 'www.deepl.com',
  1639. 'Origin': 'https://www.deepl.com',
  1640. 'Referer': 'https://www.deepl.com/'
  1641. },
  1642. anonymous: true,
  1643. nocache: true,
  1644. }
  1645. return await BaseTranslate('Deepl翻译', raw, options, res => JSON.parse(res).result.texts[0].text)
  1646. }
  1647.  
  1648. //--Deepl翻译--end
  1649.  
  1650. //--异步请求包装工具--start
  1651. async function PromiseRetryWrap(task, options, ...values) {
  1652. const { RetryTimes, ErrProcesser } = options || {};
  1653. let retryTimes = RetryTimes || 5;
  1654. const usedErrProcesser = ErrProcesser || (err => { throw err });
  1655. if (!task) return;
  1656. while (true) {
  1657. try {
  1658. return await task(...values);
  1659. } catch (err) {
  1660. if (!--retryTimes) {
  1661. console.log(err);
  1662. return usedErrProcesser(err);
  1663. }
  1664. }
  1665. }
  1666. }
  1667.  
  1668. async function BaseTranslate(name, raw, options, processer) {
  1669. const toDo = async () => {
  1670. var tmp;
  1671. try {
  1672. const data = await Request(options);
  1673. tmp = data.responseText;
  1674. const result = await processer(tmp);
  1675. if (result) sessionStorage.setItem(name + '-' + raw, result);
  1676. return result
  1677. } catch (err) {
  1678. throw {
  1679. responseText: tmp,
  1680. err: err
  1681. }
  1682. }
  1683. }
  1684. return await PromiseRetryWrap(toDo, { RetryTimes: 3, ErrProcesser: () => "翻译出错" })
  1685. }
  1686.  
  1687. function Request(options) {
  1688. return new Promise((reslove, reject) => GM_xmlhttpRequest({ ...options, onload: reslove, onerror: reject }))
  1689. }
  1690.  
  1691. //--异步请求包装工具--end
  1692.  
  1693. // 随机数生成
  1694. function getRandomNumber(numDigits) {
  1695. let min = Math.pow(10, numDigits - 1);
  1696. let max = Math.pow(10, numDigits) - 1;
  1697. return Math.floor(Math.random() * (max - min + 1)) + min;
  1698. }
  1699.  
  1700. // 旧配置迁移(临时,将在1.38版本后删除)
  1701. if(getCookie("translation")){GM_setValue("translation",getCookie("translation"));deleteCookie("translation");}
  1702. if(getCookie("baidu_uid")){GM_setValue("baidu_uid",getCookie("baidu_uid"));deleteCookie("baidu_uid");}
  1703. if(getCookie("baidu_key")){GM_setValue("baidu_key",getCookie("baidu_key"));deleteCookie("baidu_key");}
  1704. if(getCookie("openai_key")){GM_setValue("openai_key",getCookie("openai_key"));deleteCookie("openai_key");}
  1705. if(getCookie("api2d_key")){GM_setValue("api2d_key",getCookie("api2d_key"));deleteCookie("api2d_key");}
  1706. if(getCookie("bottomZh_CN")){GM_setValue("bottomZh_CN",getCookie("bottomZh_CN")==="true");deleteCookie("bottomZh_CN");}
  1707. function deleteCookie(name){document.cookie=name+"=; expires=Thu, 01 Jan 1970 00:00:01 GMT;";}
  1708. function getCookie(cname) {var name = cname + "=";var decodedCookie = decodeURIComponent(document.cookie);var ca = decodedCookie.split(';');for (var i = 0; i < ca.length; i++) {var c = ca[i];while (c.charAt(0) == ' ') {c = c.substring(1);}if (c.indexOf(name) == 0) {return c.substring(name.length, c.length);}}return "";}

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址