Atcoder Better!

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

Stan na 30-07-2023. Zobacz najnowsza wersja.

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