Greasy Fork is available in English.

Atcoder Better!

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

Verze ze dne 04. 08. 2023. Zobrazit nejnovější verzi.

  1. // ==UserScript==
  2. // @name Atcoder Better!
  3. // @namespace https://greatest.deepsurf.us/users/747162
  4. // @version 1.06
  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: 500px;
  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. <div class="help_tip">
  966. `+ helpCircleHTML + `
  967. <div class="tip_text">
  968. <p>开启后当鼠标悬浮在 MD视图/复制/翻译 按钮上时,会显示其目标区域的范围</p>
  969. </div>
  970. </div>
  971. <input type="checkbox" id="hoverTargetAreaDisplay" name="hoverTargetAreaDisplay">
  972. </div>
  973. <div class='AtBetter_setting_list'>
  974. <label for="enableSegmentedTranslation">分段翻译</label>
  975. <div class="help_tip">
  976. `+ helpCircleHTML + `
  977. <div class="tip_text">
  978. <p>分段翻译会对区域内的每一个&#60;&#112;&#47;&#62;和&#60;&#105;&#47;&#62;标签依次进行翻译,</p>
  979. <p>这通常在翻译<strong>长篇博客</strong>或者<strong>超长的题目</strong>时很有用。</p>
  980. <p><u>注意:开启分段翻译会产生如下问题:</u></p>
  981. <p>- 使得翻译接口无法知晓整个文本的上下文信息,会降低翻译质量。</p>
  982. <p>- 会有<strong>部分内容不会被翻译</strong>,因为它们不是&#60;&#112;&#47;&#62;或&#60;&#105;&#47;&#62;标签</p>
  983. </div>
  984. </div>
  985. <input type="checkbox" id="enableSegmentedTranslation" name="enableSegmentedTranslation">
  986. </div>
  987. <div class='AtBetter_setting_list'>
  988. <label for="showJumpToLuogu">显示跳转到洛谷</label>
  989. <div class="help_tip">
  990. `+ helpCircleHTML + `
  991. <div class="tip_text">
  992. <p>洛谷OJ上收录了Atcoder的部分题目,一些题目有翻译和题解</p>
  993. <p>开启显示后,如果当前题目被收录,则会在题目的右上角显示洛谷标志,</p>
  994. <p>点击即可一键跳转到该题洛谷的对应页面。</strong></p>
  995. </div>
  996. </div>
  997. <input type="checkbox" id="showJumpToLuogu" name="showJumpToLuogu">
  998. </div>
  999. <div class='AtBetter_setting_list'>
  1000. <label for="loaded"><span style="font-size: 14px;">兼容选项-不等待页面资源加载</span></label>
  1001. <div class="help_tip">
  1002. `+ helpCircleHTML + `
  1003. <div class="tip_text">
  1004. <p>为了防止在页面资源未加载完成前(主要是各种js)执行脚本产生意外的错误,脚本默认会等待 window.onload 事件</p>
  1005. <p>如果您的页面上方的加载信息始终停留在:“等待页面资源加载”,</p>
  1006. <p><u>您首先应该确认是否是网络问题,</u></p>
  1007. <p>如果页面实际已经加载完成,那这可能是由于 window.onload 事件在您的浏览器中触发过早(早于document.ready),</p>
  1008. <p>您可以尝试开启该选项来不再等待 window.onload 事件</p>
  1009. <p><u>注意:如果没有上述问题,请不要开启该选项</u></p>
  1010. </div>
  1011. </div>
  1012. <input type="checkbox" id="loaded" name="loaded">
  1013. </div>
  1014. <h4>翻译设置</h4>
  1015. <hr>
  1016. <label>
  1017. <input type='radio' name='translation' value='deepl'>
  1018. <span class='AtBetter_setting_menu_label_text'>deepl翻译</span>
  1019. </label>
  1020. <label>
  1021. <input type='radio' name='translation' value='youdao'>
  1022. <span class='AtBetter_setting_menu_label_text'>有道翻译</span>
  1023. </label>
  1024. <label>
  1025. <input type='radio' name='translation' value='google'>
  1026. <span class='AtBetter_setting_menu_label_text'>Google翻译</span>
  1027. </label>
  1028. <label>
  1029. <input type='radio' name='translation' value='openai'>
  1030. <span class='AtBetter_setting_menu_label_text'>使用ChatGPT翻译(API)
  1031. <div class="help_tip">
  1032. `+ helpCircleHTML + `
  1033. <div class="tip_text">
  1034. <p><b>请确保你能够正常访问OpenAIapi</b></p>
  1035. <p>Atcoder Better!使用 gpt-3.5-turbo 模型进行翻译,脚本的所有请求均在本地完成</p>
  1036. <p>你需要输入自己的OpenAI KEY,<a target="_blank" href="https://platform.openai.com/account/usage">官网</a></p>
  1037. </div>
  1038. </div>
  1039. </span>
  1040. </label>
  1041. <label>
  1042. <input type='radio' name='translation' value='api2d'>
  1043. <span class='AtBetter_setting_menu_label_text'>使用api2d翻译(API)
  1044. <div class="help_tip">
  1045. `+ helpCircleHTML + `
  1046. <div class="tip_text">
  1047. <p>api2d是国内的一家提供代理直连访问OpenAIapi的服务商,相当于OpenAIapi的套壳</p>
  1048. <p>Atcoder Better!使用 gpt-3.5-turbo 模型进行翻译,脚本的所有请求均在本地完成</p>
  1049. <p>你需要输入自己的api2d KEY,<a target="_blank" href="https://api2d.com/profile">官网</a></p>
  1050. </div>
  1051. </div>
  1052. </span>
  1053. </label>
  1054. <div class='AtBetter_setting_menu_input' id='openai' style='display: none;'>
  1055. <label for='openai_key'>KEY:</label><input type='text' id='openai_key'>
  1056. <div class='AtBetter_setting_list'>
  1057. <label for="showOpneAiAdvanced">使用代理API</label>
  1058. <div class="help_tip">
  1059. `+ helpCircleHTML + `
  1060. <div class="tip_text">
  1061. <p>使用你指定的API来代理访问 gpt-3.5-turbo 模型进行翻译,脚本的所有请求均在本地完成</p>
  1062. <p>如果你使用的是OpenAI的官方KEY,建议你自建代理,而不是使用他人公开的代理,那是危险的</p>
  1063. <p><strong>由于你指定了自定义的APITampermonkey会对你的跨域请求进行警告,请自行授权</strong></p>
  1064. </div>
  1065. </div>
  1066. <input type="checkbox" id="showOpneAiAdvanced" name="showOpneAiAdvanced">
  1067. </div>
  1068. <div id="is_showOpneAiAdvanced">
  1069. <label for='openai_proxy'>Proxy API:</label><input type='text' id='openai_proxy'>
  1070. </div>
  1071. </div>
  1072. <div class='AtBetter_setting_menu_input' id='api2d' style='display: none;'>
  1073. <label for='api2d_key'>KEY:</label><input type='text' id='api2d_key'>
  1074. <div class='AtBetter_setting_list'>
  1075. <label for="x_api2d_no_cache">使用缓存</label>
  1076. <div class="help_tip">
  1077. `+ helpCircleHTML + `
  1078. <div class="tip_text">
  1079. <p>API2D 的服务器会对请求结果做缓存,如果请求体的hash值相同,会直接返回缓存的结果。缓存命中之后,本次请求不会扣除任何点数。</p>
  1080. <p>缓存会保存 24 小时,如果不想使用缓存,你可以关闭“使用缓存”来跳过缓存,强制 API2D 服务器发送新请求。<a target="_blank" href="https://api2d.com/wiki/doc">详请阅读官方文档</a></p>
  1081. </div>
  1082. </div>
  1083. <input type="checkbox" id="x_api2d_no_cache" name="x_api2d_no_cache">
  1084. </div>
  1085. </div>
  1086. <br>
  1087. <button id='save'>保存</button>
  1088. </div>
  1089. `);
  1090. $("#bottomZh_CN").prop("checked", GM_getValue("bottomZh_CN") === true);
  1091. $("#showLoading").prop("checked", GM_getValue("showLoading") === true);
  1092. $("#enableSegmentedTranslation").prop("checked", GM_getValue("enableSegmentedTranslation") === true);
  1093. $("#showJumpToLuogu").prop("checked", GM_getValue("showJumpToLuogu") === true);
  1094. $("#loaded").prop("checked", GM_getValue("loaded") === true);
  1095. $("#x_api2d_no_cache").prop("checked", GM_getValue("x_api2d_no_cache") === true);
  1096. $("#showOpneAiAdvanced").prop("checked", GM_getValue("showOpneAiAdvanced") === true);
  1097. $("#hoverTargetAreaDisplay").prop("checked", GM_getValue("hoverTargetAreaDisplay") === true);
  1098. $("input[name='translation'][value='" + translation + "']").prop("checked", true);
  1099. $("input[name='translation']").css("color", "gray");
  1100. if (translation == "openai") {
  1101. $("#openai").show();
  1102. $("#openai_key").val(GM_getValue("openai_key"));
  1103. $("#openai_proxy").val(GM_getValue("openai_proxy"));
  1104. $("#openai_key").css("color", "gray");
  1105. } else if (translation == "api2d") {
  1106. $("#api2d").show();
  1107. $("#api2d_key").val(GM_getValue("api2d_key"));
  1108. $("#api2d_key").css("color", "gray");
  1109. }
  1110. // 当单选框被选中时,显示对应的输入框,同时隐藏其他输入框
  1111. $("input[name='translation']").change(function () {
  1112. var selected = $(this).val(); // 获取当前选中的值
  1113. if (selected === "openai") {
  1114. $("#openai").show();
  1115. $("#openai_key").val(GM_getValue("openai_key"));
  1116. $("#showOpneAiAdvanced").prop("checked", showOpneAiAdvanced);
  1117. if (showOpneAiAdvanced) {
  1118. $("#is_showOpneAiAdvanced").show();
  1119. $("#openai_proxy").val(GM_getValue("openai_proxy"));
  1120. }
  1121. else $("#is_showOpneAiAdvanced").hide();
  1122. $("#api2d").hide();
  1123. } else if (selected === "api2d") {
  1124. $("#api2d").show();
  1125. $("#api2d_key").val(GM_getValue("api2d_key"));
  1126. $("#x_api2d_no_cache").prop("checked", GM_getValue("x_api2d_no_cache"));
  1127. $("#openai").hide();
  1128. } else {
  1129. $("#openai, #api2d").hide();
  1130. }
  1131. });
  1132.  
  1133. // ChatGPT高级选项
  1134. $("input[name='showOpneAiAdvanced']").change(function () {
  1135. var isChecked = $(this).is(":checked");
  1136. if (isChecked) {
  1137. $("#is_showOpneAiAdvanced").show();
  1138. } else {
  1139. $("#is_showOpneAiAdvanced").hide();
  1140. }
  1141. });
  1142.  
  1143. const $settingMenu = $("#AtBetter_setting_menu");
  1144.  
  1145. $("#save").click(function () {
  1146. GM_setValue("bottomZh_CN", $("#bottomZh_CN").prop("checked"));
  1147. GM_setValue("showLoading", $("#showLoading").prop("checked"));
  1148. GM_setValue("loaded", $("#loaded").prop("checked"));
  1149. GM_setValue("enableSegmentedTranslation", $("#enableSegmentedTranslation").prop("checked"));
  1150. GM_setValue("showJumpToLuogu", $("#showJumpToLuogu").prop("checked"));
  1151. GM_setValue("showOpneAiAdvanced", $("#showOpneAiAdvanced").prop("checked"));
  1152. GM_setValue("hoverTargetAreaDisplay", $("#hoverTargetAreaDisplay").prop("checked"));
  1153. var translation = $("input[name='translation']:checked").val();
  1154. var openai_key = $("#openai_key").val();
  1155. var openai_proxy = $("#openai_proxy").val();
  1156. var api2d_key = $("#api2d_key").val();
  1157. GM_setValue("translation", translation);
  1158. if (translation == "openai") {
  1159. GM_setValue("openai_key", openai_key);
  1160. GM_setValue("openai_proxy", openai_proxy);
  1161. } else if (translation == "api2d") {
  1162. GM_setValue("api2d_key", api2d_key);
  1163. GM_setValue("x_api2d_no_cache", $("#x_api2d_no_cache").prop("checked"));
  1164. }
  1165. $settingMenu.remove();
  1166. $(styleElement).remove();
  1167. location.reload();
  1168. });
  1169.  
  1170. // 关闭
  1171. $settingMenu.on("click", ".btn-close", () => {
  1172. $settingMenu.remove();
  1173. $settingBtns.prop("disabled", false).removeClass("open");
  1174. $(styleElement).remove();
  1175. });
  1176. });
  1177. });
  1178.  
  1179. // html2md转换/处理规则
  1180. var turndownService = new TurndownService({ bulletListMarker: '-', escape: (text) => text });
  1181. var turndown = turndownService.turndown;
  1182.  
  1183. // 保留原始
  1184. turndownService.keep(['del']);
  1185.  
  1186. turndownService.addRule('removeByClass', {
  1187. filter: function (node) {
  1188. return node.classList.contains('html2md-panel') ||
  1189. node.classList.contains('div-btn-copy') ||
  1190. node.classList.contains('btn-copy') ||
  1191. node.classList.contains('overlay')
  1192. },
  1193. replacement: function () {
  1194. return '';
  1195. }
  1196. });
  1197.  
  1198. // inline math
  1199. turndownService.addRule('inline-math', {
  1200. filter: function (node, options) {
  1201. return node.tagName.toLowerCase() == "span" && node.className == "katex";
  1202. },
  1203. replacement: function (content, node) {
  1204. var latex = $(node).find('annotation').text();
  1205. latex = latex.replace(/</g, "&lt;").replace(/>/g, "&gt;");
  1206. return "$" + latex + "$";
  1207. }
  1208. });
  1209.  
  1210. // block math
  1211. turndownService.addRule('block-math', {
  1212. filter: function (node, options) {
  1213. return node.tagName.toLowerCase() == "span" && node.className == "katex-display";
  1214. },
  1215. replacement: function (content, node) {
  1216. var latex = $(node).find('annotation').text();
  1217. latex = latex.replace(/</g, "&lt;").replace(/>/g, "&gt;");
  1218. return "\n$$\n" + latex + "\n$$\n";
  1219. }
  1220. });
  1221.  
  1222. // pre
  1223. turndownService.addRule('pre', {
  1224. filter: function (node, options) {
  1225. return node.tagName.toLowerCase() == "pre";
  1226. },
  1227. replacement: function (content, node) {
  1228. return "```\n" + content + "```\n";
  1229. }
  1230. });
  1231.  
  1232. // bordertable
  1233. turndownService.addRule('bordertable', {
  1234. filter: 'table',
  1235. replacement: function (content, node) {
  1236. if (node.classList.contains('table')) {
  1237. var output = [],
  1238. thead = '',
  1239. trs = node.querySelectorAll('tr');
  1240. if (trs.length > 0) {
  1241. var ths = trs[0].querySelectorAll('th');
  1242. if (ths.length > 0) {
  1243. thead = '| ' + Array.from(ths).map(th => turndownService.turndown(th.innerHTML.trim())).join(' | ') + ' |\n'
  1244. + '| ' + Array.from(ths).map(() => ' --- ').join('|') + ' |\n';
  1245. }
  1246. }
  1247. var rows = node.querySelectorAll('tr');
  1248. Array.from(rows).forEach(function (row, i) {
  1249. if (i > 0) {
  1250. var cells = row.querySelectorAll('td,th');
  1251. var trow = '| ' + Array.from(cells).map(cell => turndownService.turndown(cell.innerHTML.trim())).join(' | ') + ' |';
  1252. output.push(trow);
  1253. }
  1254. });
  1255. return thead + output.join('\n');
  1256. } else {
  1257. return content;
  1258. }
  1259. }
  1260. });
  1261.  
  1262.  
  1263. // 随机数生成
  1264. function getRandomNumber(numDigits) {
  1265. let min = Math.pow(10, numDigits - 1);
  1266. let max = Math.pow(10, numDigits) - 1;
  1267. return Math.floor(Math.random() * (max - min + 1)) + min;
  1268. }
  1269.  
  1270. // 题目markdown转换/翻译面板
  1271. function addButtonPanel(parent, suffix, type, is_simple = false) {
  1272. let htmlString = `<div class='html2md-panel'>
  1273. <button class='html2mdButton html2md-view${suffix}'>MarkDown视图</button>
  1274. <button class='html2mdButton html2md-cb${suffix}'>Copy</button>
  1275. <button class='html2mdButton translateButton${suffix}'>翻译</button>
  1276. </div>`;
  1277. if (type === "this_level") {
  1278. $(parent).before(htmlString);
  1279. } else if (type === "child_level") {
  1280. $(parent).prepend(htmlString);
  1281. }
  1282. if (is_simple) {
  1283. $('.html2md-panel').find('.html2mdButton.html2md-view' + suffix + ', .html2mdButton.html2md-cb' + suffix).remove();
  1284. }
  1285. }
  1286.  
  1287. function addButtonWithHTML2MD(parent, suffix, type) {
  1288. $(document).on("click", ".html2md-view" + suffix, function () {
  1289. var target, removedChildren = $();
  1290. if (type === "this_level") {
  1291. target = $(".html2md-view" + suffix).parent().next().get(0);
  1292. } else if (type === "child_level") {
  1293. target = $(".html2md-view" + suffix).parent().parent().get(0);
  1294. removedChildren = $(".html2md-view" + suffix).parent().parent().children(':first').detach();
  1295. }
  1296. if (target.viewmd) {
  1297. target.viewmd = false;
  1298. $(this).text("MarkDown视图");
  1299. $(this).removeClass("mdViewed");
  1300. $(target).html(target.original_html);
  1301. } else {
  1302. target.viewmd = true;
  1303. if (!target.original_html) {
  1304. target.original_html = $(target).html();
  1305. }
  1306. if (!target.markdown) {
  1307. target.markdown = turndownService.turndown($(target).html());
  1308. }
  1309. $(this).text("原始内容");
  1310. $(this).addClass("mdViewed");
  1311. $(target).html(`<span class="mdViewContent" oninput="$(this).parent().get(0).markdown=this.value;" style="width:auto; height:auto;">${target.markdown}</span>`);
  1312. }
  1313. // 恢复删除的元素
  1314. if (removedChildren) $(target).prepend(removedChildren);
  1315. });
  1316.  
  1317. if (hoverTargetAreaDisplay) {
  1318. $(document).on("mouseover", ".html2md-view" + suffix, function () {
  1319. var target;
  1320.  
  1321. if (type === "this_level") {
  1322. target = $(".html2md-view" + suffix).parent().next().get(0);
  1323. } else if (type === "child_level") {
  1324. target = $(".html2md-view" + suffix).parent().parent().get(0);
  1325. }
  1326.  
  1327. $(target).append('<div class="overlay">目标转换区域</div>');
  1328. $(target).css({
  1329. "position": "relative",
  1330. "display": "block"
  1331. });
  1332. $(".html2md-view" + suffix).parent().css({
  1333. "position": "relative",
  1334. "z-index": "99999"
  1335. })
  1336. });
  1337.  
  1338. $(document).on("mouseout", ".html2md-view" + suffix, function () {
  1339. var target;
  1340.  
  1341. if (type === "this_level") {
  1342. target = $(".html2md-view" + suffix).parent().next().get(0);
  1343. } else if (type === "child_level") {
  1344. target = $(".html2md-view" + suffix).parent().parent().get(0);
  1345. }
  1346.  
  1347. $(target).find('.overlay').remove();
  1348. $(target).css({
  1349. "position": "",
  1350. "display": ""
  1351. });
  1352. $(".html2md-view" + suffix).parent().css({
  1353. "position": "static"
  1354. })
  1355. });
  1356. }
  1357. }
  1358.  
  1359. function addButtonWithCopy(parent, suffix, type) {
  1360. $(document).on("click", ".html2md-cb" + suffix, function () {
  1361. var target, removedChildren;
  1362. if (type === "this_level") {
  1363. target = $(".translateButton" + suffix).parent().next().eq(0).clone();
  1364. } else if (type === "child_level") {
  1365. target = $(".translateButton" + suffix).parent().parent().eq(0).clone();
  1366. $(target).children(':first').remove();
  1367. }
  1368. if ($(target).find('.mdViewContent').length <= 0) {
  1369. text = turndownService.turndown($(target).html());
  1370. } else {
  1371. text = $(target).find('.mdViewContent').text();
  1372. }
  1373. GM_setClipboard(text);
  1374. $(this).addClass("copied");
  1375. $(this).text("Copied");
  1376. // 更新复制按钮文本
  1377. setTimeout(() => {
  1378. $(this).removeClass("copied");
  1379. $(this).text("Copy");
  1380. }, 2000);
  1381. $(target).remove();
  1382. });
  1383.  
  1384. if (hoverTargetAreaDisplay) {
  1385. $(document).on("mouseover", ".html2md-cb" + suffix, function () {
  1386. var target;
  1387.  
  1388. if (type === "this_level") {
  1389. target = $(".html2md-cb" + suffix).parent().next().get(0);
  1390. } else if (type === "child_level") {
  1391. target = $(".html2md-cb" + suffix).parent().parent().get(0);
  1392. }
  1393.  
  1394. $(target).append('<div class="overlay">目标复制区域</div>');
  1395. $(target).css({
  1396. "position": "relative",
  1397. "display": "block"
  1398. });
  1399. $(".html2md-cb" + suffix).parent().css({
  1400. "position": "relative",
  1401. "z-index": "99999"
  1402. })
  1403. });
  1404.  
  1405. $(document).on("mouseout", ".html2md-cb" + suffix, function () {
  1406. var target;
  1407.  
  1408. if (type === "this_level") {
  1409. target = $(".html2md-cb" + suffix).parent().next().get(0);
  1410. } else if (type === "child_level") {
  1411. target = $(".html2md-cb" + suffix).parent().parent().get(0);
  1412. }
  1413.  
  1414. $(target).find('.overlay').remove();
  1415. $(target).css({
  1416. "position": "",
  1417. "display": ""
  1418. });
  1419. $(".html2md-cb" + suffix).parent().css({
  1420. "position": "static"
  1421. })
  1422. });
  1423. }
  1424. }
  1425.  
  1426. async function addButtonWithTranslation(parent, suffix, type) {
  1427. var result;
  1428. $(document).on('click', '.translateButton' + suffix, async function () {
  1429. $(this).removeClass("translated");
  1430. $(this).text("翻译中");
  1431. $(this).css("cursor", "not-allowed");
  1432. var target, element_node, block, errerNum = 0, is_x_api2d_no_cache = false;
  1433. if (type === "this_level") block = $(".translateButton" + suffix).parent().next();
  1434. else if (type === "child_level") block = $(".translateButton" + suffix).parent().parent();
  1435.  
  1436. // 重新翻译
  1437. if (result) {
  1438. if (result.translateDiv) {
  1439. $(result.translateDiv).remove();
  1440. }
  1441. if (result.copyDiv) {
  1442. $(result.copyDiv).remove();
  1443. }
  1444. if (result.copyButton) {
  1445. $(result.copyButton).remove();
  1446. }
  1447. // 重新翻译时暂时关闭 x_api2d_no_cache
  1448. if (x_api2d_no_cache) {
  1449. x_api2d_no_cache = false;
  1450. is_x_api2d_no_cache = true;
  1451. }
  1452. // 移除旧的事件
  1453. $(document).off("mouseover", ".translateButton" + suffix);
  1454. $(document).off("mouseout", ".translateButton" + suffix);
  1455. // 重新绑定悬停事件
  1456. if (hoverTargetAreaDisplay) bindHoverEvents(suffix, type);
  1457. }
  1458.  
  1459. // 分段翻译
  1460. if (enableSegmentedTranslation) {
  1461. var pElements = block.find("p, li");
  1462. for (let i = 0; i < pElements.length; i++) {
  1463. target = $(pElements[i]).eq(0).clone();
  1464. if (type === "child_level") $(target).children(':first').remove();
  1465. element_node = pElements[i];
  1466. if (type === "child_level") {
  1467. $(pElements[i]).append("<div></div>");
  1468. element_node = $(pElements[i]).find("div:last-child").get(0);
  1469. }
  1470. result = await blockProcessing(target, element_node, $(".translateButton" + suffix));
  1471. if (result.status) errerNum += 1;
  1472. $(target).remove();
  1473. if (translation == "deepl") await new Promise(resolve => setTimeout(resolve, 2000));
  1474. }
  1475. } else {
  1476. target = block.eq(0).clone();
  1477. if (type === "child_level") $(target).children(':first').remove();
  1478. element_node = $(block).get(0);
  1479. if (type === "child_level") {
  1480. $(parent).append("<div></div>");
  1481. element_node = $(parent).find("div:last-child").get(0);
  1482. }
  1483. //是否跳过折叠块
  1484. if ($(target).find('.spoiler').length > 0) {
  1485. const shouldSkip = await skiFoldingBlocks();
  1486. if (shouldSkip) {
  1487. $(target).find('.spoiler').remove();
  1488. } else {
  1489. $(target).find('.html2md-panel').remove();
  1490. }
  1491. }
  1492. result = await blockProcessing(target, element_node, $(".translateButton" + suffix));
  1493. if (result.status) errerNum += 1;
  1494. $(target).remove();
  1495. }
  1496. if (!errerNum) {
  1497. $(this).addClass("translated")
  1498. .text("已翻译")
  1499. .css("cursor", "pointer")
  1500. .removeClass("error");
  1501. }
  1502.  
  1503. // 恢复x_api2d_no_cache设置
  1504. if (is_x_api2d_no_cache) x_api2d_no_cache = true;
  1505.  
  1506. // 重新翻译
  1507. let currentText;
  1508. $(document).on("mouseover", ".translateButton" + suffix, function () {
  1509. currentText = $(this).text();
  1510. $(this).text("重新翻译");
  1511. });
  1512.  
  1513. $(document).on("mouseout", ".translateButton" + suffix, function () {
  1514. $(this).text(currentText);
  1515. });
  1516. });
  1517.  
  1518. // 目标区域指示
  1519. function bindHoverEvents(suffix, type) {
  1520. $(document).on("mouseover", ".translateButton" + suffix, function () {
  1521. var target;
  1522.  
  1523. if (type === "this_level") {
  1524. target = $(".translateButton" + suffix).parent().next().get(0);
  1525. } else if (type === "child_level") {
  1526. target = $(".translateButton" + suffix).parent().parent().get(0);
  1527. }
  1528.  
  1529. $(target).append('<div class="overlay">目标翻译区域</div>');
  1530. $(target).css({
  1531. "position": "relative",
  1532. "display": "block"
  1533. });
  1534. $(".translateButton" + suffix).parent().css({
  1535. "position": "relative",
  1536. "z-index": "99999"
  1537. });
  1538. });
  1539.  
  1540. $(document).on("mouseout", ".translateButton" + suffix, function () {
  1541. var target;
  1542.  
  1543. if (type === "this_level") {
  1544. target = $(".translateButton" + suffix).parent().next().get(0);
  1545. } else if (type === "child_level") {
  1546. target = $(".translateButton" + suffix).parent().parent().get(0);
  1547. }
  1548.  
  1549. $(target).find('.overlay').remove();
  1550. $(target).css({
  1551. "position": "",
  1552. "display": ""
  1553. });
  1554. $(".translateButton" + suffix).parent().css({
  1555. "position": "static"
  1556. });
  1557. });
  1558. }
  1559.  
  1560. if (hoverTargetAreaDisplay) bindHoverEvents(suffix, type);
  1561. }
  1562.  
  1563. // 块处理
  1564. async function blockProcessing(target, element_node, button) {
  1565. if (!target.markdown) {
  1566. target.markdown = turndownService.turndown($(target).html());
  1567. }
  1568. const textarea = document.createElement('textarea');
  1569. textarea.value = target.markdown;
  1570. var result = await translateProblemStatement(textarea.value, element_node, $(button));
  1571. //
  1572. if (result.status == 1) {
  1573. $(button).addClass("error")
  1574. .text("翻译中止")
  1575. .css("cursor", "pointer")
  1576. .prop("disabled", false);
  1577. $(result.translateDiv).remove();
  1578. $(target).remove();
  1579. } else if (result.status == 2) {
  1580. result.translateDiv.classList.add("error_translate");
  1581. $(button).addClass("error")
  1582. .text("翻译出错");
  1583. $(target).remove();
  1584. }
  1585. return result;
  1586. }
  1587.  
  1588. function addConversionButton() {
  1589. // 基本添加
  1590. $('section').each(function () {
  1591. let id = "_" + getRandomNumber(8);
  1592. addButtonPanel(this, id, "this_level");
  1593. addButtonWithHTML2MD(this, id, "this_level");
  1594. addButtonWithCopy(this, id, "this_level");
  1595. addButtonWithTranslation(this, id, "this_level");
  1596. });
  1597.  
  1598. // 添加按钮到题解部分
  1599. if (window.location.href.includes("editorial")) {
  1600. let contestNavTabs = $("#contest-nav-tabs");
  1601. let nextElement = contestNavTabs.next();
  1602. let id = "_editorial_" + getRandomNumber(8);
  1603. addButtonPanel(nextElement, id, "child_level");
  1604. addButtonWithHTML2MD(nextElement, id, "child_level");
  1605. addButtonWithCopy(nextElement, id, "child_level");
  1606. addButtonWithTranslation(nextElement, id, "child_level");
  1607. }
  1608. if (window.location.href.includes("editorial")) {
  1609. let contestNavTabs = $("#contest-nav-tabs");
  1610. let nextElement = contestNavTabs.next().children().eq(-2);
  1611. let id = "_editorial_" + getRandomNumber(8);
  1612. addButtonPanel(nextElement, id, "child_level");
  1613. addButtonWithHTML2MD(nextElement, id, "child_level");
  1614. addButtonWithCopy(nextElement, id, "child_level");
  1615. addButtonWithTranslation(nextElement, id, "child_level");
  1616. }
  1617.  
  1618. // 添加按钮到折叠块部分
  1619. $('details').each(function () {
  1620. let id = "_details_" + getRandomNumber(8);
  1621. addButtonPanel(this, id, "child_level");
  1622. addButtonWithHTML2MD(this, id, "child_level");
  1623. addButtonWithCopy(this, id, "child_level");
  1624. addButtonWithTranslation(this, id, "child_level");
  1625. });
  1626.  
  1627. // 添加到contest-statement部分
  1628. $('#contest-statement').each(function () {
  1629. let id = "_contest-statement_" + getRandomNumber(8);
  1630. addButtonPanel(this, id, "this_level");
  1631. addButtonWithHTML2MD(this, id, "this_level");
  1632. addButtonWithCopy(this, id, "this_level");
  1633. addButtonWithTranslation(this, id, "this_level");
  1634. });
  1635.  
  1636. // 添加到blog-post部分
  1637. $('.blog-post').each(function () {
  1638. let id = "_blog-post_" + getRandomNumber(8);
  1639. addButtonPanel(this, id, "this_level");
  1640. addButtonWithHTML2MD(this, id, "this_level");
  1641. addButtonWithCopy(this, id, "this_level");
  1642. addButtonWithTranslation(this, id, "this_level");
  1643. });
  1644. };
  1645.  
  1646. // 跳转洛谷
  1647. async function At2luogu() {
  1648. const getProblemId = () => {
  1649. const url = window.location.href;
  1650. const regex = /\/contests\/([A-Za-z\d]+)\/tasks\/([A-Za-z\d\_]+)/;
  1651. const matchResult = url.match(regex);
  1652. return matchResult && matchResult.length >= 3
  1653. ? `${matchResult[2]}`
  1654. : '';
  1655. };
  1656.  
  1657. const checkLinkExistence = (url) => {
  1658. return new Promise((resolve, reject) => {
  1659. GM.xmlHttpRequest({
  1660. method: "GET",
  1661. url,
  1662. headers: { "Range": "bytes=0-9999" }, // 获取前10KB数据
  1663. onload(response) {
  1664. if (response.responseText.match(/题目未找到/g)) {
  1665. resolve(false);
  1666. } else {
  1667. resolve(true);
  1668. }
  1669. },
  1670. onerror(error) {
  1671. reject(error);
  1672. }
  1673. });
  1674. });
  1675. };
  1676.  
  1677. const url = `https://www.luogu.com.cn/problem/AT_${getProblemId()}`;
  1678. const result = await checkLinkExistence(url);
  1679. if (getProblemId() && result) {
  1680. const problemLink = $("<a style='display: inline-block;vertical-align: middle;'>")
  1681. .attr("id", "problemLink")
  1682. .attr("href", url)
  1683. .attr("target", "_blank")
  1684. .html(`<button style="height: 25px;" class="html2mdButton"><img style="width:45px; margin-right:2px;" src="https://cdn.luogu.com.cn/fe/logo.png"></button>`);
  1685. problemLink.appendTo('.h2');
  1686. }
  1687. }
  1688.  
  1689. $(document).ready(function () {
  1690. var newElement = $("<div></div>")
  1691. .addClass("alert alert-info")
  1692. .html(`Atcoder Better! —— 正在等待页面资源加载……`)
  1693. .css({
  1694. margin: "1em",
  1695. "text-align": "center",
  1696. "font-weight": "600",
  1697. position: "relative",
  1698. });
  1699.  
  1700. var tip_SegmentedTranslation = $("<div></div>")
  1701. .addClass("alert alert-danger")
  1702. .html(`
  1703. Atcoder Better! —— 注意!分段翻译已开启,这会造成负面效果,
  1704. <p>除非你现在需要翻译超长篇的博客或者题目,否则请前往设置关闭分段翻译</p>
  1705. `)
  1706. .css({
  1707. margin: "1em",
  1708. "text-align": "center",
  1709. "font-weight": "600",
  1710. position: "relative",
  1711. });
  1712.  
  1713. function processPage() {
  1714. if (enableSegmentedTranslation)
  1715. $("#main-container").prepend(tip_SegmentedTranslation); //显示分段翻译警告
  1716.  
  1717. if (showLoading) {
  1718. newElement.html("Atcoder Better! —— 正在处理中……");
  1719. newElement.removeClass("alert-info").addClass("alert-success");
  1720. }
  1721.  
  1722. if (showJumpToLuogu) At2luogu();
  1723.  
  1724. addConversionButton();
  1725.  
  1726. if (showLoading) {
  1727. newElement.html("Atcoder Better! —— 加载已完成");
  1728. setTimeout(function () {
  1729. newElement.remove();
  1730. }, 3000);
  1731. }
  1732. }
  1733.  
  1734. if (showLoading) $("#main-container").prepend(newElement);
  1735.  
  1736. if (loaded) {
  1737. processPage();
  1738. } else {
  1739. // 页面完全加载完成后执行
  1740. window.onload = function () {
  1741. processPage();
  1742. };
  1743. }
  1744. });
  1745.  
  1746. // 字数超限确认
  1747. function showWordsExceededDialog(button) {
  1748. return new Promise(resolve => {
  1749. const styleElement = GM_addStyle(darkenPageStyle);
  1750. $(button).removeClass("translated");
  1751. $(button).text("字数超限");
  1752. $(button).css("cursor", "not-allowed");
  1753. $(button).prop("disabled", true);
  1754. let htmlString = `
  1755. <div class="wordsExceeded">
  1756. <h4>字数超限!</h4>
  1757. <p>注意,即将翻译的内容字数超过了4950个字符,您可能选择了错误的翻译按钮</p>
  1758. <div style="display:flex; padding:5px 0px; align-items: center;">
  1759. `+ helpCircleHTML + `
  1760. <p>
  1761. 由于实现方式,区域中会出现多个翻译按钮,请点击更小的子区域中的翻译按钮,
  1762. <br>或者在设置面板中开启 分段翻译 后重试。
  1763. </p>
  1764. </div>
  1765. <p>对于免费的接口,大量请求可能导致你的IP被暂时禁止访问,对于GPT,会消耗大量的token</p>
  1766. <p>您确定要继续翻译吗?</p>
  1767. <div style="display:flex; padding-top:10px">
  1768. <button id="continueButton">继续</button><button id="cancelButton">取消</button>
  1769. </div>
  1770. </div>
  1771. `;
  1772. $('body').before(htmlString);
  1773. $("#continueButton").click(function () {
  1774. $(styleElement).remove();
  1775. $('.wordsExceeded').remove();
  1776. resolve(true);
  1777. });
  1778. $("#cancelButton").click(function () {
  1779. $(styleElement).remove();
  1780. $('.wordsExceeded').remove();
  1781. resolve(false);
  1782. });
  1783. });
  1784. }
  1785.  
  1786. // 跳过折叠块确认
  1787. function skiFoldingBlocks() {
  1788. return new Promise(resolve => {
  1789. const styleElement = GM_addStyle(darkenPageStyle);
  1790. let htmlString = `
  1791. <div class="wordsExceeded">
  1792. <h4>是否跳过折叠块?</h4>
  1793. <p></p>
  1794. <div style="display:grid; padding:5px 0px; align-items: center;">
  1795. <p>
  1796. 即将翻译的区域中包含折叠块,可能不需要翻译,现在您需要选择是否跳过这些折叠块,
  1797. </p>
  1798. <p>
  1799. 如果其中有您需要翻译的折叠块,可以稍后再单独点击这些折叠块内的翻译按钮进行翻译
  1800. </p>
  1801. </div>
  1802. <p>要跳过折叠块吗?(建议选择跳过)</p>
  1803. <div style="display:flex; padding-top:10px">
  1804. <button id="cancelButton">否</button><button id="skipButton">跳过</button>
  1805. </div>
  1806. </div>
  1807. `;
  1808. $('body').before(htmlString);
  1809. $("#skipButton").click(function () {
  1810. $(styleElement).remove();
  1811. $('.wordsExceeded').remove();
  1812. resolve(true);
  1813. });
  1814. $("#cancelButton").click(function () {
  1815. $(styleElement).remove();
  1816. $('.wordsExceeded').remove();
  1817. resolve(false);
  1818. });
  1819. });
  1820. }
  1821.  
  1822. // 翻译框/翻译处理器
  1823. var translatedText = "";
  1824. async function translateProblemStatement(text, element_node, button) {
  1825. let status = 0;
  1826. let id = getRandomNumber(8);
  1827. let matches = [];
  1828. let replacements = {};
  1829. // 创建元素并放在element_node的后面
  1830. const translateDiv = document.createElement('div');
  1831. translateDiv.setAttribute('id', id);
  1832. translateDiv.classList.add('translate-problem-statement');
  1833. const spanElement = document.createElement('span');
  1834. translateDiv.appendChild(spanElement);
  1835. element_node.insertAdjacentElement('afterend', translateDiv);
  1836. // 替换latex公式
  1837. if (translation != "api2d" && translation != "openai") {
  1838. // 使用GPT翻译时不必替换latex公式
  1839. let i = 0;
  1840. // 块公式
  1841. matches = matches.concat(text.match(/\$\$([\s\S]*?)\$\$/g));
  1842. try {
  1843. for (i; i < matches.length; i++) {
  1844. let match = matches[i];
  1845. text = text.replace(match, `【${i + 1}】`);
  1846. replacements[`【${i + 1}】`] = match;
  1847. }
  1848. } catch (e) { }
  1849. // 行内公式
  1850. matches = matches.concat(text.match(/\$(.*?)\$/g));
  1851. try {
  1852. for (i; i < matches.length; i++) {
  1853. let match = matches[i];
  1854. text = text.replace(match, `【${i + 1}】`);
  1855. replacements[`【${i + 1}】`] = match;
  1856. }
  1857. } catch (e) { }
  1858. }
  1859. if (text.length > 4950) {
  1860. const shouldContinue = await showWordsExceededDialog(button);
  1861. if (!shouldContinue) {
  1862. status = 1;
  1863. return {
  1864. translateDiv: translateDiv,
  1865. status: status
  1866. };
  1867. }
  1868. }
  1869. // 翻译
  1870. if (translation == "deepl") {
  1871. translateDiv.textContent = "正在翻译中……请稍等";
  1872. translatedText = await translate_deepl(text);
  1873. } else if (translation == "youdao") {
  1874. translateDiv.textContent = "正在翻译中……请稍等";
  1875. translatedText = await translate_youdao_mobile(text);
  1876. } else if (translation == "google") {
  1877. translateDiv.textContent = "正在翻译中……请稍等";
  1878. translatedText = await translate_gg(text);
  1879. } else if (translation == "openai") {
  1880. translateDiv.textContent = "正在翻译中……\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待";
  1881. translatedText = await translate_openai(text);
  1882. } else if (translation == "api2d") {
  1883. translateDiv.textContent = "正在翻译中……\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待";
  1884. translatedText = await translate_api2d(text);
  1885. }
  1886. if (/^翻译出错/.test(translatedText)) status = 2;
  1887.  
  1888. // 还原latex公式
  1889. if (translation != "api2d" && translation != "openai") {
  1890. try {
  1891. for (let i = 0; i < matches.length; i++) {
  1892. let match = matches[i];
  1893. let replacement = replacements[`【${i + 1}】`];
  1894. let regex;
  1895. regex = new RegExp(`【${i + 1}】`, 'g');
  1896. translatedText = translatedText.replace(regex, replacement);
  1897. regex = new RegExp(`\\[${i + 1}\\]`, 'g');
  1898. translatedText = translatedText.replace(regex, replacement);
  1899. regex = new RegExp(`【${i + 1}[^】\\d]`, 'g');
  1900. translatedText = translatedText.replace(regex, replacement);
  1901. regex = new RegExp(`[^【\\d]${i + 1}】`, 'g');
  1902. translatedText = translatedText.replace(regex, " " + replacement);
  1903. }
  1904. } catch (e) { }
  1905. }
  1906.  
  1907. // 创建一个隐藏的元素来保存 translatedText 的值
  1908. var textElement = document.createElement("div");
  1909. textElement.style.display = "none";
  1910. textElement.textContent = translatedText;
  1911. translateDiv.parentNode.insertBefore(textElement, translateDiv);
  1912.  
  1913. // 翻译复制按钮
  1914. var copyButton = document.createElement("button");
  1915. copyButton.textContent = "Copy";
  1916. $(copyButton).addClass("html2mdButton html2md-cb");
  1917. $(copyButton).css({
  1918. "float": "right",
  1919. });
  1920. copyButton.addEventListener("click", function () {
  1921. var translatedText = textElement.textContent;
  1922. GM_setClipboard(translatedText);
  1923. $(this).addClass("copied");
  1924. $(this).text("Copied");
  1925. // 更新复制按钮文本
  1926. setTimeout(() => {
  1927. $(this).removeClass("copied");
  1928. $(this).text("Copy");
  1929. }, 2000);
  1930. });
  1931. translateDiv.parentNode.insertBefore(copyButton, translateDiv);
  1932.  
  1933. // 替换特殊符号为字符实体
  1934. const ruleMap = [
  1935. { pattern: /(?<!\\)>(?!\s)/g, replacement: "&gt;" }, // >符号
  1936. { pattern: /(?<!\\)</g, replacement: "&lt;" }, // <符号
  1937. ];
  1938.  
  1939. ruleMap.forEach(({ pattern, replacement }) => {
  1940. translatedText = translatedText.replace(pattern, replacement);
  1941. });
  1942.  
  1943. // 更新
  1944. translateDiv.innerHTML = translatedText;
  1945. // 渲染MarkDown
  1946. var md = window.markdownit();
  1947. var html = md.render(translateDiv.innerText);
  1948. translateDiv.innerHTML = html;
  1949. // 渲染Latex
  1950. if (typeof renderMathInElement === 'function') {
  1951. renderMathInElement(document.getElementById(id), {
  1952. delimiters: [{
  1953. left: "$$",
  1954. right: "$$",
  1955. display: true
  1956. }, {
  1957. left: "$",
  1958. right: "$",
  1959. display: false
  1960. }]
  1961. });
  1962. }
  1963. return {
  1964. translateDiv: translateDiv,
  1965. status: status,
  1966. copyDiv: textElement,
  1967. copyButton: copyButton
  1968. };
  1969.  
  1970. }
  1971.  
  1972. // ChatGPT
  1973. async function translate_openai(raw) {
  1974. var openai_key = GM_getValue("openai_key");
  1975. var openai_retext = "";
  1976. var data = {
  1977. model: "gpt-3.5-turbo",
  1978. messages: [{
  1979. role: "user",
  1980. content: "(请将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw + ")"
  1981. }],
  1982. temperature: 0.7
  1983. };
  1984. return new Promise(function (resolve, reject) {
  1985. GM_xmlhttpRequest({
  1986. method: 'POST',
  1987. 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
  1988.  
  1989. data: JSON.stringify(data),
  1990. headers: {
  1991. 'Content-Type': 'application/json',
  1992. 'Authorization': 'Bearer ' + GM_getValue("openai_key")
  1993. },
  1994. responseType: 'json',
  1995. onload: function (response) {
  1996. if (!response.response.choices || response.response.choices.length < 1 || !response.response.choices[0].message) {
  1997. resolve("翻译出错,请重试\n如果无法解决,请前往 https://greatest.deepsurf.us/zh-CN/scripts/471106/feedback 反馈\n\n报错信息:" + JSON.stringify(response.response, null, '\n'));
  1998. } else {
  1999. openai_retext = response.response.choices[0].message.content;
  2000. // openai_retext = openai_retext.replace(/^\s+/, '');
  2001. resolve(openai_retext);
  2002. }
  2003. },
  2004. onerror: function (response) {
  2005. console.error(response.statusText);
  2006. reject(response.statusText);
  2007. },
  2008. });
  2009.  
  2010. });
  2011. }
  2012.  
  2013. // api2d
  2014. async function translate_api2d(raw) {
  2015. var api2d_key = GM_getValue("api2d_key");
  2016. var api2d_retext = "";
  2017. var postData = JSON.stringify({
  2018. model: 'gpt-3.5-turbo',
  2019. messages: [{ role: 'user', content: '请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n' + raw }],
  2020. temperature: 0.7
  2021. });
  2022. const options = {
  2023. method: 'POST',
  2024. headers: {
  2025. 'Content-Type': 'application/json',
  2026. Authorization: 'Bearer ' + api2d_key,
  2027. ...(x_api2d_no_cache ? {} : { 'x-api2d-no-cache': 1 })
  2028. },
  2029. data: postData,
  2030. };
  2031.  
  2032. return new Promise(function (resolve, reject) {
  2033. GM_xmlhttpRequest({
  2034. method: options.method,
  2035. url: `https://openai.api2d.net/v1/chat/completions`,
  2036. headers: options.headers,
  2037. data: options.data,
  2038. responseType: 'json',
  2039. onload: function (response) {
  2040. if (!response.response.choices || response.response.choices.length < 1 || !response.response.choices[0].message) {
  2041. resolve("翻译出错,请重试\n如果无法解决,请前往 https://greatest.deepsurf.us/zh-CN/scripts/465777/feedback 反馈\n\n报错信息:" + JSON.stringify(response.response, null, '\n'));
  2042. } else {
  2043. api2d_retext = response.response.choices[0].message.content;
  2044. resolve(api2d_retext);
  2045. }
  2046. },
  2047. onerror: function (response) {
  2048. console.error(response.statusText);
  2049. reject(response.statusText);
  2050. },
  2051. });
  2052. });
  2053.  
  2054.  
  2055. }
  2056. //
  2057.  
  2058. //--谷歌翻译--start
  2059. async function translate_gg(raw) {
  2060. return new Promise((resolve, reject) => {
  2061. const url = 'https://translate.google.com/m';
  2062. const params = `tl=zh-CN&q=${encodeURIComponent(raw)}`;
  2063.  
  2064. GM_xmlhttpRequest({
  2065. method: 'GET',
  2066. url: `${url}?${params}`,
  2067. onload: function (response) {
  2068. const html = response.responseText;
  2069. const translatedText = $(html).find('.result-container').text();
  2070. resolve(translatedText);
  2071. },
  2072. onerror: function (error) {
  2073. console.error('Error:', error);
  2074. reject(error);
  2075. }
  2076. });
  2077. });
  2078. }
  2079. //--谷歌翻译--end
  2080.  
  2081. //--有道翻译m--start
  2082. async function translate_youdao_mobile(raw) {
  2083. const options = {
  2084. method: "POST",
  2085. url: 'http://m.youdao.com/translate',
  2086. data: "inputtext=" + encodeURIComponent(raw) + "&type=AUTO",
  2087. anonymous: true,
  2088. headers: {
  2089. "Content-Type": "application/x-www-form-urlencoded",
  2090. 'Host': 'm.youdao.com',
  2091. 'Origin': 'http://m.youdao.com',
  2092. 'Referer': 'http://m.youdao.com/translate',
  2093. }
  2094. }
  2095. return await BaseTranslate('有道翻译mobile', raw, options, res => /id="translateResult">\s*?<li>([\s\S]*?)<\/li>\s*?<\/ul/.exec(res)[1])
  2096. }
  2097. //--有道翻译m--end
  2098.  
  2099. //--Deepl翻译--start
  2100. function getTimeStamp(iCount) {
  2101. const ts = Date.now();
  2102. if (iCount !== 0) {
  2103. iCount = iCount + 1;
  2104. return ts - (ts % iCount) + iCount;
  2105. } else {
  2106. return ts;
  2107. }
  2108. }
  2109.  
  2110. async function translate_deepl(raw) {
  2111. const id = (Math.floor(Math.random() * 99999) + 100000) * 1000;
  2112. const data = {
  2113. jsonrpc: '2.0',
  2114. method: 'LMT_handle_texts',
  2115. id,
  2116. params: {
  2117. splitting: 'newlines',
  2118. lang: {
  2119. source_lang_user_selected: 'auto',
  2120. target_lang: 'ZH',
  2121. },
  2122. texts: [{
  2123. text: raw,
  2124. requestAlternatives: 3
  2125. }],
  2126. timestamp: getTimeStamp(raw.split('i').length - 1)
  2127. }
  2128. }
  2129. let postData = JSON.stringify(data);
  2130. if ((id + 5) % 29 === 0 || (id + 3) % 13 === 0) {
  2131. postData = postData.replace('"method":"', '"method" : "');
  2132. } else {
  2133. postData = postData.replace('"method":"', '"method": "');
  2134. }
  2135. const options = {
  2136. method: 'POST',
  2137. url: 'https://www2.deepl.com/jsonrpc',
  2138. data: postData,
  2139. headers: {
  2140. 'Content-Type': 'application/json',
  2141. 'Host': 'www2.deepl.com',
  2142. 'Origin': 'https://www.deepl.com',
  2143. 'Referer': 'https://www.deepl.com/',
  2144. },
  2145. anonymous: true,
  2146. nocache: true,
  2147. }
  2148. return await BaseTranslate('Deepl翻译', raw, options, res => JSON.parse(res).result.texts[0].text)
  2149. }
  2150.  
  2151. //--Deepl翻译--end
  2152.  
  2153. //--异步请求包装工具--start
  2154. async function PromiseRetryWrap(task, options, ...values) {
  2155. const { RetryTimes, ErrProcesser } = options || {};
  2156. let retryTimes = RetryTimes || 5;
  2157. const usedErrProcesser = ErrProcesser || (err => { throw err });
  2158. if (!task) return;
  2159. while (true) {
  2160. try {
  2161. return await task(...values);
  2162. } catch (err) {
  2163. if (!--retryTimes) {
  2164. console.log(err);
  2165. return usedErrProcesser(err);
  2166. }
  2167. }
  2168. }
  2169. }
  2170.  
  2171. async function BaseTranslate(name, raw, options, processer) {
  2172. let errtext;
  2173. const toDo = async () => {
  2174. var tmp;
  2175. try {
  2176. const data = await Request(options);
  2177. tmp = data.responseText;
  2178. const result = await processer(tmp);
  2179. if (result) sessionStorage.setItem(name + '-' + raw, result);
  2180. return result
  2181. } catch (err) {
  2182. errtext = tmp;
  2183. throw {
  2184. responseText: tmp,
  2185. err: err
  2186. }
  2187. }
  2188. }
  2189. return await PromiseRetryWrap(toDo, { RetryTimes: 3, ErrProcesser: () => "翻译出错,请重试或更换翻译接口\n如果无法解决,请前往 https://greatest.deepsurf.us/zh-CN/scripts/465777/feedback 反馈\n\n报错信息:" + errtext })
  2190. }
  2191.  
  2192.  
  2193. function Request(options) {
  2194. return new Promise((reslove, reject) => GM_xmlhttpRequest({ ...options, onload: reslove, onerror: reject }))
  2195. }
  2196.  
  2197. //--异步请求包装工具--end