Atcoder Better!

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

As of 2023-09-02. See the latest version.

  1. // ==UserScript==
  2. // @name Atcoder Better!
  3. // @namespace https://greatest.deepsurf.us/users/747162
  4. // @version 1.09
  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_deleteValue
  21. // @grant GM_addStyle
  22. // @grant GM_setClipboard
  23. // @icon https://aowuucdn.oss-cn-beijing.aliyuncs.com/atcoder.png
  24. // @require https://cdn.staticfile.org/turndown/7.1.2/turndown.min.js
  25. // @require https://cdn.staticfile.org/markdown-it/13.0.1/markdown-it.min.js
  26. // @license MIT
  27. // @compatible Chrome
  28. // @compatible Firefox
  29. // @compatible Edge
  30. // ==/UserScript==
  31.  
  32. // 状态与初始化
  33. const getGMValue = (key, defaultValue) => {
  34. const value = GM_getValue(key);
  35. if (value === undefined || value === "") {
  36. GM_setValue(key, defaultValue);
  37. return defaultValue;
  38. }
  39. return value;
  40. };
  41.  
  42. const bottomZh_CN = getGMValue("bottomZh_CN", true);
  43. const showLoading = getGMValue("showLoading", true);
  44. const hoverTargetAreaDisplay = getGMValue("hoverTargetAreaDisplay", false);
  45. var enableSegmentedTranslation = getGMValue("enableSegmentedTranslation", false);
  46. const showJumpToLuogu = getGMValue("showJumpToLuogu", true);
  47. const loaded = getGMValue("loaded", false);
  48. var translation = getGMValue("translation", "deepl");
  49. //openai
  50. var openai_model, openai_key, openai_proxy, openai_header, openai_data;
  51. var opneaiConfig = getGMValue("chatgpt-config", {
  52. "choice": -1,
  53. "configurations": []
  54. });
  55. if (opneaiConfig.choice !== -1 && opneaiConfig.configurations.length !== 0) {
  56. const configAtIndex = opneaiConfig.configurations[opneaiConfig.choice];
  57.  
  58. if (configAtIndex == undefined) {
  59. let existingConfig = GM_getValue('chatgpt-config');
  60. existingConfig.choice = 0;
  61. GM_setValue('chatgpt-config', existingConfig);
  62. location.reload();
  63. }
  64. openai_model = configAtIndex.model;
  65. openai_key = configAtIndex.key;
  66. openai_proxy = configAtIndex.proxy;
  67. openai_header = configAtIndex._header ?
  68. configAtIndex._header.split("\n").map(header => {
  69. const [key, value] = header.split(":");
  70. return { [key.trim()]: value.trim() };
  71. }) : [];
  72. openai_data = configAtIndex._data ?
  73. configAtIndex._data.split("\n").map(header => {
  74. const [key, value] = header.split(":");
  75. return { [key.trim()]: value.trim() };
  76. }) : [];
  77. }
  78.  
  79. // 常量
  80. 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>';
  81. 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; }`;
  82. const darkenPageStyle2 = `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: 10000; }`;
  83.  
  84. // 语言判断
  85. const isEnglishLanguage = (function () {
  86. var metaElement = $('meta[http-equiv="Content-Language"]');
  87. var contentValue = metaElement.attr('content');
  88. return (contentValue === 'en');
  89. })();
  90.  
  91. // 样式
  92. GM_addStyle(`
  93. :root {
  94. --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";
  95. }
  96. span.mdViewContent {
  97. white-space: pre-wrap;
  98. }
  99. /*翻译区域提示*/
  100. .overlay {
  101. pointer-events: none;
  102. position: absolute;
  103. top: 0;
  104. left: 0;
  105. width: 100%;
  106. height: 100%;
  107. background: repeating-linear-gradient(135deg, #97e7cacc, #97e7cacc 30px, #e9fbf1cc 0px, #e9fbf1cc 55px);
  108. border-radius: 5px;
  109. display: flex;
  110. align-items: center;
  111. justify-content: center;
  112. color: #00695C;
  113. font-size: 16px;
  114. font-weight: bold;
  115. text-shadow: 0px 0px 2px #edfcf4;
  116. }
  117. /*翻译div*/
  118. .translate-problem-statement {
  119. justify-items: start;
  120. letter-spacing: 1.8px;
  121. color: #059669;
  122. background-color: #f9f9fa;
  123. border: 1px solid #10b981;
  124. border-radius: 0.3rem;
  125. padding: 5px;
  126. margin: 10px 0px;
  127. width: 100%;
  128. box-sizing: border-box;
  129. font-size: 13px;
  130. }
  131. .translate-problem-statement.error_translate {
  132. color: red;
  133. border-color: red;
  134. }
  135.  
  136. .translate-problem-statement h2, .translate-problem-statement h3 {
  137. font-size: 16px;
  138. }
  139.  
  140. .translate-problem-statement ul {
  141. line-height: 100%;
  142. }
  143.  
  144. .translate-problem-statement a {
  145. color: #10b981;
  146. font-weight: 600;
  147. background: 0 0;
  148. text-decoration: none;
  149. }
  150. .translate-problem-statement p {
  151. font-size: 14px !important;
  152. }
  153. .translate-problem-statement img {
  154. max-width: 100.0%;
  155. max-height: 100.0%;
  156. }
  157.  
  158. .translate-problem-statement .katex {
  159. font-size: 14px;
  160. }
  161. .translate-problem-statement a:hover {
  162. text-decoration: revert;
  163. }
  164. .html2md-panel {
  165. display: flex;
  166. justify-content: flex-end;
  167. }
  168. .html2md-panel a {
  169. text-decoration: none;
  170. }
  171. button.html2mdButton {
  172. display: flex;
  173. align-items: center;
  174. cursor: pointer;
  175. background-color: #ffffff;
  176. color: #606266;
  177. height: 22px;
  178. width: auto;
  179. font-size: 13px;
  180. border-radius: 0.3rem;
  181. padding: 1px 5px;
  182. margin: 5px;
  183. border: 1px solid #dcdfe6;
  184. }
  185. button.html2mdButton:hover {
  186. color: #409eff;
  187. border-color: #409eff;
  188. }
  189. button.html2mdButton.copied {
  190. background-color: #f0f9eb;
  191. color: #67c23e;
  192. border: 1px solid #b3e19d;
  193. }
  194. button.html2mdButton.mdViewed {
  195. background-color: #fdf6ec;
  196. color: #e6a23c;
  197. border: 1px solid #f3d19e;
  198. }
  199. button.html2mdButton.error {
  200. background-color: #fef0f0;
  201. color: #f56c6c;
  202. border: 1px solid #fab6b6;
  203. }
  204. button.translated {
  205. cursor: not-allowed;
  206. background-color: #f0f9eb;
  207. color: #67c23e;
  208. border: 1px solid #b3e19d;
  209. }
  210. button.html2mdButton.reTranslation {
  211. background-color: #f4f4f5;
  212. color: #909399;
  213. border: 1px solid #c8c9cc;
  214. }
  215. .translate-problem-statement table {
  216. border: 1px #ccc solid !important;
  217. margin: 1.5em 0 !important;
  218. color: #059669 !important;
  219. }
  220. .translate-problem-statement table thead th {
  221. border: 1px #ccc solid !important;
  222. color: #059669 !important;
  223. }
  224. .translate-problem-statement table td {
  225. border-right: 1px solid #ccc;
  226. border-top: 1px solid #ccc;
  227. padding: 0.7143em 0.5em;
  228. }
  229. .translate-problem-statement table th {
  230. padding: 0.7143em 0.5em;
  231. }
  232. .translate-problem-statement p:not(:first-child) {
  233. margin: 1.5em 0 0;
  234. }
  235. /*设置面板*/
  236. header .enter-or-register-box, header .languages {
  237. position: absolute;
  238. right: 170px;
  239. }
  240. button.html2mdButton.AtBetter_setting {
  241. float: right;
  242. height: 30px;
  243. background: #3c5a7f;
  244. color: white;
  245. margin: 10px;
  246. border: 0px;
  247. }
  248.  
  249. button.html2mdButton.AtBetter_setting.open {
  250. background-color: #e6e6e61f;
  251. color: #727378;
  252. cursor: not-allowed;
  253. }
  254. .AtBetter_setting_menu {
  255. z-index: 9999;
  256. box-shadow: 0px 0px 0px 4px #ffffff;
  257. display: grid;
  258. position: fixed;
  259. top: 50%;
  260. left: 50%;
  261. width: 480px;
  262. max-height: 90vh;
  263. overflow-y: auto;
  264. transform: translate(-50%, -50%);
  265. border-radius: 6px;
  266. background-color: #edf1ff;
  267. border-collapse: collapse;
  268. border: 1px solid #ffffff;
  269. color: #697e91;
  270. font-family: var(--vp-font-family-base);
  271. padding: 10px 20px 20px 20px;
  272. box-sizing: content-box;
  273. }
  274. .AtBetter_setting_menu h4,.AtBetter_setting_menu h5 {
  275. font-weight: 600;
  276. }
  277. .AtBetter_setting_menu h3 {
  278. margin-top: 10px;
  279. }
  280. .AtBetter_setting_menu hr {
  281. border: none;
  282. height: 1px;
  283. background-color: #ccc;
  284. margin: 10px 0;
  285. }
  286. /*设置面板-关闭按钮*/
  287. .AtBetter_setting_menu .tool-box {
  288. position: absolute;
  289. display: flex;
  290. align-items: center;
  291. justify-content: center;
  292. width: 2.5rem;
  293. height: 2.5rem;
  294. top: 3px;
  295. right: 3px;
  296. }
  297.  
  298. .AtBetter_setting_menu .btn-close {
  299. display: flex;
  300. align-items: center;
  301. justify-content: center;
  302. text-align: center;
  303. width: 20px;
  304. height: 20px;
  305. color: transparent;
  306. font-size: 0;
  307. cursor: pointer;
  308. background-color: #ff000080;
  309. border: none;
  310. border-radius: 10px;
  311. transition: .15s ease all;
  312. }
  313.  
  314. .AtBetter_setting_menu .btn-close:hover {
  315. width: 20px;
  316. height: 20px !important;
  317. font-size: 17px;
  318. color: #ffffff;
  319. background-color: #ff0000cc;
  320. box-shadow: 0 5px 5px 0 #00000026;
  321. }
  322.  
  323. .AtBetter_setting_menu .btn-close:active {
  324. width: .9rem;
  325. height: .9rem;
  326. font-size: 1px;
  327. color: #ffffffde;
  328. --shadow-btn-close: 0 3px 3px 0 #00000026;
  329. box-shadow: var(--shadow-btn-close);
  330. }
  331.  
  332. /*设置面板-checkbox*/
  333. .AtBetter_setting_menu input[type=checkbox]:focus {
  334. outline: 0px;
  335. }
  336.  
  337. .AtBetter_setting_menu input[type="checkbox"] {
  338. margin: 0px;
  339. appearance: none;
  340. -webkit-appearance: none;
  341. width: 40px;
  342. height: 20px !important;
  343. border: 1.5px solid #D7CCC8;
  344. padding: 0px !important;
  345. border-radius: 20px;
  346. background: #efebe978;
  347. position: relative;
  348. box-sizing: border-box;
  349. }
  350.  
  351. .AtBetter_setting_menu input[type="checkbox"]::before {
  352. content: "";
  353. width: 14px;
  354. height: 14px;
  355. background: #D7CCC8;
  356. border: 1.5px solid #BCAAA4;
  357. border-radius: 50%;
  358. position: absolute;
  359. top: 0;
  360. left: 0;
  361. transform: translate(2%, 2%);
  362. transition: all 0.3s ease-in-out;
  363. -webkit-box-sizing: content-box;
  364. -moz-box-sizing: content-box;
  365. box-sizing: content-box;
  366. }
  367.  
  368. .AtBetter_setting_menu input[type="checkbox"]::after {
  369. 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");
  370. position: absolute;
  371. top: 0;
  372. left: 24px;
  373. }
  374.  
  375. .AtBetter_setting_menu input[type="checkbox"]:checked {
  376. border: 1.5px solid #C5CAE9;
  377. background: #E8EAF6;
  378. }
  379.  
  380. .AtBetter_setting_menu input[type="checkbox"]:checked::before {
  381. background: #C5CAE9;
  382. border: 1.5px solid #7986CB;
  383. transform: translate(122%, 2%);
  384. transition: all 0.3s ease-in-out;
  385. }
  386.  
  387. .AtBetter_setting_menu input[type="checkbox"]:checked::after {
  388. 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");
  389. position: absolute;
  390. top: 1.5px;
  391. left: 4.5px;
  392. }
  393.  
  394. .AtBetter_setting_menu label {
  395. font-size: 16px;
  396. font-weight: initial;
  397. margin-bottom: 0px;
  398. }
  399.  
  400. .AtBetter_setting_list {
  401. display: flex;
  402. align-items: center;
  403. padding: 10px;
  404. margin: 5px 0px;
  405. background-color: #ffffff;
  406. border-bottom: 1px solid #c9c6c696;
  407. border-radius: 8px;
  408. justify-content: space-between;
  409. }
  410.  
  411. /*设置面板-radio*/
  412. .AtBetter_setting_menu>label {
  413. display: flex;
  414. list-style-type: none;
  415. padding-inline-start: 0px;
  416. overflow-x: auto;
  417. max-width: 100%;
  418. margin: 0px;
  419. align-items: center;
  420. margin: 3px 0px;
  421. }
  422.  
  423. .AtBetter_setting_menu_label_text {
  424. display: flex;
  425. border: 1px dashed #00aeeccc;
  426. height: 35px;
  427. width: 100%;
  428. color: gray;
  429. font-weight: 300;
  430. font-size: 14px;
  431. letter-spacing: 2px;
  432. padding: 7px;
  433. align-items: center;
  434. -webkit-box-sizing: border-box;
  435. -moz-box-sizing: border-box;
  436. box-sizing: border-box;
  437. }
  438.  
  439. input[type="radio"]:checked+.AtBetter_setting_menu_label_text {
  440. background: #41e49930;
  441. border: 1px solid green;
  442. color: green;
  443. font-weight: 500;
  444. }
  445.  
  446. .AtBetter_setting_menu>label input[type="radio"] {
  447. -webkit-appearance: none;
  448. appearance: none;
  449. list-style: none;
  450. padding: 0px !important;
  451. margin: 0px;
  452. }
  453.  
  454. .AtBetter_setting_menu input[type="text"] {
  455. display: block;
  456. height: 25px !important;
  457. width: 100%;
  458. background-color: #ffffff;
  459. color: #727378;
  460. font-size: 12px;
  461. border-radius: 0.3rem;
  462. padding: 1px 5px !important;
  463. box-sizing: border-box;
  464. margin: 5px 0px 5px 0px;
  465. border: 1px solid #00aeeccc;
  466. box-shadow: 0 0 1px #0000004d;
  467. }
  468.  
  469. .AtBetter_setting_menu input[type="text"]:focus-visible{
  470. border-style: solid;
  471. border-color: #3f51b5;
  472. outline: none;
  473. }
  474.  
  475. .AtBetter_setting_menu_input {
  476. width: 100%;
  477. display: grid;
  478. margin-top: 5px;
  479. -webkit-box-sizing: border-box;
  480. -moz-box-sizing: border-box;
  481. box-sizing: border-box;
  482. }
  483. .AtBetter_setting_menu input::placeholder {
  484. color: #727378;
  485. }
  486. .AtBetter_setting_menu input.no_default::placeholder{
  487. color: #BDBDBD;
  488. }
  489. .AtBetter_setting_menu input.is_null::placeholder{
  490. color: red;
  491. border-width: 1.5px;
  492. }
  493. .AtBetter_setting_menu input.is_null{
  494. border-color: red;
  495. }
  496. .AtBetter_setting_menu textarea {
  497. display: block;
  498. width: 100%;
  499. height: 60px;
  500. background-color: #ffffff;
  501. color: #727378;
  502. font-size: 12px;
  503. padding: 1px 5px !important;
  504. box-sizing: border-box;
  505. margin: 5px 0px 5px 0px;
  506. border: 1px solid #00aeeccc;
  507. box-shadow: 0 0 1px #0000004d;
  508. }
  509. .AtBetter_setting_menu textarea:focus-visible{
  510. border-style: solid;
  511. border-color: #3f51b5;
  512. outline: none;
  513. }
  514. .AtBetter_setting_menu textarea::placeholder{
  515. color: #BDBDBD;
  516. font-size: 14px;
  517. }
  518.  
  519. .AtBetter_setting_menu #save {
  520. cursor: pointer;
  521. display: inline-flex;
  522. padding: 5px;
  523. background-color: #1aa06d;
  524. color: #ffffff;
  525. font-size: 14px;
  526. line-height: 1.5rem;
  527. font-weight: 500;
  528. justify-content: center;
  529. width: 100%;
  530. border-radius: 0.375rem;
  531. border: none;
  532. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  533. margin-top: 20px
  534. }
  535. .AtBetter_setting_menu button#debug_button.debug_button {
  536. width: 18%;
  537. }
  538.  
  539. .AtBetter_setting_menu span.tip {
  540. color: #999;
  541. font-size: 12px;
  542. font-weight: 500;
  543. padding: 5px 0px;
  544. }
  545. /*设置面板-tip*/
  546. .help_tip {
  547. margin-right: auto;
  548. }
  549. span.input_label {
  550. font-size: 14px;
  551. }
  552. .help_tip .tip_text {
  553. display: none;
  554. position: absolute;
  555. color: #697e91;
  556. font-weight: 400;
  557. font-size: 14px;
  558. letter-spacing: 0px;
  559. background-color: #ffffff;
  560. padding: 10px;
  561. margin: 5px 0px;
  562. border-radius: 4px;
  563. border: 1px solid #e4e7ed;
  564. box-shadow: 0px 0px 12px rgba(0, 0, 0, .12);
  565. z-index: 999;
  566. }
  567. .help_tip .tip_text p {
  568. margin-bottom: 5px;
  569. }
  570. .help_tip .tip_text:before {
  571. content: "";
  572. position: absolute;
  573. top: -20px;
  574. right: -10px;
  575. bottom: -10px;
  576. left: -10px;
  577. z-index: -1;
  578. }
  579. .help-icon {
  580. cursor: help;
  581. width: 15px;
  582. color: #b4b9d4;
  583. margin-left: 5px;
  584. margin-top: 3px;
  585. }
  586. .AtBetter_setting_menu .AtBetter_setting_menu_label_text .help_tip .help-icon {
  587. color: #7fbeb2;
  588. }
  589. .help_tip .help-icon:hover + .tip_text, .help_tip .tip_text:hover {
  590. display: block;
  591. cursor: help;
  592. width: 250px;
  593. }
  594.  
  595. /*确认弹窗*/
  596. .wordsExceeded {
  597. z-index: 99999;
  598. box-shadow: 0px 0px 5px 1px rgb(0 0 0 / 10%), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  599. display: grid;
  600. position: fixed;
  601. top: 50%;
  602. left: 50%;
  603. transform: translate(-50%, -50%);
  604. border-radius: 4px;
  605. background-color: #ffffff;
  606. border: 1px solid #e4e7ed;
  607. color: #697e91;
  608. font-family: var(--vp-font-family-base);
  609. padding: 10px 20px 20px 20px;
  610. }
  611. .wordsExceeded button {
  612. display: inline-flex;
  613. justify-content: center;
  614. align-items: center;
  615. line-height: 1;
  616. white-space: nowrap;
  617. cursor: pointer;
  618. text-align: center;
  619. box-sizing: border-box;
  620. outline: none;
  621. transition: .1s;
  622. user-select: none;
  623. vertical-align: middle;
  624. -webkit-appearance: none;
  625. height: 24px;
  626. padding: 5px 11px;
  627. font-size: 12px;
  628. border-radius: 4px;
  629. color: #ffffff;
  630. background: #409eff;
  631. border-color: #409eff;
  632. border: none;
  633. margin-right: 12px;
  634. }
  635. .wordsExceeded button:hover{
  636. background-color:#79bbff;
  637. }
  638. .wordsExceeded .help-icon {
  639. margin: 0px 8px 0px 0px;
  640. height: 1em;
  641. width: 1em;
  642. line-height: 1em;
  643. display: inline-flex;
  644. justify-content: center;
  645. align-items: center;
  646. position: relative;
  647. fill: currentColor;
  648. font-size: inherit;
  649. }
  650. .wordsExceeded p {
  651. margin: 5px 0px;
  652. }
  653. /*更新检查*/
  654. div#update_panel {
  655. z-index: 9999;
  656. position: fixed;
  657. top: 50%;
  658. left: 50%;
  659. width: 240px;
  660. transform: translate(-50%, -50%);
  661. box-shadow: 0px 0px 4px 0px #0000004d;
  662. padding: 10px 20px 20px 20px;
  663. color: #444242;
  664. background-color: #f5f5f5;
  665. border: 1px solid #848484;
  666. border-radius: 8px;
  667. }
  668. div#update_panel #updating {
  669. cursor: pointer;
  670. display: inline-flex;
  671. padding: 0px;
  672. background-color: #1aa06d;
  673. color: #ffffff;
  674. font-size: 14px;
  675. line-height: 1.5rem;
  676. font-weight: 500;
  677. justify-content: center;
  678. width: 100%;
  679. border-radius: 0.375rem;
  680. border: none;
  681. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  682. }
  683. div#update_panel #updating a {
  684. text-decoration: none;
  685. color: white;
  686. display: flex;
  687. position: inherit;
  688. top: 0;
  689. left: 0;
  690. width: 100%;
  691. height: 22px;
  692. font-size: 14px;
  693. justify-content: center;
  694. align-items: center;
  695. }
  696. #skip_menu {
  697. display: flex;
  698. margin-top: 10px;
  699. justify-content: flex-end;
  700. align-items: center;
  701. }
  702. #skip_menu .help_tip {
  703. margin-right: 5px;
  704. margin-left: -5px;
  705. }
  706. #skip_menu .help-icon {
  707. color: #f44336;
  708. }
  709. /* 配置管理 */
  710. .embed-responsive {
  711. height: max-content;
  712. padding-bottom: 0px;
  713. }
  714. .config_bar {
  715. height: 70px;
  716. width: 100%;
  717. display: flex;
  718. justify-content: space-between;
  719. }
  720. li#add_button {
  721. cursor: pointer;
  722. height: 40px;
  723. border: 1px dashed #BDBDBD;
  724. border-radius: 8px;
  725. background-color: #fcfbfb36;
  726. color: #bdbdbd;
  727. font-size: 14px;
  728. align-items: center;
  729. justify-content: center;
  730. }
  731. li#add_button:hover {
  732. border: 1px dashed #03A9F4;
  733. background-color: #d7f0fb8c;
  734. color: #03A9F4;
  735. }
  736. div#config_bar_list {
  737. display: flex;
  738. width: 480px;
  739. border: 1px solid #c5cae9;
  740. border-radius: 8px;
  741. background-color: #f0f8ff;
  742. box-sizing: border-box;
  743. }
  744. div#config_bar_list input[type="radio"] {
  745. appearance: none;
  746. width: 0;
  747. height: 0;
  748. overflow: hidden;
  749. }
  750. div#config_bar_list input[type="radio"] {
  751. margin: 0px;
  752. }
  753. div#config_bar_list input[type=radio]:focus {
  754. outline: 0px;
  755. }
  756. label.config_bar_ul_li_text {
  757. display: flex;
  758. align-items: center;
  759. justify-content: center;
  760. max-width: 100%;
  761. height: 40px;
  762. overflow-x: auto;
  763. font-size: 14px;
  764. font-weight: 400;
  765. margin: 0px 4px;
  766. padding: 3px;
  767. border: 1px solid #dedede;
  768. border-radius: 10px;
  769. box-shadow: 0px 2px 4px 0px rgba(0,0,0,.05);
  770. box-sizing: border-box;
  771. }
  772. ul#config_bar_ul li button {
  773. background-color: #e6e6e6;
  774. color: #727378;
  775. height: 23px;
  776. font-size: 14px;
  777. border-radius: 0.3rem;
  778. padding: 1px 5px;
  779. margin: 5px;
  780. border: none;
  781. box-shadow: 0 0 1px #0000004d;
  782. }
  783. ul#config_bar_ul {
  784. display: flex;
  785. align-items: center;
  786. list-style-type: none;
  787. padding-inline-start: 0px;
  788. overflow-x: auto;
  789. max-width: 100%;
  790. margin: 0px;
  791. }
  792. ul#config_bar_ul li {
  793. width: 80px;
  794. display: grid;
  795. margin: 4px 4px;
  796. min-width: 100px;
  797. box-sizing: border-box;
  798. }
  799. label.config_bar_ul_li_text:hover {
  800. background-color: #eae4dc24;
  801. }
  802. input[type="radio"]:checked + .config_bar_ul_li_text {
  803. background: #41b3e430;
  804. border: 1px solid #5e7ce0;
  805. color: #5e7ce0;
  806. }
  807. ul#config_bar_ul::-webkit-scrollbar {
  808. width: 5px;
  809. height: 5px;
  810. }
  811. ul#config_bar_ul::-webkit-scrollbar-thumb {
  812. background-clip: padding-box;
  813. background-color: #d7d9e4;
  814. border-radius: 8px;
  815. }
  816. ul#config_bar_ul::-webkit-scrollbar-button:start:decrement {
  817. width: 4px;
  818. background-color: transparent;
  819. }
  820. ul#config_bar_ul::-webkit-scrollbar-button:end:increment {
  821. width: 4px;
  822. background-color: transparent;
  823. }
  824. ul#config_bar_ul::-webkit-scrollbar-track {
  825. background-color: #f1f1f1;
  826. border-radius: 5px;
  827. }
  828. label.config_bar_ul_li_text::-webkit-scrollbar {
  829. width: 5px;
  830. height: 7px;
  831. background-color: #aaa;
  832. }
  833. label.config_bar_ul_li_text::-webkit-scrollbar-thumb {
  834. background-clip: padding-box;
  835. background-color: #d7d9e4;
  836. }
  837. label.config_bar_ul_li_text::-webkit-scrollbar-track {
  838. background-color: #f1f1f1;
  839. }
  840. .config_bar_list_add_div {
  841. display: flex;
  842. height: 40px;
  843. margin: 4px 2px;
  844. }
  845. /* 修改菜单 */
  846. div#config_bar_menu {
  847. z-index: 99999;
  848. position: absolute;
  849. width: 60px;
  850. background: #ffffff;
  851. box-shadow: 1px 1px 4px 0px #0000004d;
  852. border: 0px solid rgba(0,0,0,0.04);
  853. border-radius: 4px;
  854. padding: 8px 0;
  855. }
  856. div.config_bar_menu_item {
  857. cursor: pointer;
  858. padding: 2px 6px;
  859. display: flex;
  860. justify-content: center;
  861. align-items: center;
  862. height: 32px;
  863. color: rgba(0,0,0,0.75);
  864. font-size: 14px;
  865. font-weight: 500;
  866. box-shadow: inset 0px 0px 0px 0px #8bb2d9;
  867. }
  868. div#config_bar_menu_edit:hover {
  869. background-color: #00aeec;
  870. color: white;
  871. }
  872. div#config_bar_menu_delete:hover {
  873. background-color: #FF5722;
  874. color: white;
  875. }
  876. /* 配置页面 */
  877. #config_edit_menu {
  878. z-index: 11000;
  879. width: 450px;
  880. }
  881. `);
  882.  
  883. // 获取cookie
  884. function getCookie(name) {
  885. const cookies = document.cookie.split(";");
  886. for (let i = 0; i < cookies.length; i++) {
  887. const cookie = cookies[i].trim();
  888. const [cookieName, cookieValue] = cookie.split("=");
  889.  
  890. if (cookieName === name) {
  891. return decodeURIComponent(cookieValue);
  892. }
  893. }
  894. return "";
  895. }
  896.  
  897. // 防抖函数
  898. function debounce(callback) {
  899. let timer;
  900. let immediateExecuted = false;
  901. const delay = 500;
  902. return function () {
  903. clearTimeout(timer);
  904. if (!immediateExecuted) { callback.call(this); immediateExecuted = true; }
  905. timer = setTimeout(() => { immediateExecuted = false; }, delay);
  906. };
  907. }
  908.  
  909. // 为元素添加鼠标拖动
  910. function addDraggable(element) {
  911. let isDragging = false;
  912. let initialX, initialY; // 元素的初始位置
  913. let startX, startY, offsetX, offsetY; // 鼠标起始位置,移动偏移量
  914. let isSpecialMouseDown = false; // 选取某些元素时不拖动
  915.  
  916. element.on('mousedown', function (e) {
  917. var elem = $(this);
  918. var elemOffset = elem.offset();
  919. var centerX = elemOffset.left + elem.outerWidth() / 2;
  920. var centerY = elemOffset.top + elem.outerHeight() / 2;
  921. initialX = centerX - window.pageXOffset;
  922. initialY = centerY - window.pageYOffset;
  923.  
  924. isDragging = true;
  925. startX = e.clientX;
  926. startY = e.clientY;
  927.  
  928. isSpecialMouseDown = $(e.target).is('label, p, input, textarea, span');
  929.  
  930. $('body').css('cursor', 'all-scroll');
  931. });
  932.  
  933.  
  934. $(document).on('mousemove', function (e) {
  935. if (!isDragging) return;
  936. // 不执行拖动操作
  937. if ($(e.target).is('label, p, input, textarea, span') || isSpecialMouseDown && !$(e.target).is('input, textarea')) return;
  938. e.preventDefault();
  939. offsetX = e.clientX - startX;
  940. offsetY = e.clientY - startY;
  941. element.css({ top: initialY + offsetY + 'px', left: initialX + offsetX + 'px' });
  942. });
  943.  
  944. $(document).on('mouseup', function () {
  945. isDragging = false;
  946. isSpecialMouseDown = false;
  947. $('body').css('cursor', 'default');
  948. });
  949. }
  950.  
  951.  
  952.  
  953. // 更新检查
  954. (function checkScriptVersion() {
  955. function compareVersions(version1 = "0", version2 = "0") {
  956. const v1Array = String(version1).split(".");
  957. const v2Array = String(version2).split(".");
  958. const minLength = Math.min(v1Array.length, v2Array.length);
  959. let result = 0;
  960. for (let i = 0; i < minLength; i++) {
  961. const curV1 = Number(v1Array[i]);
  962. const curV2 = Number(v2Array[i]);
  963. if (curV1 > curV2) {
  964. result = 1;
  965. break;
  966. } else if (curV1 < curV2) {
  967. result = -1;
  968. break;
  969. }
  970. }
  971. if (result === 0 && v1Array.length !== v2Array.length) {
  972. const v1IsBigger = v1Array.length > v2Array.length;
  973. const maxLenArray = v1IsBigger ? v1Array : v2Array;
  974. for (let i = minLength; i < maxLenArray.length; i++) {
  975. const curVersion = Number(maxLenArray[i]);
  976. if (curVersion > 0) {
  977. v1IsBigger ? result = 1 : result = -1;
  978. break;
  979. }
  980. }
  981. }
  982. return result;
  983. }
  984.  
  985. GM_xmlhttpRequest({
  986. method: "GET",
  987. url: "https://greatest.deepsurf.us/zh-CN/scripts/471106.json",
  988. timeout: 10 * 1e3,
  989. onload: function (response) {
  990. const scriptData = JSON.parse(response.responseText);
  991. const skipUpdate = getCookie("skipUpdate");
  992.  
  993. if (
  994. scriptData.name === GM_info.script.name &&
  995. compareVersions(scriptData.version, GM_info.script.version) === 1 &&
  996. skipUpdate !== "true"
  997. ) {
  998. const styleElement = GM_addStyle(darkenPageStyle);
  999. $("body").append(`
  1000. <div id='update_panel'>
  1001. <h3>${GM_info.script.name}有新版本!</h3>
  1002. <hr>
  1003. <div class='update_panel_menu'>
  1004. <span class ='tip'>版本信息:${GM_info.script.version} ${scriptData.version}</span>
  1005. </div>
  1006. <br>
  1007. <div id="skip_menu">
  1008. <div class="help_tip">
  1009. `+ helpCircleHTML + `
  1010. <div class="tip_text">
  1011. <p><b>更新遇到了问题?</b></p>
  1012. <p>由于 Greasyfork 平台的原因,当新版本刚发布时,点击 Greasyfork 上的更新按钮<u>可能</u>会出现<u>实际更新/安装的却是上一个版本</u>的情况</p>
  1013. <p>通常你只需要稍等几分钟,然后再次前往更新/安装即可</p>
  1014. <p>你也可以<u>点击下方按钮,在本次浏览器会话期间将不再提示更新</u></p>
  1015. <button id='skip_update' class='html2mdButton'>暂不更新</button>
  1016. </div>
  1017. </div>
  1018. <button id='updating'><a target="_blank" href="${scriptData.url}">更新</a></button>
  1019. </div>
  1020. </div>
  1021. `);
  1022.  
  1023. $("#skip_update").click(function () {
  1024. document.cookie = "skipUpdate=true; expires=session; path=/";
  1025. styleElement.remove();
  1026. $("#update_panel").remove();
  1027. });
  1028. }
  1029. }
  1030. });
  1031.  
  1032. })();
  1033.  
  1034.  
  1035. // 汉化替换
  1036. (function () {
  1037. if (!bottomZh_CN) return;
  1038.  
  1039. // 文本节点遍历替换
  1040. $(document).ready(function () {
  1041. function traverseTextNodes(node, rules) {
  1042. if (!node) return;
  1043. if (node.nodeType === Node.TEXT_NODE) {
  1044. rules.forEach(rule => {
  1045. const regex = new RegExp(rule.match, 'g');
  1046. node.textContent = node.textContent.replace(regex, rule.replace);
  1047. });
  1048. } else {
  1049. $(node).contents().each((_, child) => traverseTextNodes(child, rules));
  1050. }
  1051. }
  1052.  
  1053. // 严格
  1054. function strictTraverseTextNodes(node, rules) {
  1055. if (!node) return;
  1056. if (node.nodeType === Node.TEXT_NODE) {
  1057. const nodeText = node.textContent.trim();
  1058. rules.forEach(rule => {
  1059. if (nodeText === rule.match) {
  1060. node.textContent = rule.replace;
  1061. }
  1062. });
  1063. } else {
  1064. $(node).contents().each((_, child) => strictTraverseTextNodes(child, rules));
  1065. }
  1066. }
  1067.  
  1068. // 日语汉化
  1069. if (!isEnglishLanguage) {
  1070. const rules1 = [
  1071. { match: 'コンテスト', replace: '比赛' },
  1072. { match: 'Jobs', replace: '工作' },
  1073. { match: '検定', replace: '考试' },
  1074. { match: 'CareerDesign', replace: '职业规划' },
  1075. { match: 'マイプロフィール', replace: '我的个人资料' },
  1076. { match: '基本設定', replace: '基本设置' },
  1077. { match: 'アイコン設定', replace: '头像设置' },
  1078. { match: 'パスワードの変更', replace: '修改密码' },
  1079. { match: 'お気に入り管理', replace: '收藏夹管理' },
  1080. { match: 'ログアウト', replace: '注销' }
  1081. ];
  1082. traverseTextNodes($('.header-inner'), rules1);
  1083.  
  1084. const rules2 = [
  1085. { match: 'コンテスト', replace: '比赛' },
  1086. { match: '最新コンテスト', replace: '最新比赛' },
  1087. { match: 'ランキング', replace: '排名' },
  1088. { match: 'お知らせ', replace: '公告' },
  1089. { match: 'AtCoderJobs', replace: 'AtCoder工作' },
  1090. { match: '検定', replace: '考试' },
  1091. { match: 'アルゴリズム実技検定についてはこちらから!', replace: '有关算法实际技能考试,请点击此处!' },
  1092. { match: '過去問公開中', replace: '过去问题公开中' },
  1093. ];
  1094. traverseTextNodes($('.a-title_ttl'), rules2);
  1095.  
  1096. const rules3 = [
  1097. { match: '詳細を見る', replace: '查看详情' },
  1098. { match: '求人情報を見る', replace: '查看职位信息' },
  1099. { match: '採用担当者の方へ', replace: '致招聘负责人' },
  1100. { match: '詳細ページ', replace: '详细页面' },
  1101. { match: 'マイページ', replace: '我的页面' },
  1102. { match: 'コンテスト一覧', replace: '比赛列表' },
  1103. { match: 'すべて表示', replace: '显示全部' },
  1104. { match: '殿堂入り', replace: '名人堂' },
  1105. { match: 'お知らせ一覧', replace: '公告列表' },
  1106. ];
  1107. traverseTextNodes($('.a-btnarea'), rules3);
  1108.  
  1109. const rules4 = [
  1110. { match: '解けた!を', replace: '解决了!' },
  1111. { match: '世界に届けたい。', replace: '给全世界。' },
  1112. { match: 'AtCoderは、世界最高峰の競技プログラミングサイトです。', replace: 'AtCoder是世界最高水平的竞技编程网站。' },
  1113. { match: 'リアルタイムのオンラインコンテストで競い合うことや、', replace: '您可以参加实时在线比赛,' },
  1114. { match: '5,000以上の過去問にいつでもチャレンジすることができます。', replace: '随时挑战超过5,000道历年题目。' },
  1115. ];
  1116. traverseTextNodes($('.keyvisual-grid'), rules4);
  1117.  
  1118. const rules5 = [
  1119. { match: 'コンテスト', replace: '比赛' },
  1120. { match: '開催中のコンテスト', replace: '进行中的比赛' },
  1121. { match: '常設中のコンテスト', replace: '长期持续的比赛' },
  1122. { match: '予定されたコンテスト', replace: '计划中的比赛' },
  1123. { match: '終了後のコンテスト(最新 10 件)', replace: '已结束的比赛(最新10场)' },
  1124. { match: '終了後のコンテスト(最新 50 件)', replace: '已结束的比赛(最新10场)' },
  1125. { match: 'ランキング', replace: '排名' },
  1126. { match: 'インフォメーション', replace: '信息' },
  1127. { match: '過去のコンテスト', replace: '过去的比赛' },
  1128. { match: '過去のコンテストを検索', replace: '搜索过去的比赛' },
  1129. ];
  1130. strictTraverseTextNodes($('.panel-title'), rules5);
  1131. strictTraverseTextNodes($('h3'), rules5);
  1132. strictTraverseTextNodes($('.h3'), rules5);
  1133. strictTraverseTextNodes($('h4'), rules5);
  1134.  
  1135. const rules6 = [
  1136. { match: 'ホーム', replace: '主页' },
  1137. { match: 'コンテスト一覧', replace: '比赛列表' },
  1138. { match: 'ランキング', replace: '排名' },
  1139. { match: '便利リンク集', replace: '实用链接' },
  1140. ];
  1141. traverseTextNodes($('.header-sub_nav'), rules6);
  1142. traverseTextNodes($('.h3'), rules6);
  1143.  
  1144. const rules7 = [
  1145. { match: '現在のコンテスト', replace: '现在的比赛' },
  1146. { match: '過去のコンテスト', replace: '过去的比赛' },
  1147. { match: 'Algorithm', replace: '算法' },
  1148. { match: 'Heuristic', replace: '启发式' },
  1149. { match: 'アクティブユーザのみ', replace: '仅活跃用户' },
  1150. { match: '全ユーザ', replace: '所有用户' },
  1151. { match: '新エディタテストコンテスト', replace: '新编辑器测试比赛' },
  1152. { match: '日本語', replace: '日语' },
  1153. { match: 'English', replace: '英语' },
  1154. { match: 'bjxh (Guest)', replace: 'bjxh(游客)' },
  1155. { match: 'マイプロフィール', replace: '个人资料' },
  1156. { match: '基本設定', replace: '基本设置' },
  1157. { match: 'アイコン設定', replace: '头像设置' },
  1158. { match: 'パスワードの変更', replace: '修改密码' },
  1159. { match: 'お気に入り管理', replace: '收藏管理' },
  1160. { match: 'ログアウト', replace: '登出' },
  1161. { match: 'トップ', replace: '首页' },
  1162. { match: '問題', replace: '问题' },
  1163. { match: '質問', replace: '提问' },
  1164. { match: '提出', replace: '提交' },
  1165. { match: '提出結果', replace: '提交结果' },
  1166. { match: 'すべての提出', replace: '所有提交' },
  1167. { match: '自分の提出', replace: '我的提交' },
  1168. { match: '自分の得点状況', replace: '我的得分情况' },
  1169. { match: 'バーチャル順位表', replace: '虚拟排名表' },
  1170. { match: '順位表', replace: '排名表' },
  1171. { match: 'チーム戦排名表', replace: '团队比赛排名表' },
  1172. { match: 'コードテスト', replace: '代码测试' },
  1173. { match: '解説', replace: '题解' },
  1174. { match: 'すべての提交', replace: '所有提交' },
  1175. { match: '自分の提交', replace: '我的提交' },
  1176. { match: 'プロフィール', replace: '个人资料' },
  1177. { match: 'コンテスト成績表', replace: '比赛成绩表' },
  1178. { match: '設定', replace: '设置' },
  1179. { match: 'メールアドレスの更新・認証', replace: '更新/认证电子邮件地址' },
  1180. { match: '收藏管理', replace: '收藏管理' },
  1181. { match: 'ユーザ名照会', replace: '用户名查询' },
  1182. { match: 'ユーザ名の変更', replace: '更改用户名' },
  1183. { match: '退会', replace: '注销' },
  1184. { match: 'その他', replace: '其他' },
  1185. ];
  1186. traverseTextNodes($('.nav'), rules7);
  1187.  
  1188. const rules8 = [
  1189. { match: 'Rated対象', replace: '限定范围' },
  1190. { match: 'ABCクラス', replace: 'ABC类别' },
  1191. { match: '(Rated上限: 1999)', replace: '(Rated上限: 1999)' },
  1192. { match: 'ARCクラス', replace: 'ARC类别' },
  1193. { match: '(Rated上限: 2799)', replace: '(Rated上限: 2799)' },
  1194. { match: 'AGCクラス', replace: 'AGC类别' },
  1195. { match: '(Rated上限なし)', replace: '(无Rated上限)' },
  1196. { match: 'AHCクラス', replace: 'AHC类别' },
  1197. { match: 'カテゴリ', replace: '分类' },
  1198. { match: '全て', replace: '全部' },
  1199. { match: 'AtCoder Typical Contest', replace: 'AtCoder经典比赛' },
  1200. { match: 'PAST過去問', replace: 'PAST历年问题' },
  1201. { match: '非公式コンテスト(unrated)', replace: '非官方比赛(未评级)' },
  1202. { match: 'JOI過去問', replace: 'JOI历年问题' },
  1203. { match: '企業コンテスト決勝', replace: '企业比赛决赛' },
  1204. { match: '企業オープンコンテスト(rated)', replace: '企业公开比赛(已评级)' },
  1205. { match: '企業オープンコンテスト(unrated)', replace: '企业公开比赛(未评级)' },
  1206. { match: '企業ABC', replace: '企业ABC' },
  1207. { match: '企業ARC', replace: '企业ARC' },
  1208. { match: 'ヒューリスティック', replace: '启发式' },
  1209. { match: '企業ヒューリスティック', replace: '企业启发式' },
  1210. { match: '検索', replace: '搜索' },
  1211. { match: 'リセット', replace: '重置' },
  1212. { match: 'コンテスト名', replace: '比赛名称' },
  1213. ];
  1214. strictTraverseTextNodes($('#collapse-search'), rules8);
  1215.  
  1216. const rules9 = [
  1217. { match: 'もっと見る', replace: '查看更多' },
  1218. { match: '自分の得点状況', replace: '我的得分情况' },
  1219. { match: '印刷用問題文', replace: '打印问题集' },
  1220. { match: '記事アーカイブ', replace: '文章存档' },
  1221. { match: '詳細', replace: '详情' },
  1222. { match: 'すべて表示', replace: '显示全部' },
  1223. { match: '殿堂入り', replace: '名人堂' },
  1224. ];
  1225. strictTraverseTextNodes($('.btn-text'), rules9);
  1226.  
  1227. const rules10 = [
  1228. { match: 'ホーム', replace: '主页' },
  1229. { match: 'コンテスト一覧', replace: '比赛列表' },
  1230. { match: 'コンテスト', replace: '比赛' },
  1231. { match: 'ランキング', replace: '排名' },
  1232. { match: '便利リンク集', replace: '实用链接' },
  1233. { match: 'AtCoderJobs', replace: 'AtCoder职位' },
  1234. { match: 'AtCoderJobsトップ', replace: 'AtCoder职位首页' },
  1235. { match: '2024年新卒採用求人一覧', replace: '2024年应届毕业生招聘职位列表' },
  1236. { match: '2025年新卒採用求人一覧', replace: '2025年应届毕业生招聘职位列表' },
  1237. { match: '中途採用求人一覧', replace: '社会人招聘职位列表' },
  1238. { match: 'インターン求人一覧', replace: '实习职位列表' },
  1239. { match: 'アルバイト求人一覧', replace: '兼职职位列表' },
  1240. { match: 'その他求人一覧', replace: '其他职位列表' },
  1241. { match: 'AtCoder社による職業紹介求人一覧', replace: '由AtCoder公司提供的职业介绍职位列表' },
  1242. { match: '採用担当者の方へ', replace: '给招聘负责人的信息' },
  1243. { match: '検定', replace: '认证考试' },
  1244. { match: '検定トップ', replace: '认证考试首页' },
  1245. { match: 'マイページ', replace: '个人主页' },
  1246. { match: 'AtCoderCareerDesign', replace: 'AtCoder职业设计' },
  1247. { match: 'キャリアデザイントップ', replace: '职业设计首页' },
  1248. { match: 'About', replace: '关于' },
  1249. { match: '企業情報', replace: '企业信息' },
  1250. { match: 'よくある質問', replace: '常见问题' },
  1251. { match: 'お問い合わせ', replace: '联系我们' },
  1252. { match: '資料請求', replace: '索取资料' },
  1253. { match: '利用規約', replace: '使用规范' },
  1254. { match: 'ルール', replace: '规则' },
  1255. { match: '用語集', replace: '术语表' },
  1256. { match: 'プライバシーポリシー', replace: '隐私政策' },
  1257. { match: '個人情報保護方針', replace: '个人信息保护政策' },
  1258. { match: 'Copyright Since 2012 (C) AtCoder Inc. All rights reserved.', replace: '版权所有 © 2012年起 AtCoder公司。保留所有权利。' },
  1259. ];
  1260. strictTraverseTextNodes($('#footer'), rules10);
  1261. strictTraverseTextNodes($('.footer'), rules10);
  1262.  
  1263. const rules11 = [
  1264. { match: 'ファイルを開く', replace: '打开文件' },
  1265. { match: 'カスタマイズ', replace: '自定义' },
  1266. { match: 'エディタ切り替え', replace: '切换编辑器' },
  1267. { match: '高さ自動調節', replace: '自动调整高度' },
  1268. ];
  1269. traverseTextNodes($('.editor-buttons'), rules11);
  1270.  
  1271. const rules12 = [
  1272. { match: '問題', replace: '问题' },
  1273. { match: '言語', replace: '语言' },
  1274. { match: 'ソースコード', replace: '源代码' },
  1275. { match: '標準入力', replace: '标注输入' },
  1276. { match: '標準出力', replace: '标准输出' },
  1277. { match: '標準エラー出力', replace: '标准错误输出' },
  1278. ];
  1279. traverseTextNodes($('.control-label'), rules12);
  1280.  
  1281. const rules13 = [
  1282. { match: 'トップ', replace: '首页' },
  1283. { match: '問題', replace: '问题' },
  1284. { match: '質問', replace: '提问' },
  1285. { match: '提出', replace: '提交' },
  1286. { match: '提出結果', replace: '提交结果' },
  1287. { match: 'すべての提交', replace: '所有提交' },
  1288. { match: '自分の提交', replace: '我的提交' },
  1289. { match: '自分の得点状況', replace: '我的得分情况' },
  1290. { match: 'バーチャル順位表', replace: '虚拟排名表' },
  1291. { match: '順位表', replace: '排名表' },
  1292. { match: 'コードテスト', replace: '代码测试' },
  1293. { match: '解説', replace: '题解' },
  1294. ];
  1295. traverseTextNodes($('.h2'), rules13);
  1296. traverseTextNodes($('h2'), rules13);
  1297.  
  1298. const rules14 = [
  1299. { match: 'トップ', replace: '首页' },
  1300. { match: '問題', replace: '问题' },
  1301. { match: '質問', replace: '提问' },
  1302. { match: '提出', replace: '提交' },
  1303. { match: '提出結果', replace: '提交结果' },
  1304. { match: 'すべての提交', replace: '所有提交' },
  1305. { match: '自分の提交', replace: '我的提交' },
  1306. { match: '自分の得点状況', replace: '我的得分情况' },
  1307. { match: 'バーチャル順位表', replace: '虚拟排名表' },
  1308. { match: '順位表', replace: '排名表' },
  1309. { match: 'コードテスト', replace: '代码测试' },
  1310. { match: '解説', replace: '题解' },
  1311. ];
  1312. traverseTextNodes($('.panel-heading'), rules14);
  1313.  
  1314. const rules15 = [
  1315. { match: '予定', replace: '即将举行' },
  1316. { match: '終了', replace: '已结束' },
  1317. ];
  1318. traverseTextNodes($('.status'), rules15);
  1319.  
  1320. const rules16 = [
  1321. { match: 'コンテスト名', replace: '比赛名称' },
  1322. { match: 'Rated対象', replace: '计分对象' },
  1323. { match: '時間', replace: '时长' },
  1324. { match: '開始時刻', replace: '开始时间' },
  1325. ];
  1326. traverseTextNodes($('th.text-center'), rules16);
  1327.  
  1328. const rules17 = [
  1329. { match: 'コンテスト名', replace: '比赛名称' },
  1330. { match: '開始時刻', replace: '开始时间' },
  1331. { match: 'ユーザ', replace: '用户' },
  1332. ];
  1333. traverseTextNodes($('.table-responsive tr th'), rules17);
  1334.  
  1335. const rules18 = [
  1336. { match: 'バーチャル参加', replace: '虚拟参与' },
  1337. ];
  1338. traverseTextNodes($('.btn-default'), rules18);
  1339.  
  1340. const rules19 = [
  1341. { match: '問題名', replace: '问题名称' },
  1342. { match: '実行時間制限', replace: '执行时间限制' },
  1343. { match: 'メモリ制限', replace: '内存限制' },
  1344. ];
  1345. traverseTextNodes($('.table-bordered tr th'), rules19);
  1346.  
  1347. const rules20 = [
  1348. { match: 'ページトップ', replace: '返回顶部' },
  1349. ];
  1350. traverseTextNodes($('#scroll-page-top'), rules20);
  1351.  
  1352. const rules21 = [
  1353. { match: 'AtCoderホームへ戻る', replace: '返回 AtCoder 主页' },
  1354. ];
  1355. traverseTextNodes($('.back-to-home'), rules21);
  1356.  
  1357. return;
  1358. }
  1359.  
  1360. // 英语汉化
  1361. const rules1 = [
  1362. { match: 'Present Contests', replace: '目前的比赛' },
  1363. { match: 'Past Contests', replace: '过去的比赛' },
  1364. { match: 'Top', replace: '首页' },
  1365. { match: 'Tasks', replace: '问题集' },
  1366. { match: 'Clarifications', replace: '问题答疑' },
  1367. { match: 'Submit', replace: '提交' },
  1368. { match: 'Results', replace: '结果' },
  1369. { match: 'All Submissions', replace: '所有提交' },
  1370. { match: 'My Submissions', replace: '我的提交' },
  1371. { match: 'My Score', replace: '我的得分' },
  1372. { match: 'Virtual Standings', replace: '虚拟排名' },
  1373. { match: 'Standings', replace: '排名' },
  1374. { match: 'Custom Test', replace: '自定义测试' },
  1375. { match: 'Editorial', replace: '题解' },
  1376. { match: 'Discuss', replace: '讨论' },
  1377. { match: 'Algorithm', replace: '算法' },
  1378. { match: 'Heuristic', replace: '启发式' },
  1379. { match: 'Active Users', replace: '活跃用户' },
  1380. { match: 'All Users', replace: '所有用户' },
  1381. { match: 'Profile', replace: '个人资料' },
  1382. { match: 'Competition History', replace: '比赛记录' },
  1383. { match: 'General Settings', replace: '常规设置' },
  1384. { match: 'Settings', replace: '设置' },
  1385. { match: 'Change/Verify Email address', replace: '更改/验证电子邮件地址' },
  1386. { match: 'Remind Username', replace: '提醒用户名' },
  1387. { match: 'Change Username', replace: '更改用户名' },
  1388. { match: 'Delete Account', replace: '删除账户' },
  1389. { match: 'Change Photo', replace: '更改头像' },
  1390. { match: 'Change Password', replace: '更改密码' },
  1391. { match: 'Manage Fav', replace: '管理收藏' },
  1392. { match: 'Other', replace: '其他' },
  1393. { match: 'Remind Username', replace: '提醒用户名' },
  1394. { match: 'Change Username', replace: '更改用户名' },
  1395. { match: 'Delete Account', replace: '删除账户' }
  1396. ];
  1397. traverseTextNodes($('.nav'), rules1);
  1398.  
  1399. const rules2 = [
  1400. { match: 'My Profile', replace: '个人资料' },
  1401. { match: 'General Settings', replace: '常规设置' },
  1402. { match: 'Change Photo', replace: '更改照片' },
  1403. { match: 'Change Password', replace: '更改密码' },
  1404. { match: 'Manage Fav', replace: '管理收藏' },
  1405. { match: 'Sign Out', replace: '退出登录' }
  1406. ];
  1407. traverseTextNodes($('.dropdown-menu'), rules2);
  1408.  
  1409. const rules3 = [
  1410. { match: 'Search in Archive', replace: '搜索存档' },
  1411. { match: 'Permanent Contests', replace: '长期持续的比赛' },
  1412. { match: 'Upcoming Contests', replace: '即将举行的比赛' },
  1413. { match: 'Recent Contests', replace: '最近的比赛' },
  1414. { match: 'Ranking', replace: '排行' },
  1415. { match: 'Contest Archive', replace: '比赛档案' },
  1416. { match: 'Information', replace: '信息' },
  1417. { match: 'About the situation where it is difficult to access the contest site', replace: '关于难以访问比赛网站的情况' },
  1418. ];
  1419. traverseTextNodes($('.panel-title'), rules3);
  1420. traverseTextNodes($('.h3'), rules3);
  1421. strictTraverseTextNodes($('h3'), rules3);
  1422.  
  1423. const rules4 = [
  1424. { match: 'Rated Range', replace: '限定范围' },
  1425. { match: 'Category', replace: '类别' },
  1426. { match: 'Search', replace: '搜索' }
  1427. ];
  1428. traverseTextNodes($('.filter-body-heading'), rules4);
  1429.  
  1430. const rules5 = [
  1431. { match: 'Current Password', replace: '当前密码' },
  1432. { match: 'New Password', replace: '新密码' },
  1433. { match: 'Confirm Password', replace: '确认密码' },
  1434. { match: 'Update', replace: '更新' },
  1435. { match: 'Contest Name', replace: '比赛名称' },
  1436. { match: 'Username', replace: '用户名' },
  1437. { match: 'Password', replace: '密码' },
  1438. { match: 'Sign In', replace: '登录' },
  1439. { match: 'Sign Up', replace: '注册' },
  1440. { match: 'Nickname', replace: '昵称' },
  1441. { match: 'Country/Region', replace: '国家/地区' },
  1442. { match: 'Birth Year', replace: '出生年份' },
  1443. { match: 'Affiliation', replace: '机构' },
  1444. { match: 'Email Notifications', replace: '邮件通知' },
  1445. { match: 'New Email address', replace: '新电子邮件地址' },
  1446. { match: 'Request Email address verify', replace: '请求电子邮件地址验证' },
  1447. { match: 'I agree.', replace: '我同意。' },
  1448. { match: 'Do you live in Japan?', replace: '您是否居住在日本?' },
  1449. { match: 'Family Name', replace: '姓氏' },
  1450. { match: 'First Name', replace: '名字' },
  1451. { match: 'Category', replace: '分类' },
  1452. { match: 'College Students (Master or Doctor cource)', replace: '大学生(硕士或博士课程)' },
  1453. { match: 'College Students', replace: '大学生' },
  1454. { match: 'Technical college/Vocational school/Short-term university', replace: '技术学院/职业学校/短期大学' },
  1455. { match: 'High school', replace: '高中' },
  1456. { match: 'Junior high school', replace: '初中' },
  1457. { match: 'Office worker', replace: '上班族' },
  1458. { match: 'Other', replace: '其他' },
  1459. { match: 'Organization Name \\(Company Name or School Name\\)', replace: '组织名称(公司名称或学校名称)' },
  1460. { match: 'Depertment \\(For Students\\)', replace: '部门(适用于学生)' },
  1461. { match: 'Do you have any intention or plan to find a job or change jobs in 2023 or 2024?', replace: '您是否有意向或计划在2023年或2024年找工作或换工作?' },
  1462. { match: 'Graduation Schedule', replace: '毕业时间表' },
  1463. { match: "I'm already employed.", replace: '我已经就业了。' },
  1464. { match: 'Later years', replace: '以后的几年' },
  1465. { match: 'I am interested in going into the digital area of Toyota Motor Corporation\'s operations.', replace: '我对加入丰田汽车公司的数字领域感兴趣。' },
  1466. { match: 'Toyota is currently actively recruiting engineers. Would you like to be considered?', replace: '丰田目前正在积极招聘工程师。您有兴趣被考虑吗?' },
  1467. { match: 'I\'d like to talk to you first.', replace: '我想先和您交谈。' },
  1468. { match: 'Department name', replace: '部门名称' },
  1469. { match: 'What kind of work do you currently do?', replace: '您目前从事什么样的工作?' },
  1470. { match: 'How can the Algorithms Group of the Digital Transformation Office help\\?', replace: '数字转型办公室的算法组可以如何帮助您?' }
  1471. ];
  1472. traverseTextNodes($('.form-group'), rules5);
  1473.  
  1474. const rules6 = [
  1475. { match: 'Unofficial(unrated)', replace: '非官方(无评级)' },
  1476. { match: 'Sponsored Parallel(rated)', replace: '赞助平行(有评级)' },
  1477. { match: 'Sponsored Parallel(unrated)', replace: '赞助平行(无评级)' },
  1478. { match: 'Sponsored Heuristic Contest', replace: '启发式赞助比赛' },
  1479. { match: 'All', replace: '全部' },
  1480. { match: 'AtCoder Typical Contest', replace: 'AtCoder 经典比赛' },
  1481. { match: 'PAST Archive', replace: 'PAST 比赛归档' },
  1482. { match: 'JOI Archive', replace: 'JOI 比赛归档' },
  1483. { match: 'Sponsored Tournament', replace: '赞助比赛' },
  1484. { match: 'Sponsored ABC', replace: '赞助 ABC' },
  1485. { match: 'Sponsored ARC', replace: '赞助 ARC' },
  1486. { match: 'Heuristic Contest', replace: '启发式比赛' }
  1487. ];
  1488. strictTraverseTextNodes($('#category-btn-group'), rules6);
  1489.  
  1490. const rules7 = [
  1491. { match: 'Task', replace: '任务' },
  1492. { match: 'Language', replace: '语言' },
  1493. { match: 'Source Code', replace: '源代码' },
  1494. { match: 'Standard Input', replace: '标准输入' },
  1495. { match: 'Standard Output', replace: '标准输出' },
  1496. { match: 'Standard Error', replace: '标准错误' },
  1497. ];
  1498. traverseTextNodes($('.control-label'), rules7);
  1499.  
  1500. const rules8 = [
  1501. { match: 'Permanent Contests', replace: '永久比赛' },
  1502. { match: 'Upcoming Contests', replace: '即将举行的比赛' },
  1503. { match: 'Recent Contests', replace: '最近的比赛' }
  1504. ];
  1505. traverseTextNodes($('h4'), rules8);
  1506.  
  1507. const rules9 = [
  1508. { match: 'Open File', replace: '打开文件' },
  1509. { match: 'Toggle Editor', replace: '切换编辑器' },
  1510. { match: 'Auto Height', replace: '自动调整高度' }
  1511. ];
  1512. traverseTextNodes($('.editor-buttons'), rules9);
  1513.  
  1514. const rules10 = [
  1515. { match: 'Register', replace: '报名' },
  1516. { match: 'Virtual Participation', replace: '虚拟参加' }
  1517. ];
  1518. traverseTextNodes($('.btn'), rules10);
  1519.  
  1520. const rules11 = [
  1521. { match: 'Home', replace: '主页' },
  1522. { match: 'Contest', replace: '比赛' },
  1523. { match: 'Ranking', replace: '排名' },
  1524. { match: 'Sign Up', replace: '注册' },
  1525. { match: 'Sign In', replace: '登录' },
  1526. ];
  1527. strictTraverseTextNodes($('#navbar-collapse'), rules11);
  1528. });
  1529. })();
  1530.  
  1531. // 设置面板
  1532. $(document).ready(function () {
  1533. var htmlContent = "<button class='html2mdButton AtBetter_setting'>AtcoderBetter设置</button>";
  1534. if (isEnglishLanguage) {
  1535. $('#navbar-collapse > ul:nth-child(2) > li:last-child').after("<li class='dropdown'>" + htmlContent + "</li>");
  1536. } else {
  1537. $('.header-mypage').after(htmlContent);
  1538. }
  1539. });
  1540.  
  1541. // 配置管理函数
  1542. function setupConfigManagement(element, tempConfig, structure, configHTML, checkable) {
  1543. let counter = 0;
  1544. createControlBar();
  1545. createContextMenu();
  1546.  
  1547. // 键值对校验
  1548. function valiKeyValue(value) {
  1549. const keyValuePairs = value.split('\n');
  1550. const regex = /^[a-zA-Z0-9_-]+\s*:\s*[a-zA-Z0-9_-]+$/;
  1551. for (let i = 0; i < keyValuePairs.length; i++) {
  1552. if (!regex.test(keyValuePairs[i])) {
  1553. return false;
  1554. }
  1555. }
  1556. return true;
  1557. }
  1558.  
  1559. // 新增数据
  1560. function onAdd() {
  1561. const styleElement = createWindow();
  1562.  
  1563. const settingMenu = $("#config_edit_menu");
  1564. settingMenu.on("click", "#save", () => {
  1565. const config = {};
  1566. let allFieldsValid = true;
  1567. for (const key in structure) {
  1568. let value = $(key).val();
  1569. if (value || $(key).attr('require') === 'false') {
  1570. config[structure[key]] = $(key).val();
  1571. $(key).removeClass('is_null');
  1572. } else {
  1573. $(key).addClass('is_null');
  1574. allFieldsValid = false;
  1575. }
  1576. }
  1577.  
  1578. // 校验提示
  1579. for (let i = 0, len = checkable.length; i < len; i++) {
  1580. let value = $(checkable[i]).val();
  1581. if (value && !valiKeyValue(value)) {
  1582. if (!$(checkable[i]).prev('span.text-error').length) {
  1583. $(checkable[i]).before('<span class="text-error" style="color: red;">格式不符或存在非法字符</span>');
  1584. }
  1585. allFieldsValid = false;
  1586. } else {
  1587. $(checkable[i]).prev('span.text-error').remove();
  1588. }
  1589. }
  1590.  
  1591. if (!allFieldsValid) return;
  1592. tempConfig.configurations.push(config);
  1593.  
  1594. const list = $("#config_bar_ul");
  1595. createListItemElement(config[structure['#note']]).insertBefore($('#add_button'));
  1596.  
  1597. settingMenu.remove();
  1598. $(styleElement).remove();
  1599. });
  1600.  
  1601. settingMenu.on("click", ".btn-close", () => {
  1602. settingMenu.remove();
  1603. $(styleElement).remove();
  1604. });
  1605. }
  1606.  
  1607. // 编辑数据
  1608. function onEdit() {
  1609. const menu = $("#config_bar_menu");
  1610. menu.css({ display: "none" });
  1611.  
  1612. const list = $("#config_bar_ul");
  1613. const index = Array.from(list.children()).indexOf(this);
  1614.  
  1615. const styleElement = createWindow();
  1616.  
  1617. const settingMenu = $("#config_edit_menu");
  1618. const configAtIndex = tempConfig.configurations[index];
  1619.  
  1620. if (configAtIndex) {
  1621. for (const key in structure) {
  1622. $(key).val(configAtIndex[structure[key]]);
  1623. }
  1624. }
  1625.  
  1626. settingMenu.on("click", "#save", () => {
  1627. const config = {};
  1628. let allFieldsValid = true;
  1629. for (const key in structure) {
  1630. let value = $(key).val();
  1631. if (value || $(key).attr('require') === 'false') {
  1632. config[structure[key]] = $(key).val();
  1633. $(key).removeClass('is_null');
  1634. } else {
  1635. $(key).addClass('is_null');
  1636. allFieldsValid = false;
  1637. }
  1638. }
  1639. // 校验提示
  1640. for (let i = 0, len = checkable.length; i < len; i++) {
  1641. let value = $(checkable[i]).val();
  1642. if (value && !valiKeyValue(value)) {
  1643. if (!$(checkable[i]).prev('span.text-error').length) {
  1644. $(checkable[i]).before('<span class="text-error" style="color: red;">格式不符或存在非法字符</span>');
  1645. }
  1646. allFieldsValid = false;
  1647. } else {
  1648. $(checkable[i]).prev('span.text-error').remove();
  1649. }
  1650. }
  1651.  
  1652. if (!allFieldsValid) return;
  1653. tempConfig.configurations[index] = config;
  1654.  
  1655. settingMenu.remove();
  1656. $(styleElement).remove();
  1657. menu.css({ display: "none" });
  1658.  
  1659. list.children().eq(index).find("label").text(config.note);
  1660. });
  1661.  
  1662. // 关闭按钮
  1663. settingMenu.on("click", ".btn-close", () => {
  1664. settingMenu.remove();
  1665. $(styleElement).remove();
  1666. });
  1667. }
  1668.  
  1669. // 删除数据
  1670. function onDelete() {
  1671. const menu = $("#config_bar_menu");
  1672. menu.css({ display: "none" });
  1673.  
  1674. const list = $("#config_bar_ul");
  1675. const index = Array.from(list.children()).indexOf(this);
  1676.  
  1677. tempConfig.configurations.splice(index, 1);
  1678.  
  1679. list.children().eq(index).remove();
  1680. }
  1681.  
  1682. // 创建编辑窗口
  1683. function createWindow() {
  1684. const styleElement = GM_addStyle(darkenPageStyle2);
  1685. $("body").append(configHTML);
  1686. addDraggable($('#config_edit_menu'));
  1687. return styleElement;
  1688. }
  1689.  
  1690. // 创建控制面板
  1691. function createControlBar() {
  1692. $(element).append(`
  1693. <div id='configControlTip' style='color:red;'></div>
  1694. <div class='config_bar'>
  1695. <div class='config_bar_list' id='config_bar_list'>
  1696. <ul class='config_bar_ul' id='config_bar_ul'></ul>
  1697. </div>
  1698. </div>
  1699. `);
  1700. }
  1701.  
  1702. // 创建右键菜单
  1703. function createContextMenu() {
  1704. const menu = $("<div id='config_bar_menu' style='display: none;'></div>");
  1705. menu.html(`
  1706. <div class='config_bar_menu_item' id='config_bar_menu_edit'>修改</div>
  1707. <div class='config_bar_menu_item' id='config_bar_menu_delete'>删除</div>
  1708. `);
  1709. $("body").append(menu);
  1710. }
  1711.  
  1712. // 创建新的li元素
  1713. function createListItemElement(text) {
  1714. const li = $("<li></li>");
  1715. const radio = $("<input type='radio' name='config_item'></input>").appendTo(li);
  1716. radio.attr("value", counter).attr("id", counter++);
  1717. const label = $("<label class='config_bar_ul_li_text'></label>").text(text).attr("for", radio.attr("value")).appendTo(li);
  1718.  
  1719. // 添加右键菜单
  1720. li.on("contextmenu", function (event) {
  1721. event.preventDefault();
  1722. const menu = $("#config_bar_menu");
  1723. menu.css({ display: "block", left: event.pageX, top: event.pageY });
  1724.  
  1725. const deleteItem = $("#config_bar_menu_delete");
  1726. const editItem = $("#config_bar_menu_edit");
  1727.  
  1728. // 移除旧事件
  1729. deleteItem.off("click");
  1730. editItem.off("click");
  1731.  
  1732. deleteItem.on("click", onDelete.bind(this));
  1733. editItem.on("click", onEdit.bind(this));
  1734.  
  1735. $(document).one("click", (event) => {
  1736. if (!menu.get(0).contains(event.target)) {
  1737. menu.css({ display: "none" });
  1738. deleteItem.off("click", onDelete);
  1739. editItem.off("click", onEdit);
  1740. }
  1741. });
  1742. });
  1743.  
  1744.  
  1745. return li;
  1746. }
  1747.  
  1748. // 渲染列表
  1749. function renderList() {
  1750. const listContainer = $("#config_bar_list");
  1751. const list = $("#config_bar_ul");
  1752. list.empty();
  1753. tempConfig.configurations.forEach((item) => {
  1754. list.append(createListItemElement(item[structure['#note']]));
  1755. });
  1756.  
  1757. list.append(`
  1758. <li id='add_button'>
  1759. <span>+ 添加</span>
  1760. </li>
  1761. `);
  1762. const addItem = $('#add_button');
  1763. addItem.on("click", onAdd);
  1764. };
  1765.  
  1766. renderList();
  1767. return tempConfig;
  1768. }
  1769.  
  1770. const AtBetterSettingMenuHTML = `
  1771. <div class='AtBetter_setting_menu' id='AtBetter_setting_menu'>
  1772. <div class="tool-box">
  1773. <button class="btn-close">×</button>
  1774. </div>
  1775. <h4>基本设置</h4>
  1776. <hr>
  1777. <div class='AtBetter_setting_list'>
  1778. <label for="bottomZh_CN">界面汉化</label>
  1779. <input type="checkbox" id="bottomZh_CN" name="bottomZh_CN">
  1780. </div>
  1781. <div class='AtBetter_setting_list'>
  1782. <label for="showLoading">显示加载信息</label>
  1783. <div class="help_tip">
  1784. `+ helpCircleHTML + `
  1785. <div class="tip_text">
  1786. <p>当你开启 显示加载信息 时,每次加载页面时会在上方显示加载信息提示:“Atcoder Better! —— xxx”</p>
  1787. <p>这用于了解脚本当前的工作情况,<strong>如果你不想看到,可以选择关闭</strong></p>
  1788. <p><u>需要说明的是,如果你需要反馈脚本的任何加载问题,请开启该选项后再截图,以便于分析问题</u></p>
  1789. </div>
  1790. </div>
  1791. <input type="checkbox" id="showLoading" name="showLoading">
  1792. </div>
  1793. <div class='AtBetter_setting_list'>
  1794. <label for="hoverTargetAreaDisplay">显示目标区域范围</label>
  1795. <div class="help_tip">
  1796. `+ helpCircleHTML + `
  1797. <div class="tip_text">
  1798. <p>开启后当鼠标悬浮在 MD视图/复制/翻译 按钮上时,会显示其目标区域的范围</p>
  1799. </div>
  1800. </div>
  1801. <input type="checkbox" id="hoverTargetAreaDisplay" name="hoverTargetAreaDisplay">
  1802. </div>
  1803. <div class='AtBetter_setting_list'>
  1804. <label for="enableSegmentedTranslation">分段翻译</label>
  1805. <div class="help_tip">
  1806. `+ helpCircleHTML + `
  1807. <div class="tip_text">
  1808. <p>分段翻译会对区域内的每一个&#60;&#112;&#47;&#62;和&#60;&#105;&#47;&#62;标签依次进行翻译,</p>
  1809. <p>这通常在翻译<strong>长篇博客</strong>或者<strong>超长的题目</strong>时很有用。</p>
  1810. <p><u>注意:开启分段翻译会产生如下问题:</u></p>
  1811. <p>- 使得翻译接口无法知晓整个文本的上下文信息,会降低翻译质量。</p>
  1812. <p>- 会有<strong>部分内容不会被翻译</strong>,因为它们不是&#60;&#112;&#47;&#62;或&#60;&#105;&#47;&#62;标签</p>
  1813. </div>
  1814. </div>
  1815. <input type="checkbox" id="enableSegmentedTranslation" name="enableSegmentedTranslation">
  1816. </div>
  1817. <div class='AtBetter_setting_list'>
  1818. <label for="showJumpToLuogu">显示跳转到洛谷</label>
  1819. <div class="help_tip">
  1820. `+ helpCircleHTML + `
  1821. <div class="tip_text">
  1822. <p>洛谷OJ上收录了Atcoder的部分题目,一些题目有翻译和题解</p>
  1823. <p>开启显示后,如果当前题目被收录,则会在题目的右上角显示洛谷标志,</p>
  1824. <p>点击即可一键跳转到该题洛谷的对应页面。</strong></p>
  1825. </div>
  1826. </div>
  1827. <input type="checkbox" id="showJumpToLuogu" name="showJumpToLuogu">
  1828. </div>
  1829. <div class='AtBetter_setting_list'>
  1830. <label for="loaded"><span style="font-size: 14px;">兼容选项-不等待页面资源加载</span></label>
  1831. <div class="help_tip">
  1832. `+ helpCircleHTML + `
  1833. <div class="tip_text">
  1834. <p>为了防止在页面资源未加载完成前(主要是各种js)执行脚本产生意外的错误,脚本默认会等待 window.onload 事件</p>
  1835. <p>如果您的页面上方的加载信息始终停留在:“等待页面资源加载”,</p>
  1836. <p><u>您首先应该确认是否是网络问题,</u></p>
  1837. <p>如果页面实际已经加载完成,那这可能是由于 window.onload 事件在您的浏览器中触发过早(早于document.ready),</p>
  1838. <p>您可以尝试开启该选项来不再等待 window.onload 事件</p>
  1839. <p><u>注意:如果没有上述问题,请不要开启该选项</u></p>
  1840. </div>
  1841. </div>
  1842. <input type="checkbox" id="loaded" name="loaded">
  1843. </div>
  1844. <h4>翻译设置</h4>
  1845. <hr>
  1846. <label>
  1847. <input type='radio' name='translation' value='deepl'>
  1848. <span class='AtBetter_setting_menu_label_text'>deepl翻译</span>
  1849. </label>
  1850. <label>
  1851. <input type='radio' name='translation' value='youdao'>
  1852. <span class='AtBetter_setting_menu_label_text'>有道翻译</span>
  1853. </label>
  1854. <label>
  1855. <input type='radio' name='translation' value='google'>
  1856. <span class='AtBetter_setting_menu_label_text'>Google翻译</span>
  1857. </label>
  1858. <label>
  1859. <input type='radio' name='translation' value='openai'>
  1860. <span class='AtBetter_setting_menu_label_text'>使用ChatGPT翻译(API)
  1861. <div class="help_tip">
  1862. `+ helpCircleHTML + `
  1863. <div class="tip_text">
  1864. <p><b>请在下方选定你想使用的配置信息</b></p>
  1865. <p>脚本的所有请求均在本地完成</p>
  1866. </div>
  1867. </div>
  1868. </span>
  1869. </label>
  1870. <div class='AtBetter_setting_menu_input' id='openai' style='display: none;'>
  1871. <div id="chatgpt-config"></div>
  1872. </div>
  1873. <button id='save'>保存</button>
  1874. </div>
  1875. `;
  1876.  
  1877. const chatgptConfigEditHTML = `
  1878. <div class='AtBetter_setting_menu' id='config_edit_menu'>
  1879. <div class="tool-box">
  1880. <button class="btn-close">×</button>
  1881. </div>
  1882. <h4>配置</h4>
  1883. <h5>基本</h5>
  1884. <hr>
  1885. <label for='note'>
  1886. <span class="input_label">备注:</span>
  1887. </label>
  1888. <input type='text' id='note' class='no_default' placeholder='请为该配置取一个备注名' require = true>
  1889. <label for='openai_model'>
  1890. <div style="display: flex;align-items: center;">
  1891. <span class="input_label">模型:</span>
  1892. <div class="help_tip">
  1893. `+ helpCircleHTML + `
  1894. <div class="tip_text">
  1895. <p>留空则默认为:gpt-3.5-turbo</p>
  1896. <p>模型列表请查阅<a target="_blank" href="https://platform.openai.com/docs/models">OpenAI官方文档</a></p>
  1897. <p><strong>此外,如果您使用的是服务商提供的代理API,请确认服务商是否支持对应模型</strong></p>
  1898. </div>
  1899. </div>
  1900. </div>
  1901. </label>
  1902. <input type='text' id='openai_model' placeholder='gpt-3.5-turbo' require = false>
  1903. <label for='openai_key'>
  1904. <div style="display: flex;align-items: center;">
  1905. <span class="input_label">KEY:</span>
  1906. <div class="help_tip">
  1907. `+ helpCircleHTML + `
  1908. <div class="tip_text">
  1909. <p>您需要输入自己的OpenAI key,<a target="_blank" href="https://platform.openai.com/account/usage">官网</a></p>
  1910. <p><b>如果您使用的是服务商提供的代理API,则应该填写服务商提供的 Key</b></p>
  1911. </div>
  1912. </div>
  1913. </div>
  1914. </label>
  1915. <input type='text' id='openai_key' class='no_default' placeholder='请输入KEY' require = true>
  1916. <label for='openai_proxy'>
  1917. <div style="display: flex;align-items: center;">
  1918. <span class="input_label">Proxy API:</span>
  1919. <div class="help_tip">
  1920. `+ helpCircleHTML + `
  1921. <div class="tip_text">
  1922. <p>留空则默认为OpenAI官方API</p>
  1923. <p>您也可以填写指定的API来代理访问OpenAIAPI,</p>
  1924. <p>如果您使用的是服务商提供的代理APIKEY,则这里应该填写其提供的<strong>完整</strong>API地址,详请阅读脚本说明</p>
  1925. <p><strong>由于您指定了自定义的APITampermonkey会对您的跨域请求进行警告,您需要自行授权</strong></p>
  1926. </div>
  1927. </div>
  1928. </div>
  1929. </label>
  1930. <input type='text' id='openai_proxy' placeholder='https://api.openai.com/v1/chat/completions' require = false>
  1931. <h5>高级</h5>
  1932. <hr>
  1933. <label for='_header'>
  1934. <div style="display: flex;align-items: center;">
  1935. <span class="input_label">自定义header</span>
  1936. <div class="help_tip">
  1937. `+ helpCircleHTML + `
  1938. <div class="tip_text">
  1939. <p>格式样例:</p>
  1940. <div style="border: 1px solid #795548; padding: 10px;">
  1941. <p>name1 : 123<br>name2 : cccc</p>
  1942. </div>
  1943. </div>
  1944. </div>
  1945. </div>
  1946. </label>
  1947. <textarea id="_header" placeholder='(选填)您可以在这里填写向请求header中额外添加的键值对' require = false></textarea>
  1948. <label for='_data'>
  1949. <div style="display: flex;align-items: center;">
  1950. <span class="input_label">自定义data</span>
  1951. <div class="help_tip">
  1952. `+ helpCircleHTML + `
  1953. <div class="tip_text">
  1954. <p>格式样例:</p>
  1955. <div style="border: 1px solid #795548; padding: 10px;">
  1956. <p>name1 : 123<br>name2 : cccc</p>
  1957. </div>
  1958. </div>
  1959. </div>
  1960. </div>
  1961. </label>
  1962. <textarea id="_data" placeholder='(选填)您可以在这里填写向请求data中额外添加的键值对' require = false></textarea>
  1963. <button id='save'>保存</button>
  1964. </div>
  1965. `;
  1966.  
  1967. $(document).ready(function () {
  1968. const $settingBtns = $(".AtBetter_setting");
  1969. $settingBtns.click(() => {
  1970. const styleElement = GM_addStyle(darkenPageStyle);
  1971. $settingBtns.prop("disabled", true).addClass("open");
  1972. $("body").append(AtBetterSettingMenuHTML);
  1973.  
  1974. // 窗口初始化
  1975. addDraggable($('#AtBetter_setting_menu'));
  1976. const chatgptStructure = {
  1977. '#note': 'note',
  1978. '#openai_model': 'model',
  1979. '#openai_key': 'key',
  1980. '#openai_proxy': 'proxy',
  1981. '#_header': '_header',
  1982. '#_data': '_data',
  1983. }
  1984. const checkable = [
  1985. '#_header',
  1986. '#_data',
  1987. ]
  1988.  
  1989. // 缓存配置信息
  1990. let tempConfig = GM_getValue('chatgpt-config');
  1991. tempConfig = setupConfigManagement('#chatgpt-config', tempConfig, chatgptStructure, chatgptConfigEditHTML, checkable);
  1992.  
  1993. // 状态切换
  1994. $("#bottomZh_CN").prop("checked", GM_getValue("bottomZh_CN") === true);
  1995. $("#showLoading").prop("checked", GM_getValue("showLoading") === true);
  1996. $("#enableSegmentedTranslation").prop("checked", GM_getValue("enableSegmentedTranslation") === true);
  1997. $("#showJumpToLuogu").prop("checked", GM_getValue("showJumpToLuogu") === true);
  1998. $("#loaded").prop("checked", GM_getValue("loaded") === true);
  1999. $("#hoverTargetAreaDisplay").prop("checked", GM_getValue("hoverTargetAreaDisplay") === true);
  2000. $("input[name='translation'][value='" + translation + "']").prop("checked", true);
  2001. $("input[name='translation']").css("color", "gray");
  2002. if (translation == "openai") {
  2003. $("#openai").show();
  2004. if (tempConfig) {
  2005. $("input[name='config_item'][value='" + tempConfig.choice + "']").prop("checked", true);
  2006. }
  2007. }
  2008.  
  2009. // 翻译选择情况监听
  2010. $("input[name='translation']").change(function () {
  2011. var selected = $(this).val(); // 获取当前选中的值
  2012. if (selected === "openai") {
  2013. $("#openai").show();
  2014. if (tempConfig) {
  2015. $("input[name='config_item'][value='" + tempConfig.choice + "']").prop("checked", true);
  2016. }
  2017. } else {
  2018. $("#openai").hide();
  2019. }
  2020. });
  2021. // 配置选择情况监听
  2022. $("input[name='config_item']").change(function () {
  2023. var selected = $(this).val(); // 获取当前选中的值
  2024. tempConfig.choice = selected;
  2025. });
  2026.  
  2027. const $settingMenu = $(".AtBetter_setting_menu");
  2028.  
  2029. $("#save").click(debounce(function () {
  2030. const settings = {
  2031. bottomZh_CN: $("#bottomZh_CN").prop("checked"),
  2032. showLoading: $("#showLoading").prop("checked"),
  2033. hoverTargetAreaDisplay: $("#hoverTargetAreaDisplay").prop("checked"),
  2034. enableSegmentedTranslation: $("#enableSegmentedTranslation").prop("checked"),
  2035. showJumpToLuogu: $("#showJumpToLuogu").prop("checked"),
  2036. loaded: $("#loaded").prop("checked"),
  2037. translation: $("input[name='translation']:checked").val()
  2038. };
  2039. if (settings.translation === "openai") {
  2040. var selectedIndex = $('input[name="config_item"]:checked').closest('li').index();
  2041. if (selectedIndex === -1) {
  2042. $('#configControlTip').text('请选择一项配置!')
  2043. return;
  2044. }
  2045. }
  2046. GM_setValue('chatgpt-config', tempConfig);
  2047. let refreshPage = false; // 是否需要刷新页面
  2048. for (const [key, value] of Object.entries(settings)) {
  2049. if (!refreshPage && !(key == 'enableSegmentedTranslation' || key == 'translation')) {
  2050. if (GM_getValue(key) != value) refreshPage = true;
  2051. }
  2052. GM_setValue(key, value);
  2053. }
  2054. if (refreshPage) location.reload();
  2055. else {
  2056. // 更新配置信息
  2057. enableSegmentedTranslation = settings.enableSegmentedTranslation;
  2058. translation = settings.translation;
  2059. if (settings.translation === "openai") {
  2060. var selectedIndex = $('#config_bar_ul li input[type="radio"]:checked').closest('li').index();
  2061. if (selectedIndex !== opneaiConfig.choice) {
  2062. opneaiConfig = GM_getValue("chatgpt-config");
  2063. const configAtIndex = opneaiConfig.configurations[selectedIndex];
  2064. openai_model = configAtIndex.model;
  2065. openai_key = configAtIndex.key;
  2066. openai_proxy = configAtIndex.proxy;
  2067. openai_header = configAtIndex._header ?
  2068. configAtIndex._header.split("\n").map(header => {
  2069. const [key, value] = header.split(":");
  2070. return { [key.trim()]: value.trim() };
  2071. }) : [];
  2072. openai_data = configAtIndex._data ?
  2073. configAtIndex._data.split("\n").map(header => {
  2074. const [key, value] = header.split(":");
  2075. return { [key.trim()]: value.trim() };
  2076. }) : [];
  2077. }
  2078. }
  2079. }
  2080.  
  2081. $settingMenu.remove();
  2082. $settingBtns.prop("disabled", false).removeClass("open");
  2083. $(styleElement).remove();
  2084. }));
  2085.  
  2086. // 关闭
  2087. $settingMenu.on("click", ".btn-close", () => {
  2088. $settingMenu.remove();
  2089. $settingBtns.prop("disabled", false).removeClass("open");
  2090. $(styleElement).remove();
  2091. });
  2092. });
  2093. });
  2094.  
  2095. // html2md转换/处理规则
  2096. var turndownService = new TurndownService({ bulletListMarker: '-', escape: (text) => text });
  2097. var turndown = turndownService.turndown;
  2098.  
  2099. // 保留原始
  2100. turndownService.keep(['del']);
  2101.  
  2102. turndownService.addRule('removeByClass', {
  2103. filter: function (node) {
  2104. return node.classList.contains('html2md-panel') ||
  2105. node.classList.contains('div-btn-copy') ||
  2106. node.classList.contains('btn-copy') ||
  2107. node.classList.contains('overlay')
  2108. },
  2109. replacement: function () {
  2110. return '';
  2111. }
  2112. });
  2113.  
  2114. // inline math
  2115. turndownService.addRule('inline-math', {
  2116. filter: function (node, options) {
  2117. return node.tagName.toLowerCase() == "span" && node.className == "katex";
  2118. },
  2119. replacement: function (content, node) {
  2120. var latex = $(node).find('annotation').text();
  2121. latex = latex.replace(/</g, "&lt;").replace(/>/g, "&gt;");
  2122. return "$" + latex + "$";
  2123. }
  2124. });
  2125.  
  2126. // block math
  2127. turndownService.addRule('block-math', {
  2128. filter: function (node, options) {
  2129. return node.tagName.toLowerCase() == "span" && node.className == "katex-display";
  2130. },
  2131. replacement: function (content, node) {
  2132. var latex = $(node).find('annotation').text();
  2133. latex = latex.replace(/</g, "&lt;").replace(/>/g, "&gt;");
  2134. return "\n$$\n" + latex + "\n$$\n";
  2135. }
  2136. });
  2137.  
  2138. // pre
  2139. turndownService.addRule('pre', {
  2140. filter: function (node, options) {
  2141. return node.tagName.toLowerCase() == "pre";
  2142. },
  2143. replacement: function (content, node) {
  2144. return "```\n" + content + "```\n";
  2145. }
  2146. });
  2147.  
  2148. // bordertable
  2149. turndownService.addRule('bordertable', {
  2150. filter: 'table',
  2151. replacement: function (content, node) {
  2152. if (node.classList.contains('table')) {
  2153. var output = [],
  2154. thead = '',
  2155. trs = node.querySelectorAll('tr');
  2156. if (trs.length > 0) {
  2157. var ths = trs[0].querySelectorAll('th, td');
  2158. if (ths.length > 0) {
  2159. thead = '| ' + Array.from(ths).map(th => turndownService.turndown(th.innerHTML.trim())).join(' | ') + ' |\n'
  2160. thead += '| ' + Array.from(ths).map(() => ' --- ').join('|') + ' |\n';
  2161. }
  2162. }
  2163. var rows = node.querySelectorAll('tr');
  2164. Array.from(rows).forEach(function (row, i) {
  2165. if (i > 0) {
  2166. var cells = row.querySelectorAll('td,th');
  2167. var trow = '| ' + Array.from(cells).map(cell => turndownService.turndown(cell.innerHTML.trim())).join(' | ') + ' |';
  2168. output.push(trow);
  2169. }
  2170. });
  2171. return thead + output.join('\n');
  2172. } else {
  2173. return content;
  2174. }
  2175. }
  2176. });
  2177.  
  2178. // 随机数生成
  2179. function getRandomNumber(numDigits) {
  2180. let min = Math.pow(10, numDigits - 1);
  2181. let max = Math.pow(10, numDigits) - 1;
  2182. return Math.floor(Math.random() * (max - min + 1)) + min;
  2183. }
  2184.  
  2185. // 题目markdown转换/翻译面板
  2186. function addButtonPanel(parent, suffix, type, is_simple = false) {
  2187. let htmlString = `<div class='html2md-panel'>
  2188. <button class='html2mdButton html2md-view${suffix}'>MarkDown视图</button>
  2189. <button class='html2mdButton html2md-cb${suffix}'>Copy</button>
  2190. <button class='html2mdButton translateButton${suffix}'>翻译</button>
  2191. </div>`;
  2192. if (type === "this_level") {
  2193. $(parent).before(htmlString);
  2194. } else if (type === "child_level") {
  2195. $(parent).prepend(htmlString);
  2196. }
  2197. if (is_simple) {
  2198. $('.html2md-panel').find('.html2mdButton.html2md-view' + suffix + ', .html2mdButton.html2md-cb' + suffix).remove();
  2199. }
  2200. }
  2201.  
  2202. function addButtonWithHTML2MD(parent, suffix, type) {
  2203. $(document).on("click", ".html2md-view" + suffix, debounce(function () {
  2204. var target, removedChildren = $();
  2205. if (type === "this_level") {
  2206. target = $(".html2md-view" + suffix).parent().next().get(0);
  2207. } else if (type === "child_level") {
  2208. target = $(".html2md-view" + suffix).parent().parent().get(0);
  2209. removedChildren = $(".html2md-view" + suffix).parent().parent().children(':first').detach();
  2210. }
  2211. if (target.viewmd) {
  2212. target.viewmd = false;
  2213. $(this).text("MarkDown视图");
  2214. $(this).removeClass("mdViewed");
  2215. $(target).html(target.original_html);
  2216. } else {
  2217. target.viewmd = true;
  2218. if (!target.original_html) {
  2219. target.original_html = $(target).html();
  2220. }
  2221. if (!target.markdown) {
  2222. target.markdown = turndownService.turndown($(target).html());
  2223. }
  2224. $(this).text("原始内容");
  2225. $(this).addClass("mdViewed");
  2226. $(target).html(`<span class="mdViewContent" oninput="$(this).parent().get(0).markdown=this.value;" style="width:auto; height:auto;">${target.markdown}</span>`);
  2227. }
  2228. // 恢复删除的元素
  2229. if (removedChildren) $(target).prepend(removedChildren);
  2230. }));
  2231.  
  2232. if (hoverTargetAreaDisplay) {
  2233. var previousCSS;
  2234. $(document).on("mouseover", ".html2md-view" + suffix, function () {
  2235. var target;
  2236.  
  2237. if (type === "this_level") {
  2238. target = $(".html2md-view" + suffix).parent().next().get(0);
  2239. } else if (type === "child_level") {
  2240. target = $(".html2md-view" + suffix).parent().parent().get(0);
  2241. }
  2242.  
  2243. $(target).append('<div class="overlay">目标转换区域</div>');
  2244.  
  2245. previousCSS = {
  2246. "position": $(target).css("position"),
  2247. "display": $(target).css("display")
  2248. };
  2249. $(target).css({
  2250. "position": "relative",
  2251. "display": "block"
  2252. });
  2253.  
  2254. $(".html2md-view" + suffix).parent().css({
  2255. "position": "relative",
  2256. "z-index": "99999"
  2257. })
  2258. });
  2259.  
  2260. $(document).on("mouseout", ".html2md-view" + suffix, function () {
  2261. var target;
  2262.  
  2263. if (type === "this_level") {
  2264. target = $(".html2md-view" + suffix).parent().next().get(0);
  2265. } else if (type === "child_level") {
  2266. target = $(".html2md-view" + suffix).parent().parent().get(0);
  2267. }
  2268.  
  2269. $(target).find('.overlay').remove();
  2270. $(target).css(previousCSS);
  2271. $(".html2md-view" + suffix).parent().css({
  2272. "position": "static"
  2273. })
  2274. });
  2275. }
  2276. }
  2277.  
  2278. function addButtonWithCopy(parent, suffix, type) {
  2279. $(document).on("click", ".html2md-cb" + suffix, debounce(function () {
  2280. var target, removedChildren;
  2281. if (type === "this_level") {
  2282. target = $(".translateButton" + suffix).parent().next().eq(0).clone();
  2283. } else if (type === "child_level") {
  2284. target = $(".translateButton" + suffix).parent().parent().eq(0).clone();
  2285. $(target).children(':first').remove();
  2286. }
  2287. if ($(target).find('.mdViewContent').length <= 0) {
  2288. text = turndownService.turndown($(target).html());
  2289. } else {
  2290. text = $(target).find('.mdViewContent').text();
  2291. }
  2292. GM_setClipboard(text);
  2293. $(this).addClass("copied");
  2294. $(this).text("Copied");
  2295. // 更新复制按钮文本
  2296. setTimeout(() => {
  2297. $(this).removeClass("copied");
  2298. $(this).text("Copy");
  2299. }, 2000);
  2300. $(target).remove();
  2301. }));
  2302.  
  2303. if (hoverTargetAreaDisplay) {
  2304. var previousCSS;
  2305. $(document).on("mouseover", ".html2md-cb" + suffix, function () {
  2306. var target;
  2307.  
  2308. if (type === "this_level") {
  2309. target = $(".html2md-cb" + suffix).parent().next().get(0);
  2310. } else if (type === "child_level") {
  2311. target = $(".html2md-cb" + suffix).parent().parent().get(0);
  2312. }
  2313.  
  2314. $(target).append('<div class="overlay">目标复制区域</div>');
  2315. previousCSS = {
  2316. "position": $(target).css("position"),
  2317. "display": $(target).css("display")
  2318. };
  2319. $(target).css({
  2320. "position": "relative",
  2321. "display": "block"
  2322. });
  2323. $(".html2md-cb" + suffix).parent().css({
  2324. "position": "relative",
  2325. "z-index": "99999"
  2326. })
  2327. });
  2328.  
  2329. $(document).on("mouseout", ".html2md-cb" + suffix, function () {
  2330. var target;
  2331.  
  2332. if (type === "this_level") {
  2333. target = $(".html2md-cb" + suffix).parent().next().get(0);
  2334. } else if (type === "child_level") {
  2335. target = $(".html2md-cb" + suffix).parent().parent().get(0);
  2336. }
  2337.  
  2338. $(target).find('.overlay').remove();
  2339. $(target).css(previousCSS);
  2340. $(".html2md-cb" + suffix).parent().css({
  2341. "position": "static"
  2342. })
  2343. });
  2344. }
  2345. }
  2346.  
  2347. async function addButtonWithTranslation(parent, suffix, type) {
  2348. var result;
  2349. $(document).on('click', '.translateButton' + suffix, debounce(async function () {
  2350. $(this).trigger('mouseout');
  2351. $(this).removeClass("translated");
  2352. $(this).text("翻译中");
  2353. $(this).css("cursor", "not-allowed");
  2354. $(this).prop("disabled", true);
  2355. var target, element_node, block, errerNum = 0;
  2356. if (type === "this_level") block = $(".translateButton" + suffix).parent().next();
  2357. else if (type === "child_level") block = $(".translateButton" + suffix).parent().parent();
  2358.  
  2359. // 重新翻译
  2360. if (result) {
  2361. if (result.translateDiv) {
  2362. $(result.translateDiv).remove();
  2363. }
  2364. if (result.copyDiv) {
  2365. $(result.copyDiv).remove();
  2366. }
  2367. if (result.copyButton) {
  2368. $(result.copyButton).remove();
  2369. }
  2370. // 移除旧的事件
  2371. $(document).off("mouseover", ".translateButton" + suffix);
  2372. $(document).off("mouseout", ".translateButton" + suffix);
  2373. // 重新绑定悬停事件
  2374. if (hoverTargetAreaDisplay) bindHoverEvents(suffix, type);
  2375. }
  2376.  
  2377. // 分段翻译
  2378. if (enableSegmentedTranslation) {
  2379. var pElements = block.find("p, li");
  2380. for (let i = 0; i < pElements.length; i++) {
  2381. target = $(pElements[i]).eq(0).clone();
  2382. if (type === "child_level") $(target).children(':first').remove();
  2383. element_node = pElements[i];
  2384. if (type === "child_level") {
  2385. $(pElements[i]).append("<div></div>");
  2386. element_node = $(pElements[i]).find("div:last-child").get(0);
  2387. }
  2388. result = await blockProcessing(target, element_node, $(".translateButton" + suffix));
  2389. if (result.status) errerNum += 1;
  2390. $(target).remove();
  2391. if (translation == "deepl") await new Promise(resolve => setTimeout(resolve, 2000));
  2392. }
  2393. } else {
  2394. target = block.eq(0).clone();
  2395. if (type === "child_level") $(target).children(':first').remove();
  2396. element_node = $(block).get(0);
  2397. if (type === "child_level") {
  2398. $(parent).append("<div></div>");
  2399. element_node = $(parent).find("div:last-child").get(0);
  2400. }
  2401. //是否跳过折叠块
  2402. if ($(target).find('.spoiler').length > 0) {
  2403. const shouldSkip = await skiFoldingBlocks();
  2404. if (shouldSkip) {
  2405. $(target).find('.spoiler').remove();
  2406. } else {
  2407. $(target).find('.html2md-panel').remove();
  2408. }
  2409. }
  2410. result = await blockProcessing(target, element_node, $(".translateButton" + suffix));
  2411. if (result.status) errerNum += 1;
  2412. $(target).remove();
  2413. }
  2414.  
  2415. if (!errerNum) {
  2416. $(this).addClass("translated")
  2417. .text("已翻译")
  2418. .css("cursor", "pointer")
  2419. .removeClass("error")
  2420. .prop("disabled", false);
  2421. } else {
  2422. $(this).prop("disabled", false);
  2423. }
  2424.  
  2425. // 重新翻译
  2426. let currentText, is_error;
  2427. $(document).on("mouseover", ".translateButton" + suffix, function () {
  2428. currentText = $(this).text();
  2429. $(this).text("重新翻译");
  2430. if ($(this).hasClass("error")) {
  2431. is_error = true;
  2432. $(this).removeClass("error");
  2433. }
  2434. });
  2435.  
  2436. $(document).on("mouseout", ".translateButton" + suffix, function () {
  2437. $(this).text(currentText);
  2438. if (is_error) $(this).addClass("error");
  2439. });
  2440. }));
  2441.  
  2442. // 目标区域指示
  2443. function bindHoverEvents(suffix, type) {
  2444. var previousCSS;
  2445.  
  2446. $(document).on("mouseover", ".translateButton" + suffix, function () {
  2447. var target;
  2448.  
  2449. if (type === "this_level") {
  2450. target = $(".translateButton" + suffix).parent().next().get(0);
  2451. } else if (type === "child_level") {
  2452. target = $(".translateButton" + suffix).parent().parent().get(0);
  2453. }
  2454.  
  2455. $(target).append('<div class="overlay">目标翻译区域</div>');
  2456. previousCSS = {
  2457. "position": $(target).css("position"),
  2458. "display": $(target).css("display")
  2459. };
  2460. $(target).css({
  2461. "position": "relative",
  2462. "display": "block"
  2463. });
  2464. $(".translateButton" + suffix).parent().css({
  2465. "position": "relative",
  2466. "z-index": "99999"
  2467. });
  2468. });
  2469.  
  2470. $(document).on("mouseout", ".translateButton" + suffix, function () {
  2471. var target;
  2472.  
  2473. if (type === "this_level") {
  2474. target = $(".translateButton" + suffix).parent().next().get(0);
  2475. } else if (type === "child_level") {
  2476. target = $(".translateButton" + suffix).parent().parent().get(0);
  2477. }
  2478.  
  2479. $(target).find('.overlay').remove();
  2480. if (previousCSS) {
  2481. $(target).css(previousCSS);
  2482. }
  2483. $(".translateButton" + suffix).parent().css({
  2484. "position": "static"
  2485. });
  2486. });
  2487. }
  2488.  
  2489. if (hoverTargetAreaDisplay) bindHoverEvents(suffix, type);
  2490. }
  2491.  
  2492. // 块处理
  2493. async function blockProcessing(target, element_node, button) {
  2494. if (!target.markdown) {
  2495. target.markdown = turndownService.turndown($(target).html());
  2496. }
  2497. const textarea = document.createElement('textarea');
  2498. textarea.value = target.markdown;
  2499. var result = await translateProblemStatement(textarea.value, element_node, $(button));
  2500. //
  2501. if (result.status == 1) {
  2502. $(button).addClass("error")
  2503. .text("翻译中止")
  2504. .css("cursor", "pointer")
  2505. .prop("disabled", false);
  2506. $(result.translateDiv).remove();
  2507. $(target).remove();
  2508. } else if (result.status == 2) {
  2509. result.translateDiv.classList.add("error_translate");
  2510. $(button).addClass("error")
  2511. .text("翻译出错")
  2512. .css("cursor", "pointer")
  2513. .prop("disabled", false);
  2514. $(target).remove();
  2515. }
  2516. return result;
  2517. }
  2518.  
  2519. function addConversionButton() {
  2520. // 基本添加
  2521. $('section').each(function () {
  2522. let id = "_" + getRandomNumber(8);
  2523. addButtonPanel(this, id, "this_level");
  2524. addButtonWithHTML2MD(this, id, "this_level");
  2525. addButtonWithCopy(this, id, "this_level");
  2526. addButtonWithTranslation(this, id, "this_level");
  2527. });
  2528.  
  2529. // 添加按钮到题解部分
  2530. if (window.location.href.includes("editorial")) {
  2531. let contestNavTabs = $("#contest-nav-tabs");
  2532. let nextElement = contestNavTabs.next();
  2533. let id = "_editorial_" + getRandomNumber(8);
  2534. addButtonPanel(nextElement, id, "child_level");
  2535. addButtonWithHTML2MD(nextElement, id, "child_level");
  2536. addButtonWithCopy(nextElement, id, "child_level");
  2537. addButtonWithTranslation(nextElement, id, "child_level");
  2538. }
  2539. if (window.location.href.includes("editorial")) {
  2540. let contestNavTabs = $("#contest-nav-tabs");
  2541. let nextElement = contestNavTabs.next().children().eq(-2);
  2542. let id = "_editorial_" + getRandomNumber(8);
  2543. addButtonPanel(nextElement, id, "child_level");
  2544. addButtonWithHTML2MD(nextElement, id, "child_level");
  2545. addButtonWithCopy(nextElement, id, "child_level");
  2546. addButtonWithTranslation(nextElement, id, "child_level");
  2547. }
  2548.  
  2549. // 添加按钮到折叠块部分
  2550. $('details').each(function () {
  2551. let id = "_details_" + getRandomNumber(8);
  2552. addButtonPanel(this, id, "child_level");
  2553. addButtonWithHTML2MD(this, id, "child_level");
  2554. addButtonWithCopy(this, id, "child_level");
  2555. addButtonWithTranslation(this, id, "child_level");
  2556. });
  2557.  
  2558. // 添加到contest-statement部分
  2559. $('#contest-statement').each(function () {
  2560. let id = "_contest-statement_" + getRandomNumber(8);
  2561. addButtonPanel(this, id, "this_level");
  2562. addButtonWithHTML2MD(this, id, "this_level");
  2563. addButtonWithCopy(this, id, "this_level");
  2564. addButtonWithTranslation(this, id, "this_level");
  2565. });
  2566.  
  2567. // 添加到blog-post部分
  2568. $('.blog-post').each(function () {
  2569. let id = "_blog-post_" + getRandomNumber(8);
  2570. addButtonPanel(this, id, "this_level");
  2571. addButtonWithHTML2MD(this, id, "this_level");
  2572. addButtonWithCopy(this, id, "this_level");
  2573. addButtonWithTranslation(this, id, "this_level");
  2574. });
  2575. };
  2576.  
  2577. // 跳转洛谷
  2578. async function At2luogu() {
  2579. const getProblemId = () => {
  2580. const url = window.location.href;
  2581. const regex = /\/contests\/([A-Za-z\d]+)\/tasks\/([A-Za-z\d\_]+)/;
  2582. const matchResult = url.match(regex);
  2583. return matchResult && matchResult.length >= 3
  2584. ? `${matchResult[2]}`
  2585. : '';
  2586. };
  2587.  
  2588. const checkLinkExistence = (url) => {
  2589. return new Promise((resolve, reject) => {
  2590. GM.xmlHttpRequest({
  2591. method: "GET",
  2592. url,
  2593. headers: { "Range": "bytes=0-9999" }, // 获取前10KB数据
  2594. onload(response) {
  2595. if (response.responseText.match(/题目未找到/g)) {
  2596. resolve(false);
  2597. } else {
  2598. resolve(true);
  2599. }
  2600. },
  2601. onerror(error) {
  2602. reject(error);
  2603. }
  2604. });
  2605. });
  2606. };
  2607.  
  2608. const url = `https://www.luogu.com.cn/problem/AT_${getProblemId()}`;
  2609. const result = await checkLinkExistence(url);
  2610. if (getProblemId() && result) {
  2611. const problemLink = $("<a style='display: inline-block;vertical-align: middle;'>")
  2612. .attr("id", "problemLink")
  2613. .attr("href", url)
  2614. .attr("target", "_blank")
  2615. .html(`<button style="height: 25px;" class="html2mdButton"><img style="width:45px; margin-right:2px;" src="https://cdn.luogu.com.cn/fe/logo.png"></button>`);
  2616. problemLink.appendTo('.h2');
  2617. }
  2618. }
  2619.  
  2620. $(document).ready(function () {
  2621. var newElement = $("<div></div>")
  2622. .addClass("alert alert-info")
  2623. .html(`Atcoder Better! —— 正在等待页面资源加载……`)
  2624. .css({
  2625. margin: "1em",
  2626. "text-align": "center",
  2627. "font-weight": "600",
  2628. position: "relative",
  2629. });
  2630.  
  2631. var tip_SegmentedTranslation = $("<div></div>")
  2632. .addClass("alert alert-danger")
  2633. .html(`
  2634. Atcoder Better! —— 注意!分段翻译已开启,这会造成负面效果,
  2635. <p>除非你现在需要翻译超长篇的博客或者题目,否则请前往设置关闭分段翻译</p>
  2636. `)
  2637. .css({
  2638. margin: "1em",
  2639. "text-align": "center",
  2640. "font-weight": "600",
  2641. position: "relative",
  2642. });
  2643.  
  2644. function processPage() {
  2645. if (enableSegmentedTranslation)
  2646. $("#main-container").prepend(tip_SegmentedTranslation); //显示分段翻译警告
  2647.  
  2648. if (showLoading) {
  2649. newElement.html("Atcoder Better! —— 正在处理中……");
  2650. newElement.removeClass("alert-info").addClass("alert-success");
  2651. }
  2652.  
  2653. if (showJumpToLuogu) At2luogu();
  2654.  
  2655. addConversionButton();
  2656.  
  2657. if (showLoading) {
  2658. newElement.html("Atcoder Better! —— 加载已完成");
  2659. setTimeout(function () {
  2660. newElement.remove();
  2661. }, 3000);
  2662. }
  2663. }
  2664.  
  2665. if (showLoading) $("#main-container").prepend(newElement);
  2666.  
  2667. if (loaded) {
  2668. processPage();
  2669. } else {
  2670. // 页面完全加载完成后执行
  2671. window.onload = function () {
  2672. processPage();
  2673. };
  2674. }
  2675. });
  2676.  
  2677. // 字数超限确认
  2678. function showWordsExceededDialog(button) {
  2679. return new Promise(resolve => {
  2680. const styleElement = GM_addStyle(darkenPageStyle);
  2681. $(button).removeClass("translated");
  2682. $(button).text("字数超限");
  2683. $(button).css("cursor", "not-allowed");
  2684. $(button).prop("disabled", true);
  2685. let htmlString = `
  2686. <div class="wordsExceeded">
  2687. <h4>字数超限!</h4>
  2688. <p>注意,即将翻译的内容字数超过了4950个字符,您可能选择了错误的翻译按钮</p>
  2689. <div style="display:flex; padding:5px 0px; align-items: center;">
  2690. `+ helpCircleHTML + `
  2691. <p>
  2692. 由于实现方式,区域中会出现多个翻译按钮,请点击更小的子区域中的翻译按钮,
  2693. <br>或者在设置面板中开启 分段翻译 后重试。
  2694. </p>
  2695. </div>
  2696. <p>对于免费的接口,大量请求可能导致你的IP被暂时禁止访问,对于GPT,会消耗大量的token</p>
  2697. <p>您确定要继续翻译吗?</p>
  2698. <div style="display:flex; padding-top:10px">
  2699. <button id="continueButton">继续</button><button id="cancelButton">取消</button>
  2700. </div>
  2701. </div>
  2702. `;
  2703. $('body').before(htmlString);
  2704. $("#continueButton").click(function () {
  2705. $(styleElement).remove();
  2706. $('.wordsExceeded').remove();
  2707. resolve(true);
  2708. });
  2709. $("#cancelButton").click(function () {
  2710. $(styleElement).remove();
  2711. $('.wordsExceeded').remove();
  2712. resolve(false);
  2713. });
  2714. });
  2715. }
  2716.  
  2717. // 跳过折叠块确认
  2718. function skiFoldingBlocks() {
  2719. return new Promise(resolve => {
  2720. const styleElement = GM_addStyle(darkenPageStyle);
  2721. let htmlString = `
  2722. <div class="wordsExceeded">
  2723. <h4>是否跳过折叠块?</h4>
  2724. <p></p>
  2725. <div style="display:grid; padding:5px 0px; align-items: center;">
  2726. <p>
  2727. 即将翻译的区域中包含折叠块,可能不需要翻译,现在您需要选择是否跳过这些折叠块,
  2728. </p>
  2729. <p>
  2730. 如果其中有您需要翻译的折叠块,可以稍后再单独点击这些折叠块内的翻译按钮进行翻译
  2731. </p>
  2732. </div>
  2733. <p>要跳过折叠块吗?(建议选择跳过)</p>
  2734. <div style="display:flex; padding-top:10px">
  2735. <button id="cancelButton">否</button><button id="skipButton">跳过</button>
  2736. </div>
  2737. </div>
  2738. `;
  2739. $('body').before(htmlString);
  2740. $("#skipButton").click(function () {
  2741. $(styleElement).remove();
  2742. $('.wordsExceeded').remove();
  2743. resolve(true);
  2744. });
  2745. $("#cancelButton").click(function () {
  2746. $(styleElement).remove();
  2747. $('.wordsExceeded').remove();
  2748. resolve(false);
  2749. });
  2750. });
  2751. }
  2752.  
  2753. // 翻译框/翻译处理器
  2754. var translatedText = "";
  2755. async function translateProblemStatement(text, element_node, button) {
  2756. let status = 0;
  2757. let id = getRandomNumber(8);
  2758. let matches = [];
  2759. let replacements = {};
  2760. // 创建元素并放在element_node的后面
  2761. const translateDiv = document.createElement('div');
  2762. translateDiv.setAttribute('id', id);
  2763. translateDiv.classList.add('translate-problem-statement');
  2764. const spanElement = document.createElement('span');
  2765. translateDiv.appendChild(spanElement);
  2766. element_node.insertAdjacentElement('afterend', translateDiv);
  2767. // 替换latex公式
  2768. if (translation != "openai") {
  2769. // 使用GPT翻译时不必替换latex公式
  2770. let i = 0;
  2771. // 块公式
  2772. matches = matches.concat(text.match(/\$\$([\s\S]*?)\$\$/g));
  2773. try {
  2774. for (i; i < matches.length; i++) {
  2775. let match = matches[i];
  2776. text = text.replace(match, `【${i + 1}】`);
  2777. replacements[`【${i + 1}】`] = match;
  2778. }
  2779. } catch (e) { }
  2780. // 行内公式
  2781. matches = matches.concat(text.match(/\$(.*?)\$/g));
  2782. try {
  2783. for (i; i < matches.length; i++) {
  2784. let match = matches[i];
  2785. text = text.replace(match, `【${i + 1}】`);
  2786. replacements[`【${i + 1}】`] = match;
  2787. }
  2788. } catch (e) { }
  2789. }
  2790. if (text.length > 4950) {
  2791. const shouldContinue = await showWordsExceededDialog(button);
  2792. if (!shouldContinue) {
  2793. status = 1;
  2794. return {
  2795. translateDiv: translateDiv,
  2796. status: status
  2797. };
  2798. }
  2799. }
  2800. // 翻译
  2801. if (translation == "deepl") {
  2802. translateDiv.innerHTML = "正在翻译中……请稍等";
  2803. translatedText = await translate_deepl(text);
  2804. } else if (translation == "youdao") {
  2805. translateDiv.innerHTML = "正在翻译中……请稍等";
  2806. translatedText = await translate_youdao_mobile(text);
  2807. } else if (translation == "google") {
  2808. translateDiv.innerHTML = "正在翻译中……请稍等";
  2809. translatedText = await translate_gg(text);
  2810. } else if (translation == "openai") {
  2811. try {
  2812. translateDiv.innerHTML = "正在翻译中……" + "<br><br>正在使用的配置:" + opneaiConfig.configurations[opneaiConfig.choice].note
  2813. + "<br><br>使用 ChatGPT 进行翻译通常需要很长的时间,请耐心等待";
  2814. translatedText = await translate_openai(text);
  2815. } catch (error) {
  2816. status = 2;
  2817. translatedText = error;
  2818. }
  2819. }
  2820. if (/^翻译出错/.test(translatedText)) status = 2;
  2821. // 还原latex公式
  2822. if (translation != "openai") {
  2823. try {
  2824. for (let i = 0; i < matches.length; i++) {
  2825. let match = matches[i];
  2826. let replacement = replacements[`【${i + 1}】`];
  2827. let regex;
  2828. regex = new RegExp(`【\\s*${i + 1}\\s*】`, 'g');
  2829. translatedText = translatedText.replace(regex, replacement);
  2830. regex = new RegExp(`\\[\\s*${i + 1}\\s*\\]`, 'g');
  2831. translatedText = translatedText.replace(regex, replacement);
  2832. regex = new RegExp(`【\\s*${i + 1}[^】\\d]`, 'g');
  2833. translatedText = translatedText.replace(regex, replacement);
  2834. regex = new RegExp(`[^【\\d]${i + 1}\\s*】`, 'g');
  2835. translatedText = translatedText.replace(regex, " " + replacement);
  2836. }
  2837. } catch (e) { }
  2838. }
  2839.  
  2840. // 创建一个隐藏的元素来保存 translatedText 的值
  2841. var textElement = document.createElement("div");
  2842. textElement.style.display = "none";
  2843. textElement.textContent = translatedText;
  2844. translateDiv.parentNode.insertBefore(textElement, translateDiv);
  2845.  
  2846. // 翻译复制按钮
  2847. var copyButton = document.createElement("button");
  2848. copyButton.textContent = "Copy";
  2849. var wrapperDiv = document.createElement("div");
  2850. $(wrapperDiv).css({
  2851. display: "flex",
  2852. justifyContent: "flex-end"
  2853. });
  2854. $(wrapperDiv).append(copyButton);
  2855. $(copyButton).addClass("html2mdButton html2md-cb");
  2856.  
  2857. copyButton.addEventListener("click", function () {
  2858. var translatedText = textElement.textContent;
  2859. GM_setClipboard(translatedText);
  2860. $(this).addClass("copied").text("Copied");
  2861. // 更新复制按钮文本
  2862. setTimeout(() => {
  2863. $(this).removeClass("copied");
  2864. $(this).text("Copy");
  2865. }, 2000);
  2866. });
  2867. translateDiv.parentNode.insertBefore(wrapperDiv, translateDiv);
  2868.  
  2869. // 转义LaTex中的特殊符号
  2870. const escapeRules = [
  2871. { pattern: /(?<!\\)>(?!\s)/g, replacement: " &gt; " }, // >符号
  2872. { pattern: /(?<!\\)</g, replacement: " &lt; " }, // <符号
  2873. { pattern: /(?<!\\)\*/g, replacement: " &#42; " }, // *符号
  2874. { pattern: /(?<!\\)& /g, replacement: "\\&" }, // &符号
  2875. { pattern: /\\&/g, replacement: "\\\\&" }, // &符号
  2876. ];
  2877.  
  2878. let latexMatches = [...translatedText.matchAll(/\$\$([\s\S]*?)\$\$|\$(.*?)\$/g)];
  2879.  
  2880. for (const match of latexMatches) {
  2881. const matchedText = match[0];
  2882.  
  2883. for (const rule of escapeRules) {
  2884. const escapedText = matchedText.replaceAll(rule.pattern, rule.replacement);
  2885. translatedText = translatedText.replace(matchedText, escapedText);
  2886. }
  2887. }
  2888.  
  2889. // 渲染MarkDown
  2890. var md = window.markdownit();
  2891. var html = md.render(translatedText);
  2892. translateDiv.innerHTML = html;
  2893. // 渲染Latex
  2894. if (typeof renderMathInElement === 'function') {
  2895. renderMathInElement(translateDiv, {
  2896. delimiters: [{
  2897. left: "$$",
  2898. right: "$$",
  2899. display: true
  2900. }, {
  2901. left: "$",
  2902. right: "$",
  2903. display: false
  2904. }]
  2905. });
  2906. }
  2907. return {
  2908. translateDiv: translateDiv,
  2909. status: status,
  2910. copyDiv: textElement,
  2911. copyButton: copyButton
  2912. };
  2913.  
  2914. }
  2915.  
  2916. // ChatGPT
  2917. async function translate_openai(raw) {
  2918. var openai_retext = "";
  2919. var data = {
  2920. model: (openai_model !== null && openai_model !== "") ? openai_model : 'gpt-3.5-turbo',
  2921. messages: [{
  2922. role: "user",
  2923. content: "请将下面的文本翻译为中文,这是一道编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw
  2924. }],
  2925. temperature: 0.7,
  2926. ...Object.assign({}, ...openai_data)
  2927. };
  2928. return new Promise(function (resolve, reject) {
  2929. GM_xmlhttpRequest({
  2930. method: 'POST',
  2931. url: (openai_proxy !== null && openai_proxy !== "") ? openai_proxy : 'https://api.openai.com/v1/chat/completions',
  2932.  
  2933. data: JSON.stringify(data),
  2934. headers: {
  2935. 'Content-Type': 'application/json',
  2936. 'Authorization': 'Bearer ' + openai_key,
  2937. ...Object.assign({}, ...openai_header)
  2938. },
  2939. responseType: 'json',
  2940. onload: function (response) {
  2941. if (!response.response) {
  2942. reject("发生了未知的错误,如果你启用了代理API,请确认是否填写正确,并确保代理能够正常工作。\n\n如果无法解决,请前往 https://greatest.deepsurf.us/zh-CN/scripts/471106/feedback 反馈 请注意打码响应报文的敏感部分\n\n响应报文:" + JSON.stringify(response));
  2943. }
  2944. else if (!response.response.choices || response.response.choices.length < 1 || !response.response.choices[0].message) {
  2945. resolve("翻译出错,请重试\n\n如果无法解决,请前往 https://greatest.deepsurf.us/zh-CN/scripts/471106/feedback 反馈\n\n报错信息:" + JSON.stringify(response.response, null, ''));
  2946. } else {
  2947. openai_retext = response.response.choices[0].message.content;
  2948. resolve(openai_retext);
  2949. }
  2950. },
  2951. onerror: function (response) {
  2952. reject("发生了未知的错误,请确认你是否能正常访问OpenAi的接口,如果使用代理API,请检查是否正常工作\n\n如果无法解决,请前往 https://greatest.deepsurf.us/zh-CN/scripts/471106/feedback 反馈 请注意打码响应报文的敏感部分\n\n响应报文:" + JSON.stringify(response));
  2953. },
  2954. });
  2955. });
  2956. }
  2957.  
  2958. //--谷歌翻译--start
  2959. async function translate_gg(raw) {
  2960. return new Promise((resolve, reject) => {
  2961. const url = 'https://translate.google.com/m';
  2962. const params = `tl=zh-CN&q=${encodeURIComponent(raw)}`;
  2963.  
  2964. GM_xmlhttpRequest({
  2965. method: 'GET',
  2966. url: `${url}?${params}`,
  2967. onload: function (response) {
  2968. const html = response.responseText;
  2969. const translatedText = $(html).find('.result-container').text();
  2970. resolve(translatedText);
  2971. },
  2972. onerror: function (error) {
  2973. console.error('Error:', error);
  2974. reject(error);
  2975. }
  2976. });
  2977. });
  2978. }
  2979. //--谷歌翻译--end
  2980.  
  2981. //--有道翻译m--start
  2982. async function translate_youdao_mobile(raw) {
  2983. const options = {
  2984. method: "POST",
  2985. url: 'http://m.youdao.com/translate',
  2986. data: "inputtext=" + encodeURIComponent(raw) + "&type=AUTO",
  2987. anonymous: true,
  2988. headers: {
  2989. "Content-Type": "application/x-www-form-urlencoded",
  2990. 'Host': 'm.youdao.com',
  2991. 'Origin': 'http://m.youdao.com',
  2992. 'Referer': 'http://m.youdao.com/translate',
  2993. }
  2994. }
  2995. return await BaseTranslate('有道翻译mobile', raw, options, res => /id="translateResult">\s*?<li>([\s\S]*?)<\/li>\s*?<\/ul/.exec(res)[1])
  2996. }
  2997. //--有道翻译m--end
  2998.  
  2999. //--Deepl翻译--start
  3000. function getTimeStamp(iCount) {
  3001. const ts = Date.now();
  3002. if (iCount !== 0) {
  3003. iCount = iCount + 1;
  3004. return ts - (ts % iCount) + iCount;
  3005. } else {
  3006. return ts;
  3007. }
  3008. }
  3009.  
  3010. async function translate_deepl(raw) {
  3011. const id = (Math.floor(Math.random() * 99999) + 100000) * 1000;
  3012. const data = {
  3013. jsonrpc: '2.0',
  3014. method: 'LMT_handle_texts',
  3015. id,
  3016. params: {
  3017. splitting: 'newlines',
  3018. lang: {
  3019. source_lang_user_selected: 'auto',
  3020. target_lang: 'ZH',
  3021. },
  3022. texts: [{
  3023. text: raw,
  3024. requestAlternatives: 3
  3025. }],
  3026. timestamp: getTimeStamp(raw.split('i').length - 1)
  3027. }
  3028. }
  3029. let postData = JSON.stringify(data);
  3030. if ((id + 5) % 29 === 0 || (id + 3) % 13 === 0) {
  3031. postData = postData.replace('"method":"', '"method" : "');
  3032. } else {
  3033. postData = postData.replace('"method":"', '"method": "');
  3034. }
  3035. const options = {
  3036. method: 'POST',
  3037. url: 'https://www2.deepl.com/jsonrpc',
  3038. data: postData,
  3039. headers: {
  3040. 'Content-Type': 'application/json',
  3041. 'Host': 'www2.deepl.com',
  3042. 'Origin': 'https://www.deepl.com',
  3043. 'Referer': 'https://www.deepl.com/',
  3044. },
  3045. anonymous: true,
  3046. nocache: true,
  3047. }
  3048. return await BaseTranslate('Deepl翻译', raw, options, res => JSON.parse(res).result.texts[0].text)
  3049. }
  3050.  
  3051. //--Deepl翻译--end
  3052.  
  3053. //--异步请求包装工具--start
  3054. async function PromiseRetryWrap(task, options, ...values) {
  3055. const { RetryTimes, ErrProcesser } = options || {};
  3056. let retryTimes = RetryTimes || 5;
  3057. const usedErrProcesser = ErrProcesser || (err => { throw err });
  3058. if (!task) return;
  3059. while (true) {
  3060. try {
  3061. return await task(...values);
  3062. } catch (err) {
  3063. if (!--retryTimes) {
  3064. console.log(err);
  3065. return usedErrProcesser(err);
  3066. }
  3067. }
  3068. }
  3069. }
  3070.  
  3071. async function BaseTranslate(name, raw, options, processer) {
  3072. let errtext;
  3073. const toDo = async () => {
  3074. var tmp;
  3075. try {
  3076. const data = await Request(options);
  3077. tmp = data.responseText;
  3078. const result = await processer(tmp);
  3079. if (result) sessionStorage.setItem(name + '-' + raw, result);
  3080. return result
  3081. } catch (err) {
  3082. errtext = tmp;
  3083. throw {
  3084. responseText: tmp,
  3085. err: err
  3086. }
  3087. }
  3088. }
  3089. return await PromiseRetryWrap(toDo, { RetryTimes: 3, ErrProcesser: () => "翻译出错,请重试或更换翻译接口\n\n如果无法解决,请前往 https://greatest.deepsurf.us/zh-CN/scripts/471106/feedback 反馈 请注意打码报错信息的敏感部分\n\n报错信息:" + errtext })
  3090. }
  3091.  
  3092.  
  3093. function Request(options) {
  3094. return new Promise((reslove, reject) => GM_xmlhttpRequest({ ...options, onload: reslove, onerror: reject }))
  3095. }
  3096.  
  3097. //--异步请求包装工具--end
  3098.  
  3099. // 配置自动迁移代码(将在10个小版本后移除)
  3100. if (GM_getValue("openai_key") || GM_getValue("api2d_key")) {
  3101. const newConfig = { "choice": -1, "configurations": [] };
  3102. if (GM_getValue("openai_key")) {
  3103. let config1 = {
  3104. "note": "我的配置1",
  3105. "model": GM_getValue("openai_model"),
  3106. "key": GM_getValue("openai_key"),
  3107. "proxy": GM_getValue("openai_proxy"),
  3108. "_header": "",
  3109. "_data": ""
  3110. }
  3111. if (GM_getValue("translation") === "openai") newConfig.choice = 0;
  3112. newConfig.configurations.push(config1);
  3113. }
  3114. if (GM_getValue("api2d_key")) {
  3115. let config2 = {
  3116. "note": "api2d",
  3117. "model": GM_getValue("api2d_model"),
  3118. "key": GM_getValue("api2d_key"),
  3119. "proxy": GM_getValue("api2d_request_entry") + '/v1/chat/completions',
  3120. "_header": GM_getValue("x_api2d_no_cache") ? "" : " x-api2d-no-cache : 1",
  3121. "_data": ""
  3122. }
  3123. if (GM_getValue("translation") === "api2d") {
  3124. if (GM_getValue("openai_key")) newConfig.choice = 1;
  3125. else newConfig.choice = 0;
  3126. }
  3127. newConfig.configurations.push(config2);
  3128. }
  3129. GM_setValue("chatgpt-config", newConfig);
  3130. const keysToDelete = ["openai_key", "openai_model", "openai_proxy", "api2d_key", "api2d_model", "api2d_request_entry", "x_api2d_no_cache", "showOpneAiAdvanced"];
  3131. keysToDelete.forEach(key => {
  3132. if (GM_getValue(key) != undefined) GM_deleteValue(key);
  3133. });
  3134. if (GM_getValue("translation") === "api2d") GM_setValue("translation", "openai");
  3135. location.reload();
  3136. }