Atcoder Better!

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

Verzia zo dňa 08.09.2023. Pozri najnovšiu verziu.

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