Atcoder Better!

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

As of 2023-07-18. See the latest version.

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