Atcoder Better!

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

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

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