Atcoder Better!

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

Fra 30.07.2023. Se den seneste versjonen.

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