Greasy Fork 支持简体中文。

Atcoder Better!

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

目前為 2023-07-27 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name Atcoder Better!
  3. // @namespace https://greasyfork.org/users/747162
  4. // @version 1.01
  5. // @description Atcoder界面汉化、题目翻译,markdown视图,一键复制题目,跳转到洛谷
  6. // @author 北极小狐
  7. // @match https://atcoder.jp/*
  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_setClipboard
  22. // @icon https://atcoder-cdn.oss-cn-beijing.aliyuncs.com/atcoder.png
  23. // @require https://cdn.staticfile.org/turndown/7.1.2/turndown.min.js
  24. // @require https://cdn.staticfile.org/markdown-it/13.0.1/markdown-it.min.js
  25. // @license MIT
  26. // @compatible Chrome
  27. // @compatible Firefox
  28. // @compatible Edge
  29. // ==/UserScript==
  30.  
  31. // 状态与初始化
  32. const getGMValue = (key, defaultValue) => {
  33. const value = GM_getValue(key);
  34. if (value === undefined) {
  35. GM_setValue(key, defaultValue);
  36. return defaultValue;
  37. }
  38. return value;
  39. };
  40.  
  41. const bottomZh_CN = getGMValue("bottomZh_CN", true);
  42. const translation = getGMValue("translation", "deepl");
  43. const enableSegmentedTranslation = getGMValue("enableSegmentedTranslation", false);
  44. const showJumpToLuogu = getGMValue("showJumpToLuogu", true);
  45. const showLoading = getGMValue("showLoading", true);
  46. const loaded = getGMValue("loaded", false);
  47. var x_api2d_no_cache = getGMValue("x_api2d_no_cache", true);
  48. var showOpneAiAdvanced = getGMValue("showOpneAiAdvanced", false);
  49.  
  50. // 常量
  51. 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>';
  52. 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: 9999; }`;
  53.  
  54. // 样式
  55. GM_addStyle(`
  56. :root {
  57. --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";
  58. }
  59. span.mdViewContent {
  60. white-space: pre-wrap;
  61. }
  62. /*翻译div*/
  63. .translate-problem-statement {
  64. display: grid;
  65. justify-items: start;
  66. white-space: pre-wrap;
  67. letter-spacing: 1.8px;
  68. color: #059669;
  69. background-color: #f9f9fa;
  70. border: 1px solid #10b981;
  71. border-radius: 0.3rem;
  72. padding: 5px;
  73. margin: 10px 0px;
  74. width: 100%;
  75. box-sizing: border-box;
  76. font-size: 13px;
  77. }
  78. .translate-problem-statement.error_translate {
  79. color: red;
  80. border-color: red;
  81. }
  82.  
  83. .translate-problem-statement h2, .translate-problem-statement h3 {
  84. font-size: 16px;
  85. }
  86.  
  87. .translate-problem-statement ul {
  88. line-height: 100%;
  89. }
  90.  
  91. .translate-problem-statement a {
  92. color: #10b981;
  93. font-weight: 600;
  94. background: 0 0;
  95. text-decoration: none;
  96. }
  97. .translate-problem-statement p {
  98. margin: 8px 0 !important;
  99. font-size: 14px !important;
  100. }
  101. .translate-problem-statement img {
  102. max-width: 100.0%;
  103. max-height: 100.0%;
  104. }
  105.  
  106. .translate-problem-statement .katex {
  107. font-size: 14px;
  108. }
  109. .translate-problem-statement a:hover {
  110. text-decoration: revert;
  111. }
  112. .html2md-panel {
  113. display: flex;
  114. justify-content: flex-end;
  115. }
  116. .html2md-panel a {
  117. text-decoration: none;
  118. }
  119. button.html2mdButton {
  120. display: flex;
  121. align-items: center;
  122. cursor: pointer;
  123. background-color: #ffffff;
  124. color: #606266;
  125. height: 22px;
  126. width: auto;
  127. font-size: 13px;
  128. border-radius: 0.3rem;
  129. padding: 1px 5px;
  130. margin: 5px;
  131. border: 1px solid #dcdfe6;
  132. }
  133. button.html2mdButton:hover {
  134. color: #409eff;
  135. border-color: #409eff;
  136. }
  137. button.html2mdButton.copied {
  138. background-color: #f0f9eb;
  139. color: #67c23e;
  140. border: 1px solid #b3e19d;
  141. }
  142. button.html2mdButton.mdViewed {
  143. background-color: #fdf6ec;
  144. color: #e6a23c;
  145. border: 1px solid #f3d19e;
  146. }
  147. button.html2mdButton.error {
  148. background-color: #fef0f0;
  149. color: #f56c6c;
  150. border: 1px solid #fab6b6;
  151. }
  152. button.translated {
  153. cursor: not-allowed;
  154. background-color: #f0f9eb;
  155. color: #67c23e;
  156. border: 1px solid #b3e19d;
  157. }
  158. button.html2mdButton.reTranslation {
  159. background-color: #f4f4f5;
  160. color: #909399;
  161. border: 1px solid #c8c9cc;
  162. }
  163. .translate-problem-statement table {
  164. border: 1px #ccc solid;
  165. border-collapse: collapse;
  166. margin: 1.3571em 0 0;
  167. color: #222;
  168. }
  169. .translate-problem-statement table td {
  170. border-right: 1px solid #ccc;
  171. border-top: 1px solid #ccc;
  172. padding: 0.7143em 0.5em;
  173. }
  174. .translate-problem-statement table th {
  175. padding: 0.7143em 0.5em;
  176. }
  177. .translate-problem-statement p:not(:first-child) {
  178. margin: 1.5em 0 0;
  179. }
  180. /*设置面板*/
  181. header .enter-or-register-box, header .languages {
  182. position: absolute;
  183. right: 170px;
  184. }
  185. button.html2mdButton.AtBetter_setting {
  186. float: right;
  187. height: 30px;
  188. background: #3c5a7f;
  189. color: white;
  190. margin: 10px;
  191. border: 0px;
  192. }
  193.  
  194. button.html2mdButton.AtBetter_setting.open {
  195. background-color: #e6e6e61f;
  196. color: #727378;
  197. cursor: not-allowed;
  198. }
  199. #AtBetter_setting_menu {
  200. z-index: 9999;
  201. box-shadow: 0px 0px 0px 4px #ffffff;
  202. display: grid;
  203. position: fixed;
  204. top: 50%;
  205. left: 50%;
  206. width: 360px;
  207. transform: translate(-50%, -50%);
  208. border-radius: 6px;
  209. background-color: #edf1ff;
  210. border-collapse: collapse;
  211. border: 1px solid #ffffff;
  212. color: #697e91;
  213. font-family: var(--vp-font-family-base);
  214. padding: 10px 20px 20px 20px;
  215. }
  216. #AtBetter_setting_menu h3 {
  217. margin-top: 10px;
  218. }
  219. #AtBetter_setting_menu hr {
  220. border: none;
  221. height: 1px;
  222. background-color: #ccc;
  223. margin: 10px 0;
  224. }
  225. /*设置面板-关闭按钮*/
  226. #AtBetter_setting_menu .tool-box {
  227. position: absolute;
  228. display: flex;
  229. align-items: center;
  230. justify-content: center;
  231. width: 2.5rem;
  232. height: 2.5rem;
  233. top: 3px;
  234. right: 3px;
  235. }
  236.  
  237. #AtBetter_setting_menu .btn-close {
  238. display: flex;
  239. align-items: center;
  240. justify-content: center;
  241. text-align: center;
  242. padding: 10px !important;
  243. width: 1px;
  244. height: 1px !important;
  245. color: transparent;
  246. font-size: 0;
  247. cursor: pointer;
  248. background-color: #ff000080;
  249. border: none;
  250. border-radius: 10px;
  251. transition: .15s ease all;
  252. }
  253.  
  254. #AtBetter_setting_menu .btn-close:hover {
  255. width: 20px;
  256. height: 20px !important;
  257. font-size: 17px;
  258. color: #ffffff;
  259. background-color: #ff0000cc;
  260. box-shadow: 0 5px 5px 0 #00000026;
  261. }
  262.  
  263. #AtBetter_setting_menu .btn-close:active {
  264. width: .9rem;
  265. height: .9rem;
  266. font-size: 1px;
  267. color: #ffffffde;
  268. --shadow-btn-close: 0 3px 3px 0 #00000026;
  269. box-shadow: var(--shadow-btn-close);
  270. }
  271.  
  272. /*设置面板-checkbox*/
  273. #AtBetter_setting_menu input[type=checkbox]:focus {
  274. outline: 0px;
  275. }
  276.  
  277. #AtBetter_setting_menu input[type="checkbox"] {
  278. margin: 0px;
  279. appearance: none;
  280. -webkit-appearance: none;
  281. width: 40px;
  282. height: 20px !important;
  283. border: 1.5px solid #D7CCC8;
  284. padding: 0px !important;
  285. border-radius: 20px;
  286. background: #efebe978;
  287. position: relative;
  288. box-sizing: border-box;
  289. }
  290.  
  291. #AtBetter_setting_menu input[type="checkbox"]::before {
  292. content: "";
  293. width: 14px;
  294. height: 14px;
  295. background: #D7CCC8;
  296. border: 1.5px solid #BCAAA4;
  297. border-radius: 50%;
  298. position: absolute;
  299. top: 0;
  300. left: 0;
  301. transform: translate(2%, 2%);
  302. transition: all 0.3s ease-in-out;
  303. -webkit-box-sizing: content-box;
  304. -moz-box-sizing: content-box;
  305. box-sizing: content-box;
  306. }
  307.  
  308. #AtBetter_setting_menu input[type="checkbox"]::after {
  309. 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");
  310. position: absolute;
  311. top: 0;
  312. left: 24px;
  313. }
  314.  
  315. #AtBetter_setting_menu input[type="checkbox"]:checked {
  316. border: 1.5px solid #C5CAE9;
  317. background: #E8EAF6;
  318. }
  319.  
  320. #AtBetter_setting_menu input[type="checkbox"]:checked::before {
  321. background: #C5CAE9;
  322. border: 1.5px solid #7986CB;
  323. transform: translate(122%, 2%);
  324. transition: all 0.3s ease-in-out;
  325. }
  326.  
  327. #AtBetter_setting_menu input[type="checkbox"]:checked::after {
  328. 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");
  329. position: absolute;
  330. top: 1.5px;
  331. left: 4.5px;
  332. }
  333.  
  334. #AtBetter_setting_menu label {
  335. font-size: 16px;
  336. font-weight: initial;
  337. margin-bottom: 0px;
  338. }
  339.  
  340. .AtBetter_setting_list {
  341. display: flex;
  342. align-items: center;
  343. padding: 10px;
  344. margin: 5px 0px;
  345. background-color: #ffffff;
  346. border-bottom: 1px solid #c9c6c696;
  347. border-radius: 8px;
  348. justify-content: space-between;
  349. }
  350.  
  351. /*设置面板-radio*/
  352. #AtBetter_setting_menu>label {
  353. display: flex;
  354. list-style-type: none;
  355. padding-inline-start: 0px;
  356. overflow-x: auto;
  357. max-width: 100%;
  358. margin: 0px;
  359. align-items: center;
  360. margin: 3px 0px;
  361. }
  362.  
  363. .AtBetter_setting_menu_label_text {
  364. display: flex;
  365. border: 1px dashed #00aeeccc;
  366. height: 20px;
  367. width: 100%;
  368. color: gray;
  369. font-weight: 300;
  370. font-size: 14px;
  371. letter-spacing: 2px;
  372. padding: 7px;
  373. align-items: center;
  374. -webkit-box-sizing: content-box;
  375. -moz-box-sizing: content-box;
  376. box-sizing: content-box;
  377. }
  378.  
  379. input[type="radio"]:checked+.AtBetter_setting_menu_label_text {
  380. background: #41e49930;
  381. border: 1px solid green;
  382. color: green;
  383. font-weight: 500;
  384. }
  385.  
  386. #AtBetter_setting_menu>label input[type="radio"] {
  387. -webkit-appearance: none;
  388. appearance: none;
  389. list-style: none;
  390. padding: 0px !important;
  391. margin: 0px;
  392. }
  393.  
  394. #AtBetter_setting_menu input[type="text"] {
  395. display: block;
  396. height: 25px !important;
  397. width: 100%;
  398. background-color: #ffffff;
  399. color: #727378;
  400. font-size: 12px;
  401. border-radius: 0.3rem;
  402. padding: 1px 5px !important;
  403. box-sizing: border-box;
  404. margin: 5px 0px 5px 0px;
  405. border: 1px solid #00aeeccc;
  406. box-shadow: 0 0 1px #0000004d;
  407. }
  408.  
  409. .AtBetter_setting_menu_input {
  410. width: 100%;
  411. display: grid;
  412. margin-top: 5px;
  413. }
  414.  
  415. #AtBetter_setting_menu #save {
  416. cursor: pointer;
  417. display: inline-flex;
  418. padding: 0.5rem 1rem;
  419. background-color: #1aa06d;
  420. color: #ffffff;
  421. font-size: 1rem;
  422. line-height: 1.5rem;
  423. font-weight: 500;
  424. justify-content: center;
  425. width: 100%;
  426. border-radius: 0.375rem;
  427. border: none;
  428. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  429. }
  430. #AtBetter_setting_menu button#debug_button.debug_button {
  431. width: 18%;
  432. }
  433.  
  434. #AtBetter_setting_menu span.tip {
  435. color: #999;
  436. font-size: 12px;
  437. font-weight: 500;
  438. padding: 5px 0px;
  439. }
  440. /*设置面板-tip*/
  441. .help_tip {
  442. margin-right: auto;
  443. }
  444. .help_tip .tip_text {
  445. display: none;
  446. position: absolute;
  447. color: #697e91;
  448. font-weight: 400;
  449. letter-spacing: 0px;
  450. background-color: #ffffff;
  451. padding: 10px;
  452. margin: 5px 0px;
  453. border-radius: 4px;
  454. border: 1px solid #e4e7ed;
  455. box-shadow: 0px 0px 12px rgba(0, 0, 0, .12);
  456. z-index: 999;
  457. }
  458. .help_tip .tip_text p {
  459. margin-bottom: 5px;
  460. }
  461. .help_tip .tip_text:before {
  462. content: "";
  463. position: absolute;
  464. top: -20px;
  465. right: -10px;
  466. bottom: -10px;
  467. left: -10px;
  468. z-index: -1;
  469. }
  470. .help-icon {
  471. display: flex;
  472. cursor: help;
  473. width: 15px;
  474. color: rgb(255, 153, 0);
  475. margin-left: 5px;
  476. }
  477. #AtBetter_setting_menu .AtBetter_setting_menu_label_text .help_tip .help-icon {
  478. color: #7fbeb2;
  479. }
  480. .help_tip .help-icon:hover + .tip_text, .help_tip .tip_text:hover {
  481. display: block;
  482. cursor: help;
  483. width: 250px;
  484. }
  485.  
  486. /*设置面板-展开*/
  487. #is_showOpneAiAdvanced{
  488. width: 100%;
  489. background-color: aliceblue;
  490. padding: 8px;
  491. box-sizing: border-box;
  492. border-radius: 10px;
  493. }
  494. /*确认弹窗*/
  495. .wordsExceeded {
  496. z-index: 99999;
  497. box-shadow: 0px 0px 5px 1px rgb(0 0 0 / 10%), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  498. display: grid;
  499. position: fixed;
  500. top: 50%;
  501. left: 50%;
  502. transform: translate(-50%, -50%);
  503. border-radius: 4px;
  504. background-color: #ffffff;
  505. border: 1px solid #e4e7ed;
  506. color: #697e91;
  507. font-family: var(--vp-font-family-base);
  508. padding: 10px 20px 20px 20px;
  509. }
  510. .wordsExceeded button {
  511. display: inline-flex;
  512. justify-content: center;
  513. align-items: center;
  514. line-height: 1;
  515. white-space: nowrap;
  516. cursor: pointer;
  517. text-align: center;
  518. box-sizing: border-box;
  519. outline: none;
  520. transition: .1s;
  521. user-select: none;
  522. vertical-align: middle;
  523. -webkit-appearance: none;
  524. height: 24px;
  525. padding: 5px 11px;
  526. font-size: 12px;
  527. border-radius: 4px;
  528. color: #ffffff;
  529. background: #409eff;
  530. border-color: #409eff;
  531. border: none;
  532. margin-right: 12px;
  533. }
  534. .wordsExceeded button:hover{
  535. background-color:#79bbff;
  536. }
  537. .wordsExceeded .help-icon {
  538. margin: 0px 8px 0px 0px;
  539. height: 1em;
  540. width: 1em;
  541. line-height: 1em;
  542. display: inline-flex;
  543. justify-content: center;
  544. align-items: center;
  545. position: relative;
  546. fill: currentColor;
  547. font-size: inherit;
  548. }
  549. .wordsExceeded p {
  550. margin: 5px 0px;
  551. }
  552. /*更新检查*/
  553. div#update_panel {
  554. z-index: 9999;
  555. position: fixed;
  556. top: 50%;
  557. left: 50%;
  558. width: 240px;
  559. transform: translate(-50%, -50%);
  560. box-shadow: 0px 0px 4px 0px #0000004d;
  561. padding: 10px 20px 20px 20px;
  562. color: #444242;
  563. background-color: #f5f5f5;
  564. border: 1px solid #848484;
  565. border-radius: 8px;
  566. }
  567. div#update_panel #updating {
  568. cursor: pointer;
  569. display: inline-flex;
  570. padding: 0px;
  571. background-color: #1aa06d;
  572. color: #ffffff;
  573. font-size: 1rem;
  574. line-height: 1.5rem;
  575. font-weight: 500;
  576. justify-content: center;
  577. width: 100%;
  578. border-radius: 0.375rem;
  579. border: none;
  580. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  581. }
  582. div#update_panel #updating a {
  583. text-decoration: none;
  584. color: white;
  585. display: flex;
  586. position: inherit;
  587. top: 0;
  588. left: 0;
  589. width: 100%;
  590. height: 22px;
  591. font-size: 14px;
  592. justify-content: center;
  593. align-items: center;
  594. }
  595. #skip_menu {
  596. display: flex;
  597. margin-top: 10px;
  598. justify-content: flex-end;
  599. align-items: center;
  600. }
  601. #skip_menu .help_tip {
  602. margin-right: 5px;
  603. margin-left: -5px;
  604. }
  605. #skip_menu .help-icon {
  606. color: #f44336;
  607. }
  608. `);
  609.  
  610. // 获取cookie
  611. function getCookie(name) {
  612. const cookies = document.cookie.split(";");
  613. for (let i = 0; i < cookies.length; i++) {
  614. const cookie = cookies[i].trim();
  615. const [cookieName, cookieValue] = cookie.split("=");
  616.  
  617. if (cookieName === name) {
  618. return decodeURIComponent(cookieValue);
  619. }
  620. }
  621. return "";
  622. }
  623.  
  624. // 更新检查
  625. (function checkScriptVersion() {
  626. function compareVersions(version1 = "0", version2 = "0") {
  627. const v1Array = String(version1).split(".");
  628. const v2Array = String(version2).split(".");
  629. const minLength = Math.min(v1Array.length, v2Array.length);
  630. let result = 0;
  631. for (let i = 0; i < minLength; i++) {
  632. const curV1 = Number(v1Array[i]);
  633. const curV2 = Number(v2Array[i]);
  634. if (curV1 > curV2) {
  635. result = 1;
  636. break;
  637. } else if (curV1 < curV2) {
  638. result = -1;
  639. break;
  640. }
  641. }
  642. if (result === 0 && v1Array.length !== v2Array.length) {
  643. const v1IsBigger = v1Array.length > v2Array.length;
  644. const maxLenArray = v1IsBigger ? v1Array : v2Array;
  645. for (let i = minLength; i < maxLenArray.length; i++) {
  646. const curVersion = Number(maxLenArray[i]);
  647. if (curVersion > 0) {
  648. v1IsBigger ? result = 1 : result = -1;
  649. break;
  650. }
  651. }
  652. }
  653. return result;
  654. }
  655.  
  656. GM_xmlhttpRequest({
  657. method: "GET",
  658. url: "https://greasyfork.org/zh-CN/scripts/471106.json",
  659. timeout: 10 * 1e3,
  660. onload: function (response) {
  661. const scriptData = JSON.parse(response.responseText);
  662. const skipUpdate = getCookie("skipUpdate");
  663.  
  664. if (
  665. scriptData.name === GM_info.script.name &&
  666. compareVersions(scriptData.version, GM_info.script.version) === 1 &&
  667. skipUpdate !== "true"
  668. ) {
  669. const styleElement = GM_addStyle(darkenPageStyle);
  670. $("body").append(`
  671. <div id='update_panel'>
  672. <h3>${GM_info.script.name}有新版本!</h3>
  673. <hr>
  674. <div class='update_panel_menu'>
  675. <span class ='tip'>版本信息:${GM_info.script.version} ${scriptData.version}</span>
  676. </div>
  677. <br>
  678. <div id="skip_menu">
  679. <div class="help_tip">
  680. `+ helpCircleHTML + `
  681. <div class="tip_text">
  682. <p><b>更新遇到了问题?</b></p>
  683. <p>由于 Greasyfork 平台的原因,当新版本刚发布时,点击 Greasyfork 上的更新按钮<u>可能</u>会出现<u>实际更新/安装的却是上一个版本</u>的情况</p>
  684. <p>通常你只需要稍等几分钟,然后再次前往更新/安装即可</p>
  685. <p>你也可以<u>点击下方按钮,在本次浏览器会话期间将不再提示更新</u></p>
  686. <button id='skip_update' class='html2mdButton'>暂不更新</button>
  687. </div>
  688. </div>
  689. <button id='updating'><a target="_blank" href="${scriptData.url}">更新</a></button>
  690. </div>
  691. </div>
  692. `);
  693.  
  694. $("#skip_update").click(function () {
  695. document.cookie = "skipUpdate=true; expires=session; path=/";
  696. styleElement.remove();
  697. $("#update_panel").remove();
  698. });
  699. }
  700. }
  701. });
  702.  
  703. })();
  704.  
  705. // 汉化替换
  706. (function () {
  707. if (!bottomZh_CN) return;
  708.  
  709. // 文本节点遍历替换
  710. $(document).ready(function () {
  711. function traverseTextNodes(node, rules) {
  712. if (!node) return;
  713. if (node.nodeType === Node.TEXT_NODE) {
  714. rules.forEach(rule => {
  715. const regex = new RegExp(rule.match, 'g');
  716. node.textContent = node.textContent.replace(regex, rule.replace);
  717. });
  718. } else {
  719. $(node).contents().each((_, child) => traverseTextNodes(child, rules));
  720. }
  721. }
  722.  
  723. // 严格
  724. function strictTraverseTextNodes(node, rules) {
  725. if (!node) return;
  726. if (node.nodeType === Node.TEXT_NODE) {
  727. const nodeText = node.textContent.trim();
  728. rules.forEach(rule => {
  729. if (nodeText === rule.match) {
  730. node.textContent = rule.replace;
  731. }
  732. });
  733. } else {
  734. $(node).contents().each((_, child) => strictTraverseTextNodes(child, rules));
  735. }
  736. }
  737.  
  738. const rules1 = [
  739. { match: 'Present Contests', replace: '目前的比赛' },
  740. { match: 'Past Contests', replace: '过去的比赛' },
  741. { match: 'Top', replace: '首页' },
  742. { match: 'Tasks', replace: '问题集' },
  743. { match: 'Clarifications', replace: '问题答疑' },
  744. { match: 'Submit', replace: '提交' },
  745. { match: 'Results', replace: '结果' },
  746. { match: 'All Submissions', replace: '所有提交' },
  747. { match: 'My Submissions', replace: '我的提交' },
  748. { match: 'My Score', replace: '我的得分' },
  749. { match: 'Virtual Standings', replace: '虚拟排名' },
  750. { match: 'Standings', replace: '排名' },
  751. { match: 'Custom Test', replace: '自定义测试' },
  752. { match: 'Editorial', replace: '题解' },
  753. { match: 'Discuss', replace: '讨论' },
  754. { match: 'Algorithm', replace: '算法' },
  755. { match: 'Heuristic', replace: '启发式' },
  756. { match: 'Active Users', replace: '活跃用户' },
  757. { match: 'All Users', replace: '所有用户' },
  758. { match: 'Profile', replace: '个人资料' },
  759. { match: 'Competition History', replace: '比赛记录' },
  760. { match: 'General Settings', replace: '常规设置' },
  761. { match: 'Settings', replace: '设置' },
  762. { match: 'Change/Verify Email address', replace: '更改/验证电子邮件地址' },
  763. { match: 'Remind Username', replace: '提醒用户名' },
  764. { match: 'Change Username', replace: '更改用户名' },
  765. { match: 'Delete Account', replace: '删除账户' },
  766. { match: 'Change Photo', replace: '更改照片' },
  767. { match: 'Change Password', replace: '更改密码' },
  768. { match: 'Manage Fav', replace: '管理收藏' },
  769. { match: 'Other', replace: '其他' },
  770. { match: 'Remind Username', replace: '提醒用户名' },
  771. { match: 'Change Username', replace: '更改用户名' },
  772. { match: 'Delete Account', replace: '删除账户' }
  773. ];
  774. traverseTextNodes($('.nav'), rules1);
  775.  
  776. const rules2 = [
  777. { match: 'My Profile', replace: '个人资料' },
  778. { match: 'General Settings', replace: '常规设置' },
  779. { match: 'Change Photo', replace: '更改照片' },
  780. { match: 'Change Password', replace: '更改密码' },
  781. { match: 'Manage Fav', replace: '管理收藏' },
  782. { match: 'Sign Out', replace: '退出登录' }
  783. ];
  784. traverseTextNodes($('.dropdown-menu'), rules2);
  785.  
  786. const rules3 = [
  787. { match: 'Search in Archive', replace: '搜索存档' },
  788. { match: 'Permanent Contests', replace: '永久比赛' },
  789. { match: 'Upcoming Contests', replace: '即将举行的比赛' },
  790. { match: 'Recent Contests', replace: '最近的比赛' },
  791. { match: 'Ranking', replace: '排行' },
  792. { match: 'Contest Archive', replace: '比赛档案' },
  793. { match: 'Information', replace: '信息' },
  794. { match: 'About the situation where it is difficult to access the contest site', replace: '关于难以访问比赛网站的情况' },
  795. ];
  796. traverseTextNodes($('.panel-title'), rules3);
  797. traverseTextNodes($('.h3'), rules3);
  798. strictTraverseTextNodes($('h3'), rules3);
  799.  
  800. const rules4 = [
  801. { match: 'Rated Range', replace: '限定范围' },
  802. { match: 'Category', replace: '类别' },
  803. { match: 'Search', replace: '搜索' }
  804. ];
  805. traverseTextNodes($('.filter-body-heading'), rules4);
  806.  
  807. const rules5 = [
  808. { match: 'Current Password', replace: '当前密码' },
  809. { match: 'New Password', replace: '新密码' },
  810. { match: 'Confirm Password', replace: '确认密码' },
  811. { match: 'Update', replace: '更新' },
  812. { match: 'Contest Name', replace: '比赛名称' },
  813. { match: 'Username', replace: '用户名' },
  814. { match: 'Password', replace: '密码' },
  815. { match: 'Sign In', replace: '登录' },
  816. { match: 'Sign Up', replace: '注册' },
  817. { match: 'Nickname', replace: '昵称' },
  818. { match: 'Country/Region', replace: '国家/地区' },
  819. { match: 'Birth Year', replace: '出生年份' },
  820. { match: 'Affiliation', replace: '机构' },
  821. { match: 'Email Notifications', replace: '邮件通知' },
  822. { match: 'New Email address', replace: '新电子邮件地址' },
  823. { match: 'Request Email address verify', replace: '请求电子邮件地址验证' },
  824. { match: 'I agree.', replace: '我同意。' },
  825. { match: 'Do you live in Japan?', replace: '您是否居住在日本?' },
  826. { match: 'Family Name', replace: '姓氏' },
  827. { match: 'First Name', replace: '名字' },
  828. { match: 'Category', replace: '分类' },
  829. { match: 'College Students (Master or Doctor cource)', replace: '大学生(硕士或博士课程)' },
  830. { match: 'College Students', replace: '大学生' },
  831. { match: 'Technical college/Vocational school/Short-term university', replace: '技术学院/职业学校/短期大学' },
  832. { match: 'High school', replace: '高中' },
  833. { match: 'Junior high school', replace: '初中' },
  834. { match: 'Office worker', replace: '上班族' },
  835. { match: 'Other', replace: '其他' },
  836. { match: 'Organization Name \\(Company Name or School Name\\)', replace: '组织名称(公司名称或学校名称)' },
  837. { match: 'Depertment \\(For Students\\)', replace: '部门(适用于学生)' },
  838. { match: 'Do you have any intention or plan to find a job or change jobs in 2023 or 2024?', replace: '您是否有意向或计划在2023年或2024年找工作或换工作?' },
  839. { match: 'Graduation Schedule', replace: '毕业时间表' },
  840. { match: "I'm already employed.", replace: '我已经就业了。' },
  841. { match: 'Later years', replace: '以后的几年' },
  842. { match: 'I am interested in going into the digital area of Toyota Motor Corporation\'s operations.', replace: '我对加入丰田汽车公司的数字领域感兴趣。' },
  843. { match: 'Toyota is currently actively recruiting engineers. Would you like to be considered?', replace: '丰田目前正在积极招聘工程师。您有兴趣被考虑吗?' },
  844. { match: 'I\'d like to talk to you first.', replace: '我想先和您交谈。' },
  845. { match: 'Department name', replace: '部门名称' },
  846. { match: 'What kind of work do you currently do?', replace: '您目前从事什么样的工作?' },
  847. { match: 'How can the Algorithms Group of the Digital Transformation Office help\\?', replace: '数字转型办公室的算法组可以如何帮助您?' }
  848. ];
  849. traverseTextNodes($('.form-group'), rules5);
  850.  
  851. const rules6 = [
  852. { match: 'Unofficial(unrated)', replace: '非官方(无评级)' },
  853. { match: 'Sponsored Parallel(rated)', replace: '赞助平行(有评级)' },
  854. { match: 'Sponsored Parallel(unrated)', replace: '赞助平行(无评级)' },
  855. { match: 'Sponsored Heuristic Contest', replace: '启发式赞助比赛' },
  856. { match: 'All', replace: '全部' },
  857. { match: 'AtCoder Typical Contest', replace: 'AtCoder 经典比赛' },
  858. { match: 'PAST Archive', replace: 'PAST 比赛归档' },
  859. { match: 'JOI Archive', replace: 'JOI 比赛归档' },
  860. { match: 'Sponsored Tournament', replace: '赞助比赛' },
  861. { match: 'Sponsored ABC', replace: '赞助 ABC' },
  862. { match: 'Sponsored ARC', replace: '赞助 ARC' },
  863. { match: 'Heuristic Contest', replace: '启发式比赛' }
  864. ];
  865. strictTraverseTextNodes($('#category-btn-group'), rules6);
  866.  
  867. const rules7 = [
  868. { match: 'Task', replace: '任务' },
  869. { match: 'Language', replace: '语言' },
  870. { match: 'Source Code', replace: '源代码' },
  871. { match: 'Standard Input', replace: '标准输入' },
  872. { match: 'Standard Output', replace: '标准输出' },
  873. { match: 'Standard Error', replace: '标准错误' },
  874. ];
  875. traverseTextNodes($('.control-label'), rules7);
  876.  
  877. const rules8 = [
  878. { match: 'Permanent Contests', replace: '永久比赛' },
  879. { match: 'Upcoming Contests', replace: '即将举行的比赛' },
  880. { match: 'Recent Contests', replace: '最近的比赛' }
  881. ];
  882. traverseTextNodes($('h4'), rules8);
  883.  
  884. const rules9 = [
  885. { match: 'Open File', replace: '打开文件' },
  886. { match: 'Toggle Editor', replace: '切换编辑器' },
  887. { match: 'Auto Height', replace: '自动调整高度' }
  888. ];
  889. traverseTextNodes($('.editor-buttons'), rules9);
  890.  
  891. const rules10 = [
  892. { match: 'Register', replace: '报名' },
  893. { match: 'Virtual Participation', replace: '虚拟参加' }
  894. ];
  895. traverseTextNodes($('.btn'), rules10);
  896.  
  897. const rules11 = [
  898. { match: 'Home', replace: '主页' },
  899. { match: 'Contest', replace: '比赛' },
  900. { match: 'Ranking', replace: '排名' },
  901. { match: 'Sign Up', replace: '注册' },
  902. { match: 'Sign In', replace: '登录' },
  903. ];
  904. strictTraverseTextNodes($('#navbar-collapse'), rules11);
  905. });
  906. })();
  907.  
  908. // 设置面板
  909. $(document).ready(function () {
  910. var htmlContent = "<button class='html2mdButton AtBetter_setting'>AtcoderBetter设置</button>";
  911. $('#navbar-collapse > ul:nth-child(2) > li:last-child').after("<li class='dropdown'>" + htmlContent + "</li>");
  912. });
  913.  
  914. $(document).ready(function () {
  915. const $settingBtns = $(".AtBetter_setting");
  916. $settingBtns.click(() => {
  917. const styleElement = GM_addStyle(darkenPageStyle);
  918. $settingBtns.prop("disabled", true).addClass("open");
  919. $("body").append(`
  920. <div id='AtBetter_setting_menu'>
  921. <div class="tool-box">
  922. <button class="btn-close">×</button>
  923. </div>
  924. <h4>基本设置</h4>
  925. <hr>
  926. <div class='AtBetter_setting_list'>
  927. <label for="bottomZh_CN">界面汉化</label>
  928. <input type="checkbox" id="bottomZh_CN" name="bottomZh_CN">
  929. </div>
  930. <div class='AtBetter_setting_list'>
  931. <label for="showLoading">显示加载信息</label>
  932. <div class="help_tip">
  933. `+ helpCircleHTML + `
  934. <div class="tip_text">
  935. <p>当你开启 显示加载信息 时,每次加载页面时会在上方显示加载信息提示:“Atcoder Better! —— xxx”</p>
  936. <p>这用于了解脚本当前的工作情况,<strong>如果你不想看到,可以选择关闭</strong></p>
  937. <p><u>需要说明的是,如果你需要反馈脚本的任何加载问题,请开启该选项后再截图,以便于分析问题</u></p>
  938. </div>
  939. </div>
  940. <input type="checkbox" id="showLoading" name="showLoading">
  941. </div>
  942. <div class='AtBetter_setting_list'>
  943. <label for="enableSegmentedTranslation">分段翻译</label>
  944. <div class="help_tip">
  945. `+ helpCircleHTML + `
  946. <div class="tip_text">
  947. <p>分段翻译会对区域内的每一个&#60;&#112;&#47;&#62;和&#60;&#105;&#47;&#62;标签依次进行翻译,</p>
  948. <p>这通常在翻译<strong>长篇博客</strong>或者<strong>超长的题目</strong>时很有用。</p>
  949. <p><u>注意:开启分段翻译会产生如下问题:</u></p>
  950. <p>- 使得翻译接口无法知晓整个文本的上下文信息,会降低翻译质量。</p>
  951. <p>- 会有<strong>部分内容不会被翻译</strong>,因为它们不是&#60;&#112;&#47;&#62;或&#60;&#105;&#47;&#62;标签</p>
  952. </div>
  953. </div>
  954. <input type="checkbox" id="enableSegmentedTranslation" name="enableSegmentedTranslation">
  955. </div>
  956. <div class='AtBetter_setting_list'>
  957. <label for="showJumpToLuogu">显示跳转到洛谷</label>
  958. <div class="help_tip">
  959. `+ helpCircleHTML + `
  960. <div class="tip_text">
  961. <p>洛谷OJ上收录了Atcoder的部分题目,一些题目有翻译和题解</p>
  962. <p>开启显示后,如果当前题目被收录,则会在题目的右上角显示洛谷标志,</p>
  963. <p>点击即可一键跳转到该题洛谷的对应页面。</strong></p>
  964. </div>
  965. </div>
  966. <input type="checkbox" id="showJumpToLuogu" name="showJumpToLuogu">
  967. </div>
  968. <div class='AtBetter_setting_list'>
  969. <label for="loaded"><span style="font-size: 14px;">兼容选项-不等待页面资源加载</span></label>
  970. <div class="help_tip">
  971. `+ helpCircleHTML + `
  972. <div class="tip_text">
  973. <p>为了防止在页面资源未加载完成前(主要是各种js)执行脚本产生意外的错误,脚本默认会等待 window.onload 事件”</p>
  974. <p>如果您的页面上方的加载信息始终停留在:“等待页面资源加载”,</p>
  975. <p><u>您首先应该是否是网络问题,</u></p>
  976. <p>如果页面实际已经加载完成,那这可能是由于 window.onload 事件在您的浏览器中触发过早(早于document.ready),</p>
  977. <p>您可以尝试开启该选项来不再等待 window.onload 事件</p>
  978. <p><u>如果没有上述问题,请不要开启该选项</u></p>
  979. </div>
  980. </div>
  981. <input type="checkbox" id="loaded" name="loaded">
  982. </div>
  983. <h4>翻译设置</h4>
  984. <hr>
  985. <label>
  986. <input type='radio' name='translation' value='deepl'>
  987. <span class='AtBetter_setting_menu_label_text'>deepl翻译</span>
  988. </label>
  989. <label>
  990. <input type='radio' name='translation' value='youdao'>
  991. <span class='AtBetter_setting_menu_label_text'>有道翻译</span>
  992. </label>
  993. <label>
  994. <input type='radio' name='translation' value='google'>
  995. <span class='AtBetter_setting_menu_label_text'>Google翻译</span>
  996. </label>
  997. <label>
  998. <input type='radio' name='translation' value='openai'>
  999. <span class='AtBetter_setting_menu_label_text'>使用ChatGPT翻译(API)
  1000. <div class="help_tip">
  1001. `+ helpCircleHTML + `
  1002. <div class="tip_text">
  1003. <p><b>请确保你能够正常访问OpenAIapi</b></p>
  1004. <p>Atcoder Better!使用 gpt-3.5-turbo 模型进行翻译,脚本的所有请求均在本地完成</p>
  1005. <p>你需要输入自己的OpenAI KEY,<a target="_blank" href="https://platform.openai.com/account/usage">官网</a></p>
  1006. </div>
  1007. </div>
  1008. </span>
  1009. </label>
  1010. <label>
  1011. <input type='radio' name='translation' value='api2d'>
  1012. <span class='AtBetter_setting_menu_label_text'>使用api2d翻译(API)
  1013. <div class="help_tip">
  1014. `+ helpCircleHTML + `
  1015. <div class="tip_text">
  1016. <p>api2d是国内的一家提供代理直连访问OpenAIapi的服务商,相当于OpenAIapi的套壳</p>
  1017. <p>Atcoder Better!使用 gpt-3.5-turbo 模型进行翻译,脚本的所有请求均在本地完成</p>
  1018. <p>你需要输入自己的api2d KEY,<a target="_blank" href="https://api2d.com/profile">官网</a></p>
  1019. </div>
  1020. </div>
  1021. </span>
  1022. </label>
  1023. <div class='AtBetter_setting_menu_input' id='openai' style='display: none;'>
  1024. <label for='openai_key'>KEY:</label><input type='text' id='openai_key'>
  1025. <div class='AtBetter_setting_list'>
  1026. <label for="showOpneAiAdvanced">使用代理API</label>
  1027. <div class="help_tip">
  1028. `+ helpCircleHTML + `
  1029. <div class="tip_text">
  1030. <p>使用你指定的API来代理访问 gpt-3.5-turbo 模型进行翻译,脚本的所有请求均在本地完成</p>
  1031. <p>建议你自建代理,而不是使用他人公开的代理,那是危险的</p>
  1032. <p><strong>由于你指定了自定义的APITampermonkey会对你的跨域请求进行警告,请自行授权</strong></p>
  1033. </div>
  1034. </div>
  1035. <input type="checkbox" id="showOpneAiAdvanced" name="showOpneAiAdvanced">
  1036. </div>
  1037. <div id="is_showOpneAiAdvanced">
  1038. <label for='openai_proxy'>Proxy API:</label><input type='text' id='openai_proxy'>
  1039. </div>
  1040. </div>
  1041. <div class='AtBetter_setting_menu_input' id='api2d' style='display: none;'>
  1042. <label for='api2d_key'>KEY:</label><input type='text' id='api2d_key'>
  1043. <div class='AtBetter_setting_list'>
  1044. <label for="x_api2d_no_cache">使用缓存</label>
  1045. <div class="help_tip">
  1046. `+ helpCircleHTML + `
  1047. <div class="tip_text">
  1048. <p>API2D 的服务器会对请求结果做缓存,如果请求文本的hash值相同,会直接返回缓存的结果。缓存命中之后,本次请求不会扣除任何点数。</p>
  1049. <p>缓存会保存 24 小时,如果不想使用缓存,你可以关闭“使用缓存”来跳过缓存,强制 API2D 服务器发送新请求。<a target="_blank" href="https://api2d.com/wiki/doc">详请阅读官方文档</a></p>
  1050. </div>
  1051. </div>
  1052. <input type="checkbox" id="x_api2d_no_cache" name="x_api2d_no_cache">
  1053. </div>
  1054. </div>
  1055. <br>
  1056. <button id='save'>保存</button>
  1057. </div>
  1058. `);
  1059. $("#bottomZh_CN").prop("checked", GM_getValue("bottomZh_CN") === true);
  1060. $("#showLoading").prop("checked", GM_getValue("showLoading") === true);
  1061. $("#enableSegmentedTranslation").prop("checked", GM_getValue("enableSegmentedTranslation") === true);
  1062. $("#showJumpToLuogu").prop("checked", GM_getValue("showJumpToLuogu") === true);
  1063. $("#loaded").prop("checked", GM_getValue("loaded") === true);
  1064. $("#x_api2d_no_cache").prop("checked", GM_getValue("x_api2d_no_cache") === true);
  1065. $("#showOpneAiAdvanced").prop("checked", GM_getValue("showOpneAiAdvanced") === true);
  1066. $("input[name='translation'][value='" + translation + "']").prop("checked", true);
  1067. $("input[name='translation']").css("color", "gray");
  1068. if (translation == "openai") {
  1069. $("#openai").show();
  1070. $("#openai_key").val(GM_getValue("openai_key"));
  1071. $("#openai_proxy").val(GM_getValue("openai_proxy"));
  1072. $("#openai_key").css("color", "gray");
  1073. } else if (translation == "api2d") {
  1074. $("#api2d").show();
  1075. $("#api2d_key").val(GM_getValue("api2d_key"));
  1076. $("#api2d_key").css("color", "gray");
  1077. }
  1078. // 当单选框被选中时,显示对应的输入框,同时隐藏其他输入框
  1079. $("input[name='translation']").change(function () {
  1080. var selected = $(this).val(); // 获取当前选中的值
  1081. if (selected === "openai") {
  1082. $("#openai").show();
  1083. $("#openai_key").val(GM_getValue("openai_key"));
  1084. $("#showOpneAiAdvanced").prop("checked", showOpneAiAdvanced);
  1085. if (showOpneAiAdvanced) {
  1086. $("#is_showOpneAiAdvanced").show();
  1087. $("#openai_proxy").val(GM_getValue("openai_proxy"));
  1088. }
  1089. else $("#is_showOpneAiAdvanced").hide();
  1090. $("#api2d").hide();
  1091. } else if (selected === "api2d") {
  1092. $("#api2d").show();
  1093. $("#api2d_key").val(GM_getValue("api2d_key"));
  1094. $("#x_api2d_no_cache").prop("checked", GM_getValue("x_api2d_no_cache"));
  1095. $("#openai").hide();
  1096. } else {
  1097. $("#openai, #api2d").hide();
  1098. }
  1099. });
  1100.  
  1101. // ChatGPT高级选项
  1102. $("input[name='showOpneAiAdvanced']").change(function () {
  1103. var isChecked = $(this).is(":checked");
  1104. if (isChecked) {
  1105. $("#is_showOpneAiAdvanced").show();
  1106. } else {
  1107. $("#is_showOpneAiAdvanced").hide();
  1108. }
  1109. });
  1110.  
  1111. const $settingMenu = $("#AtBetter_setting_menu");
  1112.  
  1113. $("#save").click(function () {
  1114. GM_setValue("bottomZh_CN", $("#bottomZh_CN").prop("checked"));
  1115. GM_setValue("showLoading", $("#showLoading").prop("checked"));
  1116. GM_setValue("loaded", $("#loaded").prop("checked"));
  1117. GM_setValue("enableSegmentedTranslation", $("#enableSegmentedTranslation").prop("checked"));
  1118. GM_setValue("showJumpToLuogu", $("#showJumpToLuogu").prop("checked"));
  1119. var translation = $("input[name='translation']:checked").val();
  1120. var openai_key = $("#openai_key").val();
  1121. var openai_proxy = $("#openai_proxy").val();
  1122. var api2d_key = $("#api2d_key").val();
  1123. GM_setValue("translation", translation);
  1124. if (translation == "openai") {
  1125. GM_setValue("openai_key", openai_key);
  1126. GM_setValue("openai_proxy", openai_proxy);
  1127. } else if (translation == "api2d") {
  1128. GM_setValue("api2d_key", api2d_key);
  1129. GM_setValue("x_api2d_no_cache", $("#x_api2d_no_cache").prop("checked"));
  1130. }
  1131. $settingMenu.remove();
  1132. $(styleElement).remove();
  1133. location.reload();
  1134. });
  1135.  
  1136. // 关闭
  1137. $settingMenu.on("click", ".btn-close", () => {
  1138. $settingMenu.remove();
  1139. $settingBtns.prop("disabled", false).removeClass("open");
  1140. $(styleElement).remove();
  1141. });
  1142. });
  1143. });
  1144.  
  1145. // html2md转换/处理规则
  1146. var turndownService = new TurndownService({ bulletListMarker: '-', escape: (text) => text });
  1147. var turndown = turndownService.turndown;
  1148.  
  1149. // 保留原始
  1150. turndownService.keep(['del']);
  1151.  
  1152. turndownService.addRule('removeByClass', {
  1153. filter: function (node) {
  1154. return node.classList.contains('html2md-panel') ||
  1155. node.classList.contains('div-btn-copy') ||
  1156. node.classList.contains('btn-copy')
  1157. },
  1158. replacement: function () {
  1159. return '';
  1160. }
  1161. });
  1162.  
  1163. // inline math
  1164. turndownService.addRule('inline-math', {
  1165. filter: function (node, options) {
  1166. return node.tagName.toLowerCase() == "span" && node.className == "katex";
  1167. },
  1168. replacement: function (content, node) {
  1169. return "$" + $(node).find('annotation').text() + "$";
  1170. }
  1171. });
  1172.  
  1173. // block math
  1174. turndownService.addRule('block-math', {
  1175. filter: function (node, options) {
  1176. return node.tagName.toLowerCase() == "span" && node.className == "katex-display";
  1177. },
  1178. replacement: function (content, node) {
  1179. return "\n$$\n" + $(node).find('annotation').text() + "\n$$\n";
  1180. }
  1181. });
  1182.  
  1183. // pre
  1184. turndownService.addRule('pre', {
  1185. filter: function (node, options) {
  1186. return node.tagName.toLowerCase() == "pre";
  1187. },
  1188. replacement: function (content, node) {
  1189. return "```\n" + content + "```\n";
  1190. }
  1191. });
  1192.  
  1193. // bordertable
  1194. turndownService.addRule('bordertable', {
  1195. filter: 'table',
  1196. replacement: function (content, node) {
  1197. if (node.classList.contains('table')) {
  1198. var output = [],
  1199. thead = '',
  1200. trs = node.querySelectorAll('tr');
  1201. if (trs.length > 0) {
  1202. var ths = trs[0].querySelectorAll('th');
  1203. if (ths.length > 0) {
  1204. thead = '| ' + Array.from(ths).map(th => turndownService.turndown(th.innerHTML.trim())).join(' | ') + ' |\n'
  1205. + '| ' + Array.from(ths).map(() => ' --- ').join('|') + ' |\n';
  1206. }
  1207. }
  1208. var rows = node.querySelectorAll('tr');
  1209. Array.from(rows).forEach(function (row, i) {
  1210. if (i > 0) {
  1211. var cells = row.querySelectorAll('td,th');
  1212. var trow = '| ' + Array.from(cells).map(cell => turndownService.turndown(cell.innerHTML.trim())).join(' | ') + ' |';
  1213. output.push(trow);
  1214. }
  1215. });
  1216. return thead + output.join('\n');
  1217. } else {
  1218. return content;
  1219. }
  1220. }
  1221. });
  1222.  
  1223.  
  1224. // 随机数生成
  1225. function getRandomNumber(numDigits) {
  1226. let min = Math.pow(10, numDigits - 1);
  1227. let max = Math.pow(10, numDigits) - 1;
  1228. return Math.floor(Math.random() * (max - min + 1)) + min;
  1229. }
  1230.  
  1231. // 题目markdown转换/翻译面板
  1232. function addButtonPanel(parent, suffix, type, is_simple = false) {
  1233. let htmlString = `<div class='html2md-panel'>
  1234. <button class='html2mdButton html2md-view${suffix}'>MarkDown视图</button>
  1235. <button class='html2mdButton html2md-cb${suffix}'>Copy</button>
  1236. <button class='html2mdButton translateButton${suffix}'>翻译</button>
  1237. </div>`;
  1238. if (type === "this_level") {
  1239. $(parent).before(htmlString);
  1240. } else if (type === "child_level") {
  1241. $(parent).prepend(htmlString);
  1242. }
  1243. if (is_simple) {
  1244. $('.html2md-panel').find('.html2mdButton.html2md-view' + suffix + ', .html2mdButton.html2md-cb' + suffix).remove();
  1245. }
  1246. }
  1247.  
  1248. function addButtonWithHTML2MD(parent, suffix, type) {
  1249. $(document).on("click", ".html2md-view" + suffix, function () {
  1250. var target, removedChildren = $();
  1251. if (type === "this_level") {
  1252. target = $(".html2md-view" + suffix).parent().next().get(0);
  1253. } else if (type === "child_level") {
  1254. target = $(".html2md-view" + suffix).parent().parent().get(0);
  1255. removedChildren = $(".html2md-view" + suffix).parent().parent().children(':first').detach();
  1256. }
  1257. if (target.viewmd) {
  1258. target.viewmd = false;
  1259. $(this).text("MarkDown视图");
  1260. $(this).removeClass("mdViewed");
  1261. $(target).html(target.original_html);
  1262. } else {
  1263. target.viewmd = true;
  1264. if (!target.original_html) {
  1265. target.original_html = $(target).html();
  1266. }
  1267. if (!target.markdown) {
  1268. target.markdown = turndownService.turndown($(target).html());
  1269. }
  1270. $(this).text("原始内容");
  1271. $(this).addClass("mdViewed");
  1272. $(target).html(`<span class="mdViewContent" oninput="$(this).parent().get(0).markdown=this.value;" style="width:auto; height:auto;">${target.markdown}</span>`);
  1273. }
  1274. // 恢复删除的元素
  1275. if (removedChildren) $(target).prepend(removedChildren);
  1276. });
  1277. }
  1278.  
  1279. function addButtonWithCopy(parent, suffix, type) {
  1280. $(document).on("click", ".html2md-cb" + suffix, function () {
  1281. let target, removedChildren, text;
  1282. if (type === "this_level") {
  1283. target = $(".translateButton" + suffix).parent().next().eq(0).clone();
  1284. } else if (type === "child_level") {
  1285. target = $(".translateButton" + suffix).parent().parent().eq(0).clone();
  1286. $(target).children(':first').remove();
  1287. }
  1288. if ($(target).find('.mdViewContent').length <= 0) {
  1289. text = turndownService.turndown($(target).html());
  1290. } else {
  1291. text = $(target).find('.mdViewContent').text();
  1292. }
  1293. GM_setClipboard(text);
  1294. $(this).addClass("copied");
  1295. $(this).text("Copied");
  1296. // 更新复制按钮文本
  1297. setTimeout(() => {
  1298. $(this).removeClass("copied");
  1299. $(this).text("Copy");
  1300. }, 2000);
  1301. $(target).remove();
  1302. });
  1303. }
  1304.  
  1305. async function addButtonWithTranslation(parent, suffix, type) {
  1306. $(document).on('click', '.translateButton' + suffix, async function () {
  1307. $(this).removeClass("translated");
  1308. $(this).text("翻译中");
  1309. $(this).css("cursor", "not-allowed");
  1310. var target, element_node, block, result, errerNum = 0;
  1311. if (type === "this_level") block = $(".translateButton" + suffix).parent().next();
  1312. else if (type === "child_level") block = $(".translateButton" + suffix).parent().parent();
  1313. // 分段翻译
  1314. if (enableSegmentedTranslation) {
  1315. var pElements = block.find("p, li");
  1316. for (let i = 0; i < pElements.length; i++) {
  1317. target = $(pElements[i]).eq(0).clone();
  1318. if (type === "child_level") $(target).children(':first').remove();
  1319. element_node = pElements[i];
  1320. if (type === "child_level") {
  1321. $(pElements[i]).append("<div></div>");
  1322. element_node = $(pElements[i]).find("div:last-child").get(0);
  1323. }
  1324. result = await blockProcessing(target, element_node, $(".translateButton" + suffix));
  1325. if (result.status) errerNum += 1;
  1326. $(target).remove();
  1327. if (translation == "deepl") await new Promise(resolve => setTimeout(resolve, 2000));
  1328. }
  1329. } else {
  1330. target = block.eq(0).clone();
  1331. if (type === "child_level") $(target).children(':first').remove();
  1332. element_node = $(block).get(0);
  1333. if (type === "child_level") {
  1334. $(parent).append("<div></div>");
  1335. element_node = $(parent).find("div:last-child").get(0);
  1336. }
  1337. //是否跳过折叠块
  1338. if ($(target).find('details').length > 0) {
  1339. const shouldSkip = await skiFoldingBlocks();
  1340. if (shouldSkip) {
  1341. $(target).find('details').remove();
  1342. } else {
  1343. $(target).find('.html2md-panel').remove();
  1344. }
  1345. }
  1346.  
  1347. //跳过代码块
  1348. $(target).find('pre').remove();
  1349.  
  1350. result = await blockProcessing(target, element_node, $(".translateButton" + suffix));
  1351. if (result.status) errerNum += 1;
  1352. $(target).remove();
  1353. }
  1354. if (!errerNum) {
  1355. $(this).addClass("translated")
  1356. .text("已翻译")
  1357. .prop("disabled", true);
  1358. }
  1359. // 重新翻译按钮
  1360. if ($(this).next('.reTranslation').length === 0) {
  1361. const reTranslateBtn = $('<button>').addClass('html2mdButton reTranslation').html('&circlearrowright;').attr('title', '重新翻译');
  1362. reTranslateBtn.on('click', function () {
  1363. result.translateDiv.remove();
  1364. result.copyDiv.remove();
  1365. result.copyButton.remove();
  1366. x_api2d_no_cache ? (x_api2d_no_cache = false, $(this).prev().prop("disabled", false), $(this).prev().click(), x_api2d_no_cache = true) : ($(this).prev().click());
  1367. });
  1368. $(this).after(reTranslateBtn);
  1369. } else {
  1370. const reTranslateBtn = $(this).next('.reTranslation');
  1371. reTranslateBtn.off('click').on('click', function () {
  1372. result.translateDiv.remove();
  1373. result.copyDiv.remove();
  1374. result.copyButton.remove();
  1375. x_api2d_no_cache ? (x_api2d_no_cache = false, $(this).prev().prop("disabled", false), $(this).prev().click(), x_api2d_no_cache = true) : ($(this).prev().click());
  1376. });
  1377. }
  1378. });
  1379. }
  1380.  
  1381. // 块处理
  1382. async function blockProcessing(target, element_node, button) {
  1383. if (!target.markdown) {
  1384. target.markdown = turndownService.turndown($(target).html());
  1385. }
  1386. const textarea = document.createElement('textarea');
  1387. textarea.value = target.markdown;
  1388. var result = await translateProblemStatement(textarea.value, element_node, $(button));
  1389. //
  1390. if (result.status == 1) {
  1391. $(button).addClass("error")
  1392. .text("翻译中止")
  1393. .css("cursor", "pointer")
  1394. .prop("disabled", false);
  1395. $(result.translateDiv).remove();
  1396. $(target).remove();
  1397. } else if (result.status == 2) {
  1398. result.translateDiv.classList.add("error_translate");
  1399. $(button).addClass("error")
  1400. .text("翻译出错");
  1401. $(target).remove();
  1402. }
  1403. return result;
  1404. }
  1405.  
  1406. function addConversionButton() {
  1407. // 基本添加
  1408. $('section').each(function () {
  1409. let id = "_" + getRandomNumber(8);
  1410. addButtonPanel(this, id, "this_level");
  1411. addButtonWithHTML2MD(this, id, "this_level");
  1412. addButtonWithCopy(this, id, "this_level");
  1413. addButtonWithTranslation(this, id, "this_level");
  1414. });
  1415.  
  1416. // 添加按钮到题解部分
  1417. if (window.location.href.includes("editorial")) {
  1418. let contestNavTabs = $("#contest-nav-tabs");
  1419. let nextElement = contestNavTabs.next();
  1420. let id = "_editorial_" + getRandomNumber(8);
  1421. addButtonPanel(nextElement, id, "child_level");
  1422. addButtonWithHTML2MD(nextElement, id, "child_level");
  1423. addButtonWithCopy(nextElement, id, "child_level");
  1424. addButtonWithTranslation(nextElement, id, "child_level");
  1425. }
  1426. if (window.location.href.includes("editorial")) {
  1427. let contestNavTabs = $("#contest-nav-tabs");
  1428. let nextElement = contestNavTabs.next().children().eq(-2);
  1429. let id = "_editorial_" + getRandomNumber(8);
  1430. addButtonPanel(nextElement, id, "child_level");
  1431. addButtonWithHTML2MD(nextElement, id, "child_level");
  1432. addButtonWithCopy(nextElement, id, "child_level");
  1433. addButtonWithTranslation(nextElement, id, "child_level");
  1434. }
  1435.  
  1436. // 添加按钮到折叠块部分
  1437. $('details').each(function () {
  1438. let id = "_details_" + getRandomNumber(8);
  1439. addButtonPanel(this, id, "child_level");
  1440. addButtonWithHTML2MD(this, id, "child_level");
  1441. addButtonWithCopy(this, id, "child_level");
  1442. addButtonWithTranslation(this, id, "child_level");
  1443. });
  1444.  
  1445. // 添加到contest-statement部分
  1446. $('#contest-statement').each(function () {
  1447. let id = "_contest-statement_" + getRandomNumber(8);
  1448. addButtonPanel(this, id, "this_level");
  1449. addButtonWithHTML2MD(this, id, "this_level");
  1450. addButtonWithCopy(this, id, "this_level");
  1451. addButtonWithTranslation(this, id, "this_level");
  1452. });
  1453.  
  1454. // 添加到blog-post部分
  1455. $('.blog-post').each(function () {
  1456. let id = "_blog-post_" + getRandomNumber(8);
  1457. addButtonPanel(this, id, "this_level");
  1458. addButtonWithHTML2MD(this, id, "this_level");
  1459. addButtonWithCopy(this, id, "this_level");
  1460. addButtonWithTranslation(this, id, "this_level");
  1461. });
  1462. };
  1463.  
  1464. // 跳转洛谷
  1465. async function At2luogu() {
  1466. const getProblemId = () => {
  1467. const url = window.location.href;
  1468. const regex = /\/contests\/([A-Za-z\d]+)\/tasks\/([A-Za-z\d\_]+)/;
  1469. const matchResult = url.match(regex);
  1470. return matchResult && matchResult.length >= 3
  1471. ? `${matchResult[2]}`
  1472. : '';
  1473. };
  1474.  
  1475. const checkLinkExistence = (url) => {
  1476. return new Promise((resolve, reject) => {
  1477. GM.xmlHttpRequest({
  1478. method: "GET",
  1479. url,
  1480. headers: { "Range": "bytes=0-9999" }, // 获取前10KB数据
  1481. onload(response) {
  1482. if (response.responseText.match(/题目未找到/g)) {
  1483. resolve(false);
  1484. } else {
  1485. resolve(true);
  1486. }
  1487. },
  1488. onerror(error) {
  1489. reject(error);
  1490. }
  1491. });
  1492. });
  1493. };
  1494.  
  1495. const url = `https://www.luogu.com.cn/problem/AT_${getProblemId()}`;
  1496. const result = await checkLinkExistence(url);
  1497. if (getProblemId() && result) {
  1498. const problemLink = $("<a style='display: inline-block;vertical-align: middle;'>")
  1499. .attr("id", "problemLink")
  1500. .attr("href", url)
  1501. .attr("target", "_blank")
  1502. .html(`<button style="height: 25px;" class="html2mdButton"><img style="width:45px; margin-right:2px;" src="https://cdn.luogu.com.cn/fe/logo.png"></button>`);
  1503. problemLink.appendTo('.h2');
  1504. }
  1505. }
  1506.  
  1507. $(document).ready(function () {
  1508. var newElement = $("<div></div>")
  1509. .addClass("alert alert-info")
  1510. .html(`Atcoder Better! —— 正在等待页面资源加载……`)
  1511. .css({
  1512. margin: "1em",
  1513. "text-align": "center",
  1514. "font-weight": "600",
  1515. position: "relative",
  1516. });
  1517.  
  1518. var tip_SegmentedTranslation = $("<div></div>")
  1519. .addClass("alert alert-danger")
  1520. .html(`
  1521. Atcoder Better! —— 注意!分段翻译已开启,这会造成负面效果,
  1522. <p>除非你现在需要翻译超长篇的博客或者题目,否则请前往设置关闭分段翻译</p>
  1523. `)
  1524. .css({
  1525. margin: "1em",
  1526. "text-align": "center",
  1527. "font-weight": "600",
  1528. position: "relative",
  1529. });
  1530.  
  1531. function processPage() {
  1532. if (enableSegmentedTranslation)
  1533. $("#main-container").prepend(tip_SegmentedTranslation); //显示分段翻译警告
  1534.  
  1535. if (showLoading) {
  1536. newElement.html("Atcoder Better! —— 正在处理中……");
  1537. newElement.removeClass("alert-info").addClass("alert-success");
  1538. }
  1539.  
  1540. if (showJumpToLuogu) At2luogu();
  1541.  
  1542. addConversionButton();
  1543.  
  1544. if (showLoading) {
  1545. newElement.html("Atcoder Better! —— 加载已完成");
  1546. setTimeout(function () {
  1547. newElement.remove();
  1548. }, 3000);
  1549. }
  1550. }
  1551.  
  1552. if (showLoading) $("#main-container").prepend(newElement);
  1553.  
  1554. if (loaded) {
  1555. processPage();
  1556. } else {
  1557. // 页面完全加载完成后执行
  1558. window.onload = function () {
  1559. processPage();
  1560. };
  1561. }
  1562. });
  1563.  
  1564. // 字数超限确认
  1565. function showWordsExceededDialog(button) {
  1566. return new Promise(resolve => {
  1567. const styleElement = GM_addStyle(darkenPageStyle);
  1568. $(button).removeClass("translated");
  1569. $(button).text("字数超限");
  1570. $(button).css("cursor", "not-allowed");
  1571. $(button).prop("disabled", true);
  1572. let htmlString = `
  1573. <div class="wordsExceeded">
  1574. <h4>字数超限!</h4>
  1575. <p>注意,即将翻译的内容字数超过了4950个字符,您可能选择了错误的翻译按钮</p>
  1576. <div style="display:flex; padding:5px 0px; align-items: center;">
  1577. `+ helpCircleHTML + `
  1578. <p>
  1579. 由于实现方式,区域中会出现多个翻译按钮,请点击更小的子区域中的翻译按钮,
  1580. <br>或者在设置面板中开启 分段翻译 后重试。
  1581. </p>
  1582. </div>
  1583. <p>对于免费的接口,大量请求可能导致你的IP被暂时禁止访问,对于GPT,会消耗大量的token</p>
  1584. <p>您确定要继续翻译吗?</p>
  1585. <div style="display:flex; padding-top:10px">
  1586. <button id="continueButton">继续</button><button id="cancelButton">取消</button>
  1587. </div>
  1588. </div>
  1589. `;
  1590. $('body').before(htmlString);
  1591. $("#continueButton").click(function () {
  1592. $(styleElement).remove();
  1593. $('.wordsExceeded').remove();
  1594. resolve(true);
  1595. });
  1596. $("#cancelButton").click(function () {
  1597. $(styleElement).remove();
  1598. $('.wordsExceeded').remove();
  1599. resolve(false);
  1600. });
  1601. });
  1602. }
  1603.  
  1604. // 跳过折叠块确认
  1605. function skiFoldingBlocks() {
  1606. return new Promise(resolve => {
  1607. const styleElement = GM_addStyle(darkenPageStyle);
  1608. let htmlString = `
  1609. <div class="wordsExceeded">
  1610. <h4>是否跳过折叠块?</h4>
  1611. <p></p>
  1612. <div style="display:grid; padding:5px 0px; align-items: center;">
  1613. <p>
  1614. 即将翻译的区域中包含折叠块,可能不需要翻译,现在您需要选择是否跳过这些折叠块,
  1615. </p>
  1616. <p>
  1617. 如果其中有您需要翻译的折叠块,可以稍后再单独点击这些折叠块内的翻译按钮进行翻译
  1618. </p>
  1619. </div>
  1620. <p>要跳过折叠块吗?(建议选择跳过)</p>
  1621. <div style="display:flex; padding-top:10px">
  1622. <button id="cancelButton">否</button><button id="skipButton">跳过</button>
  1623. </div>
  1624. </div>
  1625. `;
  1626. $('body').before(htmlString);
  1627. $("#skipButton").click(function () {
  1628. $(styleElement).remove();
  1629. $('.wordsExceeded').remove();
  1630. resolve(true);
  1631. });
  1632. $("#cancelButton").click(function () {
  1633. $(styleElement).remove();
  1634. $('.wordsExceeded').remove();
  1635. resolve(false);
  1636. });
  1637. });
  1638. }
  1639.  
  1640. // 翻译框/翻译处理器
  1641. var translatedText = "";
  1642. async function translateProblemStatement(text, element_node, button) {
  1643. let status = 0;
  1644. let id = getRandomNumber(8);
  1645. let matches = [];
  1646. let replacements = {};
  1647. // 创建元素并放在element_node的后面
  1648. const translateDiv = document.createElement('div');
  1649. translateDiv.setAttribute('id', id);
  1650. translateDiv.classList.add('translate-problem-statement');
  1651. const spanElement = document.createElement('span');
  1652. translateDiv.appendChild(spanElement);
  1653. element_node.insertAdjacentElement('afterend', translateDiv);
  1654. // 替换latex公式
  1655. if (translation != "api2d" && translation != "openai") {
  1656. // 使用GPT翻译时不必替换latex公式
  1657. let i = 0;
  1658. // 块公式
  1659. matches = matches.concat(text.match(/\$\$([\s\S]*?)\$\$/g));
  1660. try {
  1661. for (i; i < matches.length; i++) {
  1662. let match = matches[i];
  1663. text = text.replace(match, `【${i + 1}】`);
  1664. replacements[`【${i + 1}】`] = match;
  1665. }
  1666. } catch (e) { }
  1667. // 行内公式
  1668. matches = matches.concat(text.match(/\$(.*?)\$/g));
  1669. try {
  1670. for (i; i < matches.length; i++) {
  1671. let match = matches[i];
  1672. text = text.replace(match, `【${i + 1}】`);
  1673. replacements[`【${i + 1}】`] = match;
  1674. }
  1675. } catch (e) { }
  1676. }
  1677. if (text.length > 4950) {
  1678. const shouldContinue = await showWordsExceededDialog(button);
  1679. if (!shouldContinue) {
  1680. status = 1;
  1681. return {
  1682. translateDiv: translateDiv,
  1683. status: status
  1684. };
  1685. }
  1686. }
  1687. // 翻译
  1688. if (translation == "deepl") {
  1689. translateDiv.textContent = "正在翻译中……请稍等";
  1690. translatedText = await translate_deepl(text);
  1691. } else if (translation == "youdao") {
  1692. translateDiv.textContent = "正在翻译中……请稍等";
  1693. translatedText = await translate_youdao_mobile(text);
  1694. } else if (translation == "google") {
  1695. translateDiv.textContent = "正在翻译中……请稍等";
  1696. translatedText = await translate_gg(text);
  1697. } else if (translation == "openai") {
  1698. translateDiv.textContent = "正在翻译中……\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待";
  1699. translatedText = await translate_openai(text);
  1700. } else if (translation == "api2d") {
  1701. translateDiv.textContent = "正在翻译中……\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待";
  1702. translatedText = await translate_api2d(text);
  1703. }
  1704. if (/^翻译出错/.test(translatedText)) status = 2;
  1705.  
  1706. // 还原latex公式
  1707. if (translation != "api2d" && translation != "openai") {
  1708. try {
  1709. for (let i = 0; i < matches.length; i++) {
  1710. let match = matches[i];
  1711. let replacement = replacements[`【${i + 1}】`];
  1712. let regex;
  1713. regex = new RegExp(`【${i + 1}】`, 'g');
  1714. translatedText = translatedText.replace(regex, replacement);
  1715. regex = new RegExp(`\\[${i + 1}\\]`, 'g');
  1716. translatedText = translatedText.replace(regex, replacement);
  1717. regex = new RegExp(`【${i + 1}[^】\\d]`, 'g');
  1718. translatedText = translatedText.replace(regex, replacement);
  1719. regex = new RegExp(`[^【\\d]${i + 1}】`, 'g');
  1720. translatedText = translatedText.replace(regex, " " + replacement);
  1721. }
  1722. } catch (e) { }
  1723. }
  1724.  
  1725. // 创建一个隐藏的元素来保存 translatedText 的值
  1726. var textElement = document.createElement("div");
  1727. textElement.style.display = "none";
  1728. textElement.textContent = translatedText;
  1729. translateDiv.parentNode.insertBefore(textElement, translateDiv);
  1730.  
  1731. // 翻译复制按钮
  1732. var copyButton = document.createElement("button");
  1733. copyButton.textContent = "Copy";
  1734. $(copyButton).addClass("html2mdButton html2md-cb");
  1735. $(copyButton).css({
  1736. "float": "right",
  1737. });
  1738. copyButton.addEventListener("click", function () {
  1739. var translatedText = textElement.textContent;
  1740. GM_setClipboard(translatedText);
  1741. $(this).addClass("copied");
  1742. $(this).text("Copied");
  1743. // 更新复制按钮文本
  1744. setTimeout(() => {
  1745. $(this).removeClass("copied");
  1746. $(this).text("Copy");
  1747. }, 2000);
  1748. });
  1749. translateDiv.parentNode.insertBefore(copyButton, translateDiv);
  1750.  
  1751. // 更新
  1752. translateDiv.innerHTML = translatedText;
  1753. // 渲染MarkDown
  1754. var md = window.markdownit();
  1755. var html = md.render(translateDiv.innerText);
  1756. translateDiv.innerHTML = html;
  1757. // 渲染Latex
  1758. if (typeof renderMathInElement === 'function') {
  1759. renderMathInElement(document.getElementById(id), {
  1760. delimiters: [{
  1761. left: "$$",
  1762. right: "$$",
  1763. display: true
  1764. }, {
  1765. left: "$",
  1766. right: "$",
  1767. display: false
  1768. }]
  1769. });
  1770. }
  1771. return {
  1772. translateDiv: translateDiv,
  1773. status: status,
  1774. copyDiv: textElement,
  1775. copyButton: copyButton
  1776. };
  1777.  
  1778. }
  1779.  
  1780. // ChatGPT
  1781. async function translate_openai(raw) {
  1782. var openai_key = GM_getValue("openai_key");
  1783. var openai_retext = "";
  1784. var data = {
  1785. model: "gpt-3.5-turbo",
  1786. messages: [{
  1787. role: "user",
  1788. content: "(请将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw + ")"
  1789. }],
  1790. temperature: 0.7
  1791. };
  1792. return new Promise(function (resolve, reject) {
  1793. GM_xmlhttpRequest({
  1794. method: 'POST',
  1795. 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
  1796.  
  1797. data: JSON.stringify(data),
  1798. headers: {
  1799. 'Content-Type': 'application/json',
  1800. 'Authorization': 'Bearer ' + GM_getValue("openai_key")
  1801. },
  1802. responseType: 'json',
  1803. onload: function (response) {
  1804. if (!response.response.choices || response.response.choices.length < 1 || !response.response.choices[0].message) {
  1805. resolve("翻译出错,请重试\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/471106/feedback 反馈\n\n报错信息:" + JSON.stringify(response.response, null, '\n'));
  1806. } else {
  1807. openai_retext = response.response.choices[0].message.content;
  1808. // openai_retext = openai_retext.replace(/^\s+/, '');
  1809. resolve(openai_retext);
  1810. }
  1811. },
  1812. onerror: function (response) {
  1813. console.error(response.statusText);
  1814. reject(response.statusText);
  1815. },
  1816. });
  1817.  
  1818. });
  1819. }
  1820.  
  1821. // api2d
  1822. async function translate_api2d(raw) {
  1823. var api2d_key = GM_getValue("api2d_key");
  1824. var api2d_retext = "";
  1825. var postData = JSON.stringify({
  1826. model: 'gpt-3.5-turbo',
  1827. messages: [{ role: 'user', content: '请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n' + raw }],
  1828. temperature: 0.7
  1829. });
  1830. const options = {
  1831. method: 'POST',
  1832. headers: {
  1833. 'Content-Type': 'application/json',
  1834. Authorization: 'Bearer ' + api2d_key,
  1835. ...(x_api2d_no_cache ? {} : { 'x-api2d-no-cache': 1 })
  1836. },
  1837. data: postData,
  1838. };
  1839.  
  1840. return new Promise(function (resolve, reject) {
  1841. GM_xmlhttpRequest({
  1842. method: options.method,
  1843. url: `https://openai.api2d.net/v1/chat/completions`,
  1844. headers: options.headers,
  1845. data: options.data,
  1846. responseType: 'json',
  1847. onload: function (response) {
  1848. if (!response.response.choices || response.response.choices.length < 1 || !response.response.choices[0].message) {
  1849. resolve("翻译出错,请重试\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈\n\n报错信息:" + JSON.stringify(response.response, null, '\n'));
  1850. } else {
  1851. api2d_retext = response.response.choices[0].message.content;
  1852. resolve(api2d_retext);
  1853. }
  1854. },
  1855. onerror: function (response) {
  1856. console.error(response.statusText);
  1857. reject(response.statusText);
  1858. },
  1859. });
  1860. });
  1861.  
  1862.  
  1863. }
  1864. //
  1865.  
  1866. //--谷歌翻译--start
  1867. async function translate_gg(raw) {
  1868. return new Promise((resolve, reject) => {
  1869. const url = 'https://translate.google.com/m';
  1870. const params = `tl=zh-CN&q=${encodeURIComponent(raw)}`;
  1871.  
  1872. GM_xmlhttpRequest({
  1873. method: 'GET',
  1874. url: `${url}?${params}`,
  1875. onload: function (response) {
  1876. const html = response.responseText;
  1877. const translatedText = $(html).find('.result-container').text();
  1878. resolve(translatedText);
  1879. },
  1880. onerror: function (error) {
  1881. console.error('Error:', error);
  1882. reject(error);
  1883. }
  1884. });
  1885. });
  1886. }
  1887. //--谷歌翻译--end
  1888.  
  1889. //--有道翻译m--start
  1890. async function translate_youdao_mobile(raw) {
  1891. const options = {
  1892. method: "POST",
  1893. url: 'http://m.youdao.com/translate',
  1894. data: "inputtext=" + encodeURIComponent(raw) + "&type=AUTO",
  1895. anonymous: true,
  1896. headers: {
  1897. "Content-Type": "application/x-www-form-urlencoded",
  1898. 'Host': 'm.youdao.com',
  1899. 'Origin': 'http://m.youdao.com',
  1900. 'Referer': 'http://m.youdao.com/translate',
  1901. }
  1902. }
  1903. return await BaseTranslate('有道翻译mobile', raw, options, res => /id="translateResult">\s*?<li>([\s\S]*?)<\/li>\s*?<\/ul/.exec(res)[1])
  1904. }
  1905. //--有道翻译m--end
  1906.  
  1907. //--Deepl翻译--start
  1908. function getTimeStamp(iCount) {
  1909. const ts = Date.now();
  1910. if (iCount !== 0) {
  1911. iCount = iCount + 1;
  1912. return ts - (ts % iCount) + iCount;
  1913. } else {
  1914. return ts;
  1915. }
  1916. }
  1917.  
  1918. async function translate_deepl(raw) {
  1919. const id = (Math.floor(Math.random() * 99999) + 100000) * 1000;
  1920. const data = {
  1921. jsonrpc: '2.0',
  1922. method: 'LMT_handle_texts',
  1923. id,
  1924. params: {
  1925. splitting: 'newlines',
  1926. lang: {
  1927. source_lang_user_selected: 'auto',
  1928. target_lang: 'ZH',
  1929. },
  1930. texts: [{
  1931. text: raw,
  1932. requestAlternatives: 3
  1933. }],
  1934. timestamp: getTimeStamp(raw.split('i').length - 1)
  1935. }
  1936. }
  1937. let postData = JSON.stringify(data);
  1938. if ((id + 5) % 29 === 0 || (id + 3) % 13 === 0) {
  1939. postData = postData.replace('"method":"', '"method" : "');
  1940. } else {
  1941. postData = postData.replace('"method":"', '"method": "');
  1942. }
  1943. const options = {
  1944. method: 'POST',
  1945. url: 'https://www2.deepl.com/jsonrpc',
  1946. data: postData,
  1947. headers: {
  1948. 'Content-Type': 'application/json',
  1949. 'Host': 'www2.deepl.com',
  1950. 'Origin': 'https://www.deepl.com',
  1951. 'Referer': 'https://www.deepl.com/',
  1952. },
  1953. anonymous: true,
  1954. nocache: true,
  1955. }
  1956. return await BaseTranslate('Deepl翻译', raw, options, res => JSON.parse(res).result.texts[0].text)
  1957. }
  1958.  
  1959. //--Deepl翻译--end
  1960.  
  1961. //--异步请求包装工具--start
  1962. async function PromiseRetryWrap(task, options, ...values) {
  1963. const { RetryTimes, ErrProcesser } = options || {};
  1964. let retryTimes = RetryTimes || 5;
  1965. const usedErrProcesser = ErrProcesser || (err => { throw err });
  1966. if (!task) return;
  1967. while (true) {
  1968. try {
  1969. return await task(...values);
  1970. } catch (err) {
  1971. if (!--retryTimes) {
  1972. console.log(err);
  1973. return usedErrProcesser(err);
  1974. }
  1975. }
  1976. }
  1977. }
  1978.  
  1979. async function BaseTranslate(name, raw, options, processer) {
  1980. let errtext;
  1981. const toDo = async () => {
  1982. var tmp;
  1983. try {
  1984. const data = await Request(options);
  1985. tmp = data.responseText;
  1986. const result = await processer(tmp);
  1987. if (result) sessionStorage.setItem(name + '-' + raw, result);
  1988. return result
  1989. } catch (err) {
  1990. errtext = tmp;
  1991. throw {
  1992. responseText: tmp,
  1993. err: err
  1994. }
  1995. }
  1996. }
  1997. return await PromiseRetryWrap(toDo, { RetryTimes: 3, ErrProcesser: () => "翻译出错,请重试或更换翻译接口\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈\n\n报错信息:" + errtext })
  1998. }
  1999.  
  2000.  
  2001. function Request(options) {
  2002. return new Promise((reslove, reject) => GM_xmlhttpRequest({ ...options, onload: reslove, onerror: reject }))
  2003. }
  2004.  
  2005. //--异步请求包装工具--end