Nowcoder Better!

牛客竞赛题目题解markdown一键复制

  1. // ==UserScript==
  2. // @name Nowcoder Better!
  3. // @namespace https://greasyfork.org/users/747162
  4. // @version 1.12.0
  5. // @description 牛客竞赛题目题解markdown一键复制
  6. // @author 北极小狐
  7. // @match https://ac.nowcoder.com/*
  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 greasyfork.org
  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. // @connect sustech.edu.cn
  24. // @icon https://aowuucdn.oss-cn-beijing.aliyuncs.com/nowcoder.png
  25. // @require https://mirrors.sustech.edu.cn/cdnjs/ajax/libs/turndown/7.2.0/turndown.min.js#sha512-sJzEecN5Nk8cq81zKtGq6/z9Z/r3q38zV9enY75IVxiG7ybtlNUt864sL4L1Kf36bYIwxTMVKQOtU4VhD7hGrw==
  26. // @require https://mirrors.sustech.edu.cn/cdnjs/ajax/libs/markdown-it/13.0.2/markdown-it.js#sha512-2LtYcLGnCbAWz9nDIrfG2pHFiFu9n+3oGecQlzLuYsLgen/oxiYscGWnDST9J9EZanlsQkDD0ZP2n/6peDuALQ==
  27. // @license GPL3
  28. // @compatible Chrome
  29. // @compatible Firefox
  30. // @compatible Edge
  31. // ==/UserScript==
  32.  
  33. // 状态与初始化
  34. const getGMValue = (key, defaultValue) => {
  35. const value = GM_getValue(key);
  36. if (value === undefined || value === "") {
  37. GM_setValue(key, defaultValue);
  38. return defaultValue;
  39. }
  40. return value;
  41. };
  42. const hoverTargetAreaDisplay = getGMValue("hoverTargetAreaDisplay", false);
  43. var enableSegmentedTranslation = getGMValue("enableSegmentedTranslation", false);
  44. var translation = getGMValue("translation", "deepl");
  45. //openai
  46. var openai_model, openai_key, openai_proxy, openai_header, openai_data;
  47. var opneaiConfig = getGMValue("chatgpt-config", {
  48. "choice": -1,
  49. "configurations": []
  50. });
  51. if (opneaiConfig.choice !== -1 && opneaiConfig.configurations.length !== 0) {
  52. const configAtIndex = opneaiConfig.configurations[opneaiConfig.choice];
  53.  
  54. if (configAtIndex == undefined) {
  55. let existingConfig = GM_getValue('chatgpt-config');
  56. existingConfig.choice = 0;
  57. GM_setValue('chatgpt-config', existingConfig);
  58. location.reload();
  59. }
  60. openai_model = configAtIndex.model;
  61. openai_key = configAtIndex.key;
  62. openai_proxy = configAtIndex.proxy;
  63. openai_header = configAtIndex._header ?
  64. configAtIndex._header.split("\n").map(header => {
  65. const [key, value] = header.split(":");
  66. return { [key.trim()]: value.trim() };
  67. }) : [];
  68. openai_data = configAtIndex._data ?
  69. configAtIndex._data.split("\n").map(header => {
  70. const [key, value] = header.split(":");
  71. return { [key.trim()]: value.trim() };
  72. }) : [];
  73. }
  74.  
  75. // 常量
  76. 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>';
  77. 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; }`;
  78. 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; }`;
  79.  
  80. // 语言判断
  81. const isEnglishLanguage = (function () {
  82. var metaElement = $('meta[http-equiv="Content-Language"]');
  83. var contentValue = metaElement.attr('content');
  84. return (contentValue === 'en');
  85. })();
  86.  
  87. // 样式
  88. GM_addStyle(`
  89. :root {
  90. --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";
  91. }
  92. span.mdViewContent {
  93. white-space: pre-wrap;
  94. }
  95. /*翻译区域提示*/
  96. .overlay {
  97. pointer-events: none;
  98. position: absolute;
  99. top: 0;
  100. left: 0;
  101. width: 100%;
  102. height: 100%;
  103. background: repeating-linear-gradient(135deg, #97e7cacc, #97e7cacc 30px, #e9fbf1cc 0px, #e9fbf1cc 55px);
  104. border-radius: 5px;
  105. display: flex;
  106. align-items: center;
  107. justify-content: center;
  108. color: #00695C;
  109. font-size: 16px;
  110. font-weight: bold;
  111. text-shadow: 0px 0px 2px #edfcf4;
  112. }
  113. /*翻译div*/
  114. .translate-problem-statement {
  115. justify-items: start;
  116. letter-spacing: 1.8px;
  117. color: #059669;
  118. background-color: #f9f9fa;
  119. border: 1px solid #10b981;
  120. border-radius: 0.3rem;
  121. padding: 5px;
  122. margin: 10px 0px;
  123. width: 100%;
  124. box-sizing: border-box;
  125. font-size: 13px;
  126. }
  127. .translate-problem-statement.error_translate {
  128. color: red;
  129. border-color: red;
  130. }
  131.  
  132. .translate-problem-statement h2, .translate-problem-statement h3 {
  133. font-size: 16px;
  134. }
  135.  
  136. .translate-problem-statement ul {
  137. line-height: 100%;
  138. }
  139.  
  140. .translate-problem-statement a {
  141. color: #10b981;
  142. font-weight: 600;
  143. background: 0 0;
  144. text-decoration: none;
  145. }
  146. .translate-problem-statement p {
  147. font-size: 14px !important;
  148. }
  149. .translate-problem-statement img {
  150. max-width: 100.0%;
  151. max-height: 100.0%;
  152. }
  153.  
  154. .translate-problem-statement .katex {
  155. font-size: 14px;
  156. }
  157. .translate-problem-statement a:hover {
  158. text-decoration: revert;
  159. }
  160. .html2md-panel {
  161. display: flex;
  162. justify-content: flex-end;
  163. }
  164. .html2md-panel a {
  165. text-decoration: none;
  166. }
  167. button.html2mdButton {
  168. display: flex;
  169. align-items: center;
  170. cursor: pointer;
  171. background-color: #ffffff;
  172. color: #606266;
  173. height: 22px;
  174. width: auto;
  175. font-size: 13px;
  176. border-radius: 0.3rem;
  177. padding: 1px 5px;
  178. margin: 5px;
  179. border: 1px solid #dcdfe6;
  180. }
  181. button.html2mdButton:hover {
  182. color: #409eff;
  183. border-color: #409eff;
  184. }
  185. button.html2mdButton.copied {
  186. background-color: #f0f9eb;
  187. color: #67c23e;
  188. border: 1px solid #b3e19d;
  189. }
  190. button.html2mdButton.mdViewed {
  191. background-color: #fdf6ec;
  192. color: #e6a23c;
  193. border: 1px solid #f3d19e;
  194. }
  195. button.html2mdButton.error {
  196. background-color: #fef0f0;
  197. color: #f56c6c;
  198. border: 1px solid #fab6b6;
  199. }
  200. button.translated {
  201. cursor: not-allowed;
  202. background-color: #f0f9eb;
  203. color: #67c23e;
  204. border: 1px solid #b3e19d;
  205. }
  206. button.html2mdButton.reTranslation {
  207. background-color: #f4f4f5;
  208. color: #909399;
  209. border: 1px solid #c8c9cc;
  210. }
  211. .translate-problem-statement table {
  212. border: 1px #ccc solid !important;
  213. margin: 1.5em 0 !important;
  214. color: #059669 !important;
  215. }
  216. .translate-problem-statement table thead th {
  217. border: 1px #ccc solid !important;
  218. color: #059669 !important;
  219. }
  220. .translate-problem-statement table td {
  221. border-right: 1px solid #ccc;
  222. border-top: 1px solid #ccc;
  223. padding: 0.7143em 0.5em;
  224. }
  225. .translate-problem-statement table th {
  226. padding: 0.7143em 0.5em;
  227. }
  228. .translate-problem-statement p:not(:first-child) {
  229. margin: 1.5em 0 0;
  230. }
  231. /*设置面板*/
  232. header .enter-or-register-box, header .languages {
  233. position: absolute;
  234. right: 170px;
  235. }
  236. button.html2mdButton.NowcoderBetter_setting {
  237. float: right;
  238. height: 30px;
  239. background: #25bb9b;
  240. color: white;
  241. margin: 10px;
  242. border: 0px;
  243. }
  244.  
  245. button.html2mdButton.NowcoderBetter_setting.open {
  246. background-color: #e6e6e61f;
  247. color: #727378;
  248. cursor: not-allowed;
  249. }
  250. .NowcoderBetter_setting_menu {
  251. z-index: 9999;
  252. box-shadow: 0px 0px 0px 4px #ffffff;
  253. display: grid;
  254. position: fixed;
  255. top: 50%;
  256. left: 50%;
  257. width: 480px;
  258. max-height: 90vh;
  259. overflow-y: auto;
  260. transform: translate(-50%, -50%);
  261. border-radius: 6px;
  262. background-color: #edf1ff;
  263. border-collapse: collapse;
  264. border: 1px solid #ffffff;
  265. color: #697e91;
  266. font-family: var(--vp-font-family-base);
  267. padding: 10px 20px 20px 20px;
  268. box-sizing: content-box;
  269. }
  270. .NowcoderBetter_setting_menu h4,.NowcoderBetter_setting_menu h5 {
  271. font-weight: 600;
  272. margin: 5px 0px;
  273. }
  274. .NowcoderBetter_setting_menu h4 {
  275. font-size: 17px;
  276. }
  277. .NowcoderBetter_setting_menu h5 {
  278. font-size: 16px;
  279. }
  280. .NowcoderBetter_setting_menu h3 {
  281. margin-top: 10px;
  282. font-weight: 600;
  283. font-size: 18px;
  284. }
  285. .NowcoderBetter_setting_menu hr {
  286. border: none;
  287. height: 1px;
  288. background-color: #ccc;
  289. margin: 10px 0;
  290. }
  291. /*设置面板-关闭按钮*/
  292. .NowcoderBetter_setting_menu .tool-box {
  293. position: absolute;
  294. align-items: center;
  295. justify-content: center;
  296. width: 20px;
  297. height: 20px;
  298. overflow: hidden;
  299. border-radius: 10px;
  300. top: 3px;
  301. right: 3px;
  302. }
  303.  
  304. .NowcoderBetter_setting_menu .btn-close {
  305. display: flex;
  306. text-align: center;
  307. width: 20px;
  308. height: 20px;
  309. color: transparent;
  310. font-size: 0;
  311. cursor: pointer;
  312. background-color: #ff000080;
  313. border: none;
  314. margin: 0px;
  315. padding: 0px;
  316. overflow: hidden;
  317. transition: .15s ease all;
  318. align-items: center;
  319. justify-content: center;
  320. box-sizing: border-box;
  321. }
  322.  
  323. .NowcoderBetter_setting_menu .btn-close:hover {
  324. width: 20px;
  325. height: 20px !important;
  326. font-size: 17px;
  327. color: #ffffff;
  328. background-color: #ff0000cc;
  329. box-shadow: 0 5px 5px 0 #00000026;
  330. }
  331.  
  332. .NowcoderBetter_setting_menu .btn-close:active {
  333. width: 20px;
  334. height: 20px;
  335. font-size: 1px;
  336. color: #ffffffde;
  337. --shadow-btn-close: 0 3px 3px 0 #00000026;
  338. box-shadow: var(--shadow-btn-close);
  339. }
  340.  
  341. /*设置面板-checkbox*/
  342. .NowcoderBetter_setting_menu input[type=checkbox]:focus {
  343. outline: 0px;
  344. }
  345.  
  346. .NowcoderBetter_setting_menu input[type="checkbox"] {
  347. margin: 0px;
  348. appearance: none;
  349. -webkit-appearance: none;
  350. width: 40px;
  351. height: 20px !important;
  352. border: 1.5px solid #D7CCC8;
  353. padding: 0px !important;
  354. border-radius: 20px;
  355. background: #efebe978;
  356. position: relative;
  357. box-sizing: border-box;
  358. }
  359.  
  360. .NowcoderBetter_setting_menu input[type="checkbox"]::before {
  361. content: "";
  362. width: 14px;
  363. height: 14px;
  364. background: #D7CCC8;
  365. border: 1.5px solid #BCAAA4;
  366. border-radius: 50%;
  367. position: absolute;
  368. top: 0;
  369. left: 0;
  370. transform: translate(2%, 2%);
  371. transition: all 0.3s ease-in-out;
  372. -webkit-box-sizing: content-box;
  373. -moz-box-sizing: content-box;
  374. box-sizing: content-box;
  375. }
  376.  
  377. .NowcoderBetter_setting_menu input[type="checkbox"]::after {
  378. 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");
  379. position: absolute;
  380. top: 0;
  381. left: 24px;
  382. }
  383.  
  384. .NowcoderBetter_setting_menu input[type="checkbox"]:checked {
  385. border: 1.5px solid #C5CAE9;
  386. background: #E8EAF6;
  387. }
  388.  
  389. .NowcoderBetter_setting_menu input[type="checkbox"]:checked::before {
  390. background: #C5CAE9;
  391. border: 1.5px solid #7986CB;
  392. transform: translate(122%, 2%);
  393. transition: all 0.3s ease-in-out;
  394. }
  395.  
  396. .NowcoderBetter_setting_menu input[type="checkbox"]:checked::after {
  397. 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");
  398. position: absolute;
  399. top: 1.5px;
  400. left: 4.5px;
  401. }
  402.  
  403. .NowcoderBetter_setting_menu label {
  404. font-size: 16px;
  405. font-weight: initial;
  406. margin-bottom: 0px;
  407. }
  408.  
  409. .NowcoderBetter_setting_list {
  410. display: flex;
  411. align-items: center;
  412. padding: 10px;
  413. margin: 5px 0px;
  414. background-color: #ffffff;
  415. border-bottom: 1px solid #c9c6c696;
  416. border-radius: 8px;
  417. justify-content: space-between;
  418. }
  419.  
  420. /*设置面板-radio*/
  421. .NowcoderBetter_setting_menu>label {
  422. display: flex;
  423. list-style-type: none;
  424. padding-inline-start: 0px;
  425. overflow-x: auto;
  426. max-width: 100%;
  427. margin: 0px;
  428. align-items: center;
  429. margin: 3px 0px;
  430. }
  431.  
  432. .NowcoderBetter_setting_menu_label_text {
  433. display: flex;
  434. border: 1px dashed #00aeeccc;
  435. height: 35px;
  436. width: 100%;
  437. color: gray;
  438. font-weight: 300;
  439. font-size: 14px;
  440. letter-spacing: 2px;
  441. padding: 7px;
  442. align-items: center;
  443. -webkit-box-sizing: border-box;
  444. -moz-box-sizing: border-box;
  445. box-sizing: border-box;
  446. }
  447.  
  448. input[type="radio"]:checked+.NowcoderBetter_setting_menu_label_text {
  449. background: #41e49930;
  450. border: 1px solid green;
  451. color: green;
  452. font-weight: 500;
  453. }
  454.  
  455. .NowcoderBetter_setting_menu>label input[type="radio"] {
  456. -webkit-appearance: none;
  457. appearance: none;
  458. list-style: none;
  459. padding: 0px !important;
  460. margin: 0px;
  461. }
  462.  
  463. .NowcoderBetter_setting_menu input[type="text"] {
  464. display: block;
  465. height: 25px !important;
  466. width: 100%;
  467. background-color: #ffffff;
  468. color: #727378;
  469. font-size: 12px;
  470. border-radius: 0.3rem;
  471. padding: 1px 5px !important;
  472. box-sizing: border-box;
  473. margin: 5px 0px 5px 0px;
  474. border: 1px solid #00aeeccc;
  475. box-shadow: 0 0 1px #0000004d;
  476. }
  477.  
  478. .NowcoderBetter_setting_menu input[type="text"]:focus-visible{
  479. border-style: solid;
  480. border-color: #3f51b5;
  481. outline: none;
  482. }
  483.  
  484. .NowcoderBetter_setting_menu_input {
  485. width: 100%;
  486. display: grid;
  487. margin-top: 5px;
  488. -webkit-box-sizing: border-box;
  489. -moz-box-sizing: border-box;
  490. box-sizing: border-box;
  491. }
  492. .NowcoderBetter_setting_menu input::placeholder {
  493. color: #727378;
  494. }
  495. .NowcoderBetter_setting_menu input.no_default::placeholder{
  496. color: #BDBDBD;
  497. }
  498. .NowcoderBetter_setting_menu input.is_null::placeholder{
  499. color: red;
  500. border-width: 1.5px;
  501. }
  502. .NowcoderBetter_setting_menu input.is_null{
  503. border-color: red;
  504. }
  505. .NowcoderBetter_setting_menu textarea {
  506. display: block;
  507. width: 100%;
  508. height: 60px;
  509. background-color: #ffffff;
  510. color: #727378;
  511. font-size: 12px;
  512. padding: 1px 5px !important;
  513. box-sizing: border-box;
  514. margin: 5px 0px 5px 0px;
  515. border: 1px solid #00aeeccc;
  516. box-shadow: 0 0 1px #0000004d;
  517. }
  518. .NowcoderBetter_setting_menu textarea:focus-visible{
  519. border-style: solid;
  520. border-color: #3f51b5;
  521. outline: none;
  522. }
  523. .NowcoderBetter_setting_menu textarea::placeholder{
  524. color: #BDBDBD;
  525. font-size: 14px;
  526. }
  527.  
  528. .NowcoderBetter_setting_menu #save {
  529. cursor: pointer;
  530. display: inline-flex;
  531. padding: 5px;
  532. background-color: #1aa06d;
  533. color: #ffffff;
  534. font-size: 14px;
  535. line-height: 1.5rem;
  536. font-weight: 500;
  537. justify-content: center;
  538. width: 100%;
  539. border-radius: 0.375rem;
  540. border: none;
  541. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  542. margin-top: 20px
  543. }
  544. .NowcoderBetter_setting_menu button#debug_button.debug_button {
  545. width: 18%;
  546. }
  547.  
  548. .NowcoderBetter_setting_menu span.tip {
  549. color: #999;
  550. font-size: 12px;
  551. font-weight: 500;
  552. padding: 5px 0px;
  553. }
  554. /*设置面板-tip*/
  555. .help_tip {
  556. margin-right: auto;
  557. }
  558. .help_tip .tip_text {
  559. display: none;
  560. position: absolute;
  561. color: #697e91;
  562. font-weight: 400;
  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: rgb(255, 153, 0);
  588. margin-left: 5px;
  589. margin-top: 3px;
  590. }
  591. #CFBetter_setting_menu .CFBetter_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. .wordsExceeded {
  601. z-index: 99999;
  602. box-shadow: 0px 0px 5px 1px rgb(0 0 0 / 10%), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  603. display: grid;
  604. position: fixed;
  605. top: 50%;
  606. left: 50%;
  607. transform: translate(-50%, -50%);
  608. border-radius: 4px;
  609. background-color: #ffffff;
  610. border: 1px solid #e4e7ed;
  611. color: #697e91;
  612. font-family: var(--vp-font-family-base);
  613. padding: 10px 20px 20px 20px;
  614. }
  615. .wordsExceeded button {
  616. display: inline-flex;
  617. justify-content: center;
  618. align-items: center;
  619. line-height: 1;
  620. white-space: nowrap;
  621. cursor: pointer;
  622. text-align: center;
  623. box-sizing: border-box;
  624. outline: none;
  625. transition: .1s;
  626. user-select: none;
  627. vertical-align: middle;
  628. -webkit-appearance: none;
  629. height: 24px;
  630. padding: 5px 11px;
  631. font-size: 12px;
  632. border-radius: 4px;
  633. color: #ffffff;
  634. background: #409eff;
  635. border-color: #409eff;
  636. border: none;
  637. margin-right: 12px;
  638. }
  639. .wordsExceeded button:hover{
  640. background-color:#79bbff;
  641. }
  642. .wordsExceeded .help-icon {
  643. margin: 0px 8px 0px 0px;
  644. height: 1em;
  645. width: 1em;
  646. line-height: 1em;
  647. display: inline-flex;
  648. justify-content: center;
  649. align-items: center;
  650. position: relative;
  651. fill: currentColor;
  652. font-size: inherit;
  653. }
  654. .wordsExceeded p {
  655. margin: 5px 0px;
  656. }
  657. /*更新检查*/
  658. div#update_panel {
  659. z-index: 9999;
  660. position: fixed;
  661. top: 50%;
  662. left: 50%;
  663. width: 240px;
  664. transform: translate(-50%, -50%);
  665. box-shadow: 0px 0px 4px 0px #0000004d;
  666. padding: 10px 20px 20px 20px;
  667. color: #444242;
  668. background-color: #f5f5f5;
  669. border: 1px solid #848484;
  670. border-radius: 8px;
  671. }
  672. div#update_panel #updating {
  673. cursor: pointer;
  674. display: inline-flex;
  675. padding: 3px;
  676. background-color: #1aa06d;
  677. color: #ffffff;
  678. font-size: 14px;
  679. line-height: 1.5rem;
  680. font-weight: 500;
  681. justify-content: center;
  682. width: 100%;
  683. border-radius: 0.375rem;
  684. border: none;
  685. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  686. }
  687. div#update_panel #updating a {
  688. text-decoration: none;
  689. color: white;
  690. display: flex;
  691. position: inherit;
  692. top: 0;
  693. left: 0;
  694. width: 100%;
  695. height: 22px;
  696. font-size: 14px;
  697. justify-content: center;
  698. align-items: center;
  699. }
  700. #skip_menu {
  701. display: flex;
  702. margin-top: 10px;
  703. justify-content: flex-end;
  704. align-items: center;
  705. }
  706. #skip_menu .help_tip {
  707. margin-right: 5px;
  708. margin-left: -5px;
  709. }
  710. #skip_menu .help-icon {
  711. color: #f44336;
  712. }
  713. /* 配置管理 */
  714. .embed-responsive {
  715. height: max-content;
  716. padding-bottom: 0px;
  717. }
  718. .config_bar {
  719. height: 70px;
  720. width: 100%;
  721. display: flex;
  722. justify-content: space-between;
  723. }
  724. li#add_button {
  725. cursor: pointer;
  726. height: 40px;
  727. border: 1px dashed #BDBDBD;
  728. border-radius: 8px;
  729. background-color: #fcfbfb36;
  730. color: #bdbdbd;
  731. font-size: 14px;
  732. align-items: center;
  733. justify-content: center;
  734. }
  735. li#add_button:hover {
  736. border: 1px dashed #03A9F4;
  737. background-color: #d7f0fb8c;
  738. color: #03A9F4;
  739. }
  740. div#config_bar_list {
  741. display: flex;
  742. width: 480px;
  743. border: 1px solid #c5cae9;
  744. border-radius: 8px;
  745. background-color: #f0f8ff;
  746. box-sizing: border-box;
  747. }
  748. div#config_bar_list input[type="radio"] {
  749. appearance: none;
  750. width: 0;
  751. height: 0;
  752. overflow: hidden;
  753. }
  754. div#config_bar_list input[type="radio"] {
  755. margin: 0px;
  756. }
  757. div#config_bar_list input[type=radio]:focus {
  758. outline: 0px;
  759. }
  760. label.config_bar_ul_li_text {
  761. display: flex;
  762. align-items: center;
  763. justify-content: center;
  764. max-width: 100%;
  765. height: 40px;
  766. overflow-x: auto;
  767. font-size: 14px;
  768. font-weight: 400;
  769. margin: 0px 4px;
  770. padding: 3px;
  771. border: 1px solid #dedede;
  772. border-radius: 10px;
  773. box-shadow: 0px 2px 4px 0px rgba(0,0,0,.05);
  774. box-sizing: border-box;
  775. }
  776. ul#config_bar_ul li button {
  777. background-color: #e6e6e6;
  778. color: #727378;
  779. height: 23px;
  780. font-size: 14px;
  781. border-radius: 0.3rem;
  782. padding: 1px 5px;
  783. margin: 5px;
  784. border: none;
  785. box-shadow: 0 0 1px #0000004d;
  786. }
  787. ul#config_bar_ul {
  788. display: flex;
  789. align-items: center;
  790. list-style-type: none;
  791. padding-inline-start: 0px;
  792. overflow-x: auto;
  793. max-width: 100%;
  794. margin: 0px;
  795. }
  796. ul#config_bar_ul li {
  797. width: 80px;
  798. display: grid;
  799. margin: 4px 4px;
  800. min-width: 100px;
  801. box-sizing: border-box;
  802. }
  803. label.config_bar_ul_li_text:hover {
  804. background-color: #eae4dc24;
  805. }
  806. input[type="radio"]:checked + .config_bar_ul_li_text {
  807. background: #41b3e430;
  808. border: 1px solid #5e7ce0;
  809. color: #5e7ce0;
  810. }
  811. ul#config_bar_ul::-webkit-scrollbar {
  812. width: 5px;
  813. height: 5px;
  814. }
  815. ul#config_bar_ul::-webkit-scrollbar-thumb {
  816. background-clip: padding-box;
  817. background-color: #d7d9e4;
  818. border-radius: 8px;
  819. }
  820. ul#config_bar_ul::-webkit-scrollbar-button:start:decrement {
  821. width: 4px;
  822. background-color: transparent;
  823. }
  824. ul#config_bar_ul::-webkit-scrollbar-button:end:increment {
  825. width: 4px;
  826. background-color: transparent;
  827. }
  828. ul#config_bar_ul::-webkit-scrollbar-track {
  829. background-color: #f1f1f1;
  830. border-radius: 5px;
  831. }
  832. label.config_bar_ul_li_text::-webkit-scrollbar {
  833. width: 5px;
  834. height: 7px;
  835. background-color: #aaa;
  836. }
  837. label.config_bar_ul_li_text::-webkit-scrollbar-thumb {
  838. background-clip: padding-box;
  839. background-color: #d7d9e4;
  840. }
  841. label.config_bar_ul_li_text::-webkit-scrollbar-track {
  842. background-color: #f1f1f1;
  843. }
  844. .config_bar_list_add_div {
  845. display: flex;
  846. height: 40px;
  847. margin: 4px 2px;
  848. }
  849. /* 修改菜单 */
  850. div#config_bar_menu {
  851. z-index: 99999;
  852. position: absolute;
  853. width: 60px;
  854. background: #ffffff;
  855. box-shadow: 1px 1px 4px 0px #0000004d;
  856. border: 0px solid rgba(0,0,0,0.04);
  857. border-radius: 4px;
  858. padding: 8px 0;
  859. }
  860. div.config_bar_menu_item {
  861. cursor: pointer;
  862. padding: 2px 6px;
  863. display: flex;
  864. justify-content: center;
  865. align-items: center;
  866. height: 32px;
  867. color: rgba(0,0,0,0.75);
  868. font-size: 14px;
  869. font-weight: 500;
  870. box-shadow: inset 0px 0px 0px 0px #8bb2d9;
  871. }
  872. div#config_bar_menu_edit:hover {
  873. background-color: #00aeec;
  874. color: white;
  875. }
  876. div#config_bar_menu_delete:hover {
  877. background-color: #FF5722;
  878. color: white;
  879. }
  880. /* 配置页面 */
  881. #config_edit_menu {
  882. z-index: 11000;
  883. width: 450px;
  884. }
  885. `);
  886.  
  887. // 获取cookie
  888. function getCookie(name) {
  889. const cookies = document.cookie.split(";");
  890. for (let i = 0; i < cookies.length; i++) {
  891. const cookie = cookies[i].trim();
  892. const [cookieName, cookieValue] = cookie.split("=");
  893.  
  894. if (cookieName === name) {
  895. return decodeURIComponent(cookieValue);
  896. }
  897. }
  898. return "";
  899. }
  900.  
  901. // 防抖函数
  902. function debounce(callback) {
  903. let timer;
  904. let immediateExecuted = false;
  905. const delay = 500;
  906. return function () {
  907. clearTimeout(timer);
  908. if (!immediateExecuted) { callback.call(this); immediateExecuted = true; }
  909. timer = setTimeout(() => { immediateExecuted = false; }, delay);
  910. };
  911. }
  912.  
  913. // 为元素添加鼠标拖动
  914. function addDraggable(element) {
  915. let isDragging = false;
  916. let initialX, initialY; // 元素的初始位置
  917. let startX, startY, offsetX, offsetY; // 鼠标起始位置,移动偏移量
  918. let isSpecialMouseDown = false; // 选取某些元素时不拖动
  919.  
  920. element.on('mousedown', function (e) {
  921. var elem = $(this);
  922. var elemOffset = elem.offset();
  923. var centerX = elemOffset.left + elem.outerWidth() / 2;
  924. var centerY = elemOffset.top + elem.outerHeight() / 2;
  925. initialX = centerX - window.pageXOffset;
  926. initialY = centerY - window.pageYOffset;
  927.  
  928. isDragging = true;
  929. startX = e.clientX;
  930. startY = e.clientY;
  931.  
  932. isSpecialMouseDown = $(e.target).is('label, p, input, textarea, span');
  933.  
  934. $('body').css('cursor', 'all-scroll');
  935. });
  936.  
  937.  
  938. $(document).on('mousemove', function (e) {
  939. if (!isDragging) return;
  940. // 不执行拖动操作
  941. if ($(e.target).is('label, p, input, textarea, span') || isSpecialMouseDown && !$(e.target).is('input, textarea')) return;
  942. e.preventDefault();
  943. offsetX = e.clientX - startX;
  944. offsetY = e.clientY - startY;
  945. element.css({ top: initialY + offsetY + 'px', left: initialX + offsetX + 'px' });
  946. });
  947.  
  948. $(document).on('mouseup', function () {
  949. isDragging = false;
  950. isSpecialMouseDown = false;
  951. $('body').css('cursor', 'default');
  952. });
  953. }
  954.  
  955. // 更新检查
  956. (function checkScriptVersion() {
  957. function compareVersions(version1 = "0", version2 = "0") {
  958. const v1Array = String(version1).split(".");
  959. const v2Array = String(version2).split(".");
  960. const minLength = Math.min(v1Array.length, v2Array.length);
  961. let result = 0;
  962. for (let i = 0; i < minLength; i++) {
  963. const curV1 = Number(v1Array[i]);
  964. const curV2 = Number(v2Array[i]);
  965. if (curV1 > curV2) {
  966. result = 1;
  967. break;
  968. } else if (curV1 < curV2) {
  969. result = -1;
  970. break;
  971. }
  972. }
  973. if (result === 0 && v1Array.length !== v2Array.length) {
  974. const v1IsBigger = v1Array.length > v2Array.length;
  975. const maxLenArray = v1IsBigger ? v1Array : v2Array;
  976. for (let i = minLength; i < maxLenArray.length; i++) {
  977. const curVersion = Number(maxLenArray[i]);
  978. if (curVersion > 0) {
  979. v1IsBigger ? result = 1 : result = -1;
  980. break;
  981. }
  982. }
  983. }
  984. return result;
  985. }
  986.  
  987. GM_xmlhttpRequest({
  988. method: "GET",
  989. url: "https://greasyfork.org/zh-CN/scripts/473210.json",
  990. timeout: 10 * 1e3,
  991. onload: function (response) {
  992. const scriptData = JSON.parse(response.responseText);
  993. const skipUpdate = getCookie("skipUpdate");
  994.  
  995. if (
  996. scriptData.name === GM_info.script.name &&
  997. compareVersions(scriptData.version, GM_info.script.version) === 1 &&
  998. skipUpdate !== "true"
  999. ) {
  1000. const styleElement = GM_addStyle(darkenPageStyle);
  1001. $("body").append(`
  1002. <div id='update_panel'>
  1003. <h3>${GM_info.script.name}有新版本!</h3>
  1004. <hr>
  1005. <div class='update_panel_menu'>
  1006. <span class ='tip'>版本信息:${GM_info.script.version} ${scriptData.version}</span>
  1007. </div>
  1008. <br>
  1009. <div id="skip_menu">
  1010. <div class="help_tip">
  1011. `+ helpCircleHTML + `
  1012. <div class="tip_text">
  1013. <p><b>更新遇到了问题?</b></p>
  1014. <p>由于 Greasyfork 平台的原因,当新版本刚发布时,点击 Greasyfork 上的更新按钮<u>可能</u>会出现<u>实际更新/安装的却是上一个版本</u>的情况</p>
  1015. <p>通常你只需要稍等几分钟,然后再次前往更新/安装即可</p>
  1016. <p>你也可以<u>点击下方按钮,在本次浏览器会话期间将不再提示更新</u></p>
  1017. <button id='skip_update' class='html2mdButton'>暂不更新</button>
  1018. </div>
  1019. </div>
  1020. <button id='updating'><a target="_blank" href="${scriptData.url}">更新</a></button>
  1021. </div>
  1022. </div>
  1023. `);
  1024.  
  1025. $("#skip_update").click(function () {
  1026. document.cookie = "skipUpdate=true; expires=session; path=/";
  1027. styleElement.remove();
  1028. $("#update_panel").remove();
  1029. });
  1030. }
  1031. }
  1032. });
  1033.  
  1034. })();
  1035.  
  1036. // 设置面板
  1037. $(document).ready(function () {
  1038. var htmlContent = "<button class='html2mdButton NowcoderBetter_setting'>Nowcoder Better设置</button>";
  1039. if ($('.acm-nav-info').length > 0) $('.acm-nav-info > li:last-child').after("<li class='dropdown'>" + htmlContent + "</li>");
  1040. else $('.header-bar .header-right > :last-child').after(htmlContent);
  1041. });
  1042.  
  1043. // 配置管理函数
  1044. function setupConfigManagement(element, tempConfig, structure, configHTML, checkable) {
  1045. let counter = 0;
  1046. createControlBar();
  1047. createContextMenu();
  1048.  
  1049. // 键值对校验
  1050. function valiKeyValue(value) {
  1051. const keyValuePairs = value.split('\n');
  1052. const regex = /^[a-zA-Z0-9_-]+\s*:\s*[a-zA-Z0-9_-]+$/;
  1053. for (let i = 0; i < keyValuePairs.length; i++) {
  1054. if (!regex.test(keyValuePairs[i])) {
  1055. return false;
  1056. }
  1057. }
  1058. return true;
  1059. }
  1060.  
  1061. // 新增数据
  1062. function onAdd() {
  1063. const styleElement = createWindow();
  1064.  
  1065. const settingMenu = $("#config_edit_menu");
  1066. settingMenu.on("click", "#save", () => {
  1067. const config = {};
  1068. let allFieldsValid = true;
  1069. for (const key in structure) {
  1070. let value = $(key).val();
  1071. if (value || $(key).attr('require') === 'false') {
  1072. config[structure[key]] = $(key).val();
  1073. $(key).removeClass('is_null');
  1074. } else {
  1075. $(key).addClass('is_null');
  1076. allFieldsValid = false;
  1077. }
  1078. }
  1079.  
  1080. // 校验提示
  1081. for (let i = 0, len = checkable.length; i < len; i++) {
  1082. let value = $(checkable[i]).val();
  1083. if (value && !valiKeyValue(value)) {
  1084. if (!$(checkable[i]).prev('span.text-error').length) {
  1085. $(checkable[i]).before('<span class="text-error" style="color: red;">格式不符或存在非法字符</span>');
  1086. }
  1087. allFieldsValid = false;
  1088. } else {
  1089. $(checkable[i]).prev('span.text-error').remove();
  1090. }
  1091. }
  1092.  
  1093. if (!allFieldsValid) return;
  1094. tempConfig.configurations.push(config);
  1095.  
  1096. const list = $("#config_bar_ul");
  1097. createListItemElement(config[structure['#note']]).insertBefore($('#add_button'));
  1098.  
  1099. settingMenu.remove();
  1100. $(styleElement).remove();
  1101. });
  1102.  
  1103. settingMenu.on("click", ".btn-close", () => {
  1104. settingMenu.remove();
  1105. $(styleElement).remove();
  1106. });
  1107. }
  1108.  
  1109. // 编辑数据
  1110. function onEdit() {
  1111. const menu = $("#config_bar_menu");
  1112. menu.css({ display: "none" });
  1113.  
  1114. const list = $("#config_bar_ul");
  1115. const index = Array.from(list.children()).indexOf(this);
  1116.  
  1117. const styleElement = createWindow();
  1118.  
  1119. const settingMenu = $("#config_edit_menu");
  1120. const configAtIndex = tempConfig.configurations[index];
  1121.  
  1122. if (configAtIndex) {
  1123. for (const key in structure) {
  1124. $(key).val(configAtIndex[structure[key]]);
  1125. }
  1126. }
  1127.  
  1128. settingMenu.on("click", "#save", () => {
  1129. const config = {};
  1130. let allFieldsValid = true;
  1131. for (const key in structure) {
  1132. let value = $(key).val();
  1133. if (value || $(key).attr('require') === 'false') {
  1134. config[structure[key]] = $(key).val();
  1135. $(key).removeClass('is_null');
  1136. } else {
  1137. $(key).addClass('is_null');
  1138. allFieldsValid = false;
  1139. }
  1140. }
  1141. // 校验提示
  1142. for (let i = 0, len = checkable.length; i < len; i++) {
  1143. let value = $(checkable[i]).val();
  1144. if (value && !valiKeyValue(value)) {
  1145. if (!$(checkable[i]).prev('span.text-error').length) {
  1146. $(checkable[i]).before('<span class="text-error" style="color: red;">格式不符或存在非法字符</span>');
  1147. }
  1148. allFieldsValid = false;
  1149. } else {
  1150. $(checkable[i]).prev('span.text-error').remove();
  1151. }
  1152. }
  1153.  
  1154. if (!allFieldsValid) return;
  1155. tempConfig.configurations[index] = config;
  1156.  
  1157. settingMenu.remove();
  1158. $(styleElement).remove();
  1159. menu.css({ display: "none" });
  1160.  
  1161. list.children().eq(index).find("label").text(config.note);
  1162. });
  1163.  
  1164. // 关闭按钮
  1165. settingMenu.on("click", ".btn-close", () => {
  1166. settingMenu.remove();
  1167. $(styleElement).remove();
  1168. });
  1169. }
  1170.  
  1171. // 删除数据
  1172. function onDelete() {
  1173. const menu = $("#config_bar_menu");
  1174. menu.css({ display: "none" });
  1175.  
  1176. const list = $("#config_bar_ul");
  1177. const index = Array.from(list.children()).indexOf(this);
  1178.  
  1179. tempConfig.configurations.splice(index, 1);
  1180.  
  1181. list.children().eq(index).remove();
  1182. }
  1183.  
  1184. // 创建编辑窗口
  1185. function createWindow() {
  1186. const styleElement = GM_addStyle(darkenPageStyle2);
  1187. $("body").append(configHTML);
  1188. addDraggable($('#config_edit_menu'));
  1189. return styleElement;
  1190. }
  1191.  
  1192. // 创建控制面板
  1193. function createControlBar() {
  1194. $(element).append(`
  1195. <div id='configControlTip' style='color:red;'></div>
  1196. <div class='config_bar'>
  1197. <div class='config_bar_list' id='config_bar_list'>
  1198. <ul class='config_bar_ul' id='config_bar_ul'></ul>
  1199. </div>
  1200. </div>
  1201. `);
  1202. }
  1203.  
  1204. // 创建右键菜单
  1205. function createContextMenu() {
  1206. const menu = $("<div id='config_bar_menu' style='display: none;'></div>");
  1207. menu.html(`
  1208. <div class='config_bar_menu_item' id='config_bar_menu_edit'>修改</div>
  1209. <div class='config_bar_menu_item' id='config_bar_menu_delete'>删除</div>
  1210. `);
  1211. $("body").append(menu);
  1212. }
  1213.  
  1214. // 创建新的li元素
  1215. function createListItemElement(text) {
  1216. const li = $("<li></li>");
  1217. const radio = $("<input type='radio' name='config_item'></input>").appendTo(li);
  1218. radio.attr("value", counter).attr("id", counter++);
  1219. const label = $("<label class='config_bar_ul_li_text'></label>").text(text).attr("for", radio.attr("value")).appendTo(li);
  1220.  
  1221. // 添加右键菜单
  1222. li.on("contextmenu", function (event) {
  1223. event.preventDefault();
  1224. const menu = $("#config_bar_menu");
  1225. menu.css({ display: "block", left: event.pageX, top: event.pageY });
  1226.  
  1227. const deleteItem = $("#config_bar_menu_delete");
  1228. const editItem = $("#config_bar_menu_edit");
  1229.  
  1230. // 移除旧事件
  1231. deleteItem.off("click");
  1232. editItem.off("click");
  1233.  
  1234. deleteItem.on("click", onDelete.bind(this));
  1235. editItem.on("click", onEdit.bind(this));
  1236.  
  1237. $(document).one("click", (event) => {
  1238. if (!menu.get(0).contains(event.target)) {
  1239. menu.css({ display: "none" });
  1240. deleteItem.off("click", onDelete);
  1241. editItem.off("click", onEdit);
  1242. }
  1243. });
  1244. });
  1245.  
  1246.  
  1247. return li;
  1248. }
  1249.  
  1250. // 渲染列表
  1251. function renderList() {
  1252. const listContainer = $("#config_bar_list");
  1253. const list = $("#config_bar_ul");
  1254. list.empty();
  1255. tempConfig.configurations.forEach((item) => {
  1256. list.append(createListItemElement(item[structure['#note']]));
  1257. });
  1258.  
  1259. list.append(`
  1260. <li id='add_button'>
  1261. <span>+ 添加</span>
  1262. </li>
  1263. `);
  1264. const addItem = $('#add_button');
  1265. addItem.on("click", onAdd);
  1266. };
  1267.  
  1268. renderList();
  1269. return tempConfig;
  1270. }
  1271.  
  1272. const NowcoderBetterSettingMenuHTML = `
  1273. <div id='NowcoderBetter_setting_menu' class='NowcoderBetter_setting_menu'>
  1274. <div class="tool-box">
  1275. <button class="btn-close">×</button>
  1276. </div>
  1277. <h3>基本设置</h3>
  1278. <hr>
  1279. <div class='NowcoderBetter_setting_list'>
  1280. <label for="hoverTargetAreaDisplay">显示目标区域范围</label>
  1281. <div class="help_tip">
  1282. `+ helpCircleHTML + `
  1283. <div class="tip_text">
  1284. <p>开启后当鼠标悬浮在 MD视图/复制/翻译 按钮上时,会显示其目标区域的范围</p>
  1285. </div>
  1286. </div>
  1287. <input type="checkbox" id="hoverTargetAreaDisplay" name="hoverTargetAreaDisplay">
  1288. </div>
  1289. <div class='NowcoderBetter_setting_list'>
  1290. <label for="enableSegmentedTranslation">分段翻译</label>
  1291. <div class="help_tip">
  1292. `+ helpCircleHTML + `
  1293. <div class="tip_text">
  1294. <p>分段翻译会对区域内的每一个&#60;&#112;&#47;&#62;和&#60;&#105;&#47;&#62;标签依次进行翻译,</p>
  1295. <p>这通常在翻译<strong>长篇博客</strong>或者<strong>超长的题目</strong>时很有用。</p>
  1296. <p><u>注意:开启分段翻译会产生如下问题:</u></p>
  1297. <p>- 使得翻译接口无法知晓整个文本的上下文信息,会降低翻译质量。</p>
  1298. <p>- 会有<strong>部分内容不会被翻译</strong>,因为它们不是&#60;&#112;&#47;&#62;或&#60;&#105;&#47;&#62;标签</p>
  1299. </div>
  1300. </div>
  1301. <input type="checkbox" id="enableSegmentedTranslation" name="enableSegmentedTranslation">
  1302. </div>
  1303. <h3>翻译设置</h3>
  1304. <hr>
  1305. <label>
  1306. <input type='radio' name='translation' value='deepl'>
  1307. <span class='NowcoderBetter_setting_menu_label_text'>deepl翻译</span>
  1308. </label>
  1309. <label>
  1310. <input type='radio' name='translation' value='youdao'>
  1311. <span class='NowcoderBetter_setting_menu_label_text'>有道翻译</span>
  1312. </label>
  1313. <label>
  1314. <input type='radio' name='translation' value='google'>
  1315. <span class='NowcoderBetter_setting_menu_label_text'>Google翻译</span>
  1316. </label>
  1317. <label>
  1318. <input type='radio' name='translation' value='openai'>
  1319. <span class='NowcoderBetter_setting_menu_label_text'>使用ChatGPT翻译(API)
  1320. <div class="help_tip">
  1321. `+ helpCircleHTML + `
  1322. <div class="tip_text">
  1323. <p><b>请在下方选定你想使用的配置信息</b></p>
  1324. <p>脚本的所有请求均在本地完成</p>
  1325. </div>
  1326. </div>
  1327. </span>
  1328. </label>
  1329. <div class='NowcoderBetter_setting_menu_input' id='openai' style='display: none;'>
  1330. <div id="chatgpt-config"></div>
  1331. </div>
  1332. <button id='save'>保存</button>
  1333. </div>
  1334. `;
  1335.  
  1336. const chatgptConfigEditHTML = `
  1337. <div class='NowcoderBetter_setting_menu' id='config_edit_menu'>
  1338. <div class="tool-box">
  1339. <button class="btn-close">×</button>
  1340. </div>
  1341. <h4>配置</h4>
  1342. <h5>基本</h5>
  1343. <hr>
  1344. <label for='note'>
  1345. <span class="input_label">备注:</span>
  1346. </label>
  1347. <input type='text' id='note' class='no_default' placeholder='请为该配置取一个备注名' require = true>
  1348. <label for='openai_model'>
  1349. <div style="display: flex;align-items: center;">
  1350. <span class="input_label">模型:</span>
  1351. <div class="help_tip">
  1352. `+ helpCircleHTML + `
  1353. <div class="tip_text">
  1354. <p>留空则默认为:gpt-3.5-turbo</p>
  1355. <p>模型列表请查阅<a target="_blank" href="https://platform.openai.com/docs/models">OpenAI官方文档</a></p>
  1356. <p><strong>此外,如果您使用的是服务商提供的代理API,请确认服务商是否支持对应模型</strong></p>
  1357. </div>
  1358. </div>
  1359. </div>
  1360. </label>
  1361. <input type='text' id='openai_model' placeholder='gpt-3.5-turbo' require = false>
  1362. <label for='openai_key'>
  1363. <div style="display: flex;align-items: center;">
  1364. <span class="input_label">KEY:</span>
  1365. <div class="help_tip">
  1366. `+ helpCircleHTML + `
  1367. <div class="tip_text">
  1368. <p>您需要输入自己的OpenAI key,<a target="_blank" href="https://platform.openai.com/account/usage">官网</a></p>
  1369. <p><b>如果您使用的是服务商提供的代理API,则应该填写服务商提供的 Key</b></p>
  1370. </div>
  1371. </div>
  1372. </div>
  1373. </label>
  1374. <input type='text' id='openai_key' class='no_default' placeholder='请输入KEY' require = true>
  1375. <label for='openai_proxy'>
  1376. <div style="display: flex;align-items: center;">
  1377. <span class="input_label">Proxy API:</span>
  1378. <div class="help_tip">
  1379. `+ helpCircleHTML + `
  1380. <div class="tip_text">
  1381. <p>留空则默认为OpenAI官方API</p>
  1382. <p>您也可以填写指定的API来代理访问OpenAIAPI,</p>
  1383. <p>如果您使用的是服务商提供的代理APIKEY,则这里应该填写其提供的<strong>完整</strong>API地址,详请阅读脚本说明</p>
  1384. <p><strong>由于您指定了自定义的APITampermonkey会对您的跨域请求进行警告,您需要自行授权</strong></p>
  1385. </div>
  1386. </div>
  1387. </div>
  1388. </label>
  1389. <input type='text' id='openai_proxy' placeholder='https://api.openai.com/v1/chat/completions' require = false>
  1390. <h5>高级</h5>
  1391. <hr>
  1392. <label for='_header'>
  1393. <div style="display: flex;align-items: center;">
  1394. <span class="input_label">自定义header</span>
  1395. <div class="help_tip">
  1396. `+ helpCircleHTML + `
  1397. <div class="tip_text">
  1398. <p>格式样例:</p>
  1399. <div style="border: 1px solid #795548; padding: 10px;">
  1400. <p>name1 : 123<br>name2 : cccc</p>
  1401. </div>
  1402. </div>
  1403. </div>
  1404. </div>
  1405. </label>
  1406. <textarea id="_header" placeholder='(选填)您可以在这里填写向请求header中额外添加的键值对' require = false></textarea>
  1407. <label for='_data'>
  1408. <div style="display: flex;align-items: center;">
  1409. <span class="input_label">自定义data</span>
  1410. <div class="help_tip">
  1411. `+ helpCircleHTML + `
  1412. <div class="tip_text">
  1413. <p>格式样例:</p>
  1414. <div style="border: 1px solid #795548; padding: 10px;">
  1415. <p>name1 : 123<br>name2 : cccc</p>
  1416. </div>
  1417. </div>
  1418. </div>
  1419. </div>
  1420. </label>
  1421. <textarea id="_data" placeholder='(选填)您可以在这里填写向请求data中额外添加的键值对' require = false></textarea>
  1422. <button id='save'>保存</button>
  1423. </div>
  1424. `;
  1425.  
  1426. $(document).ready(function () {
  1427. const $settingBtns = $(".NowcoderBetter_setting");
  1428. $settingBtns.click(() => {
  1429. const styleElement = GM_addStyle(darkenPageStyle);
  1430. $settingBtns.prop("disabled", true).addClass("open");
  1431. $("body").append(NowcoderBetterSettingMenuHTML);
  1432.  
  1433. // 窗口初始化
  1434. addDraggable($('#NowcoderBetter_setting_menu'));
  1435. const chatgptStructure = {
  1436. '#note': 'note',
  1437. '#openai_model': 'model',
  1438. '#openai_key': 'key',
  1439. '#openai_proxy': 'proxy',
  1440. '#_header': '_header',
  1441. '#_data': '_data',
  1442. }
  1443. const checkable = [
  1444. '#_header',
  1445. '#_data',
  1446. ]
  1447.  
  1448. // 缓存配置信息
  1449. let tempConfig = GM_getValue('chatgpt-config');
  1450. tempConfig = setupConfigManagement('#chatgpt-config', tempConfig, chatgptStructure, chatgptConfigEditHTML, checkable);
  1451.  
  1452. // 状态切换
  1453. $("#enableSegmentedTranslation").prop("checked", GM_getValue("enableSegmentedTranslation") === true);
  1454. $("#hoverTargetAreaDisplay").prop("checked", GM_getValue("hoverTargetAreaDisplay") === true);
  1455. $("input[name='translation'][value='" + translation + "']").prop("checked", true);
  1456. $("input[name='translation']").css("color", "gray");
  1457. if (translation == "openai") {
  1458. $("#openai").show();
  1459. if (tempConfig) {
  1460. $("input[name='config_item'][value='" + tempConfig.choice + "']").prop("checked", true);
  1461. }
  1462. }
  1463.  
  1464. // 翻译选择情况监听
  1465. $("input[name='translation']").change(function () {
  1466. var selected = $(this).val(); // 获取当前选中的值
  1467. if (selected === "openai") {
  1468. $("#openai").show();
  1469. if (tempConfig) {
  1470. $("input[name='config_item'][value='" + tempConfig.choice + "']").prop("checked", true);
  1471. }
  1472. } else {
  1473. $("#openai").hide();
  1474. }
  1475. });
  1476. // 配置选择情况监听
  1477. $("input[name='config_item']").change(function () {
  1478. var selected = $(this).val(); // 获取当前选中的值
  1479. tempConfig.choice = selected;
  1480. });
  1481.  
  1482. const $settingMenu = $(".NowcoderBetter_setting_menu");
  1483.  
  1484. $("#save").click(debounce(function () {
  1485. const settings = {
  1486. hoverTargetAreaDisplay: $("#hoverTargetAreaDisplay").prop("checked"),
  1487. enableSegmentedTranslation: $("#enableSegmentedTranslation").prop("checked"),
  1488. translation: $("input[name='translation']:checked").val()
  1489. };
  1490. if (settings.translation === "openai") {
  1491. var selectedIndex = $('input[name="config_item"]:checked').closest('li').index();
  1492. if (selectedIndex === -1) {
  1493. $('#configControlTip').text('请选择一项配置!')
  1494. return;
  1495. }
  1496. }
  1497. GM_setValue('chatgpt-config', tempConfig);
  1498. let refreshPage = false; // 是否需要刷新页面
  1499. for (const [key, value] of Object.entries(settings)) {
  1500. if (!refreshPage && !(key == 'enableSegmentedTranslation' || key == 'translation')) {
  1501. if (GM_getValue(key) != value) refreshPage = true;
  1502. }
  1503. GM_setValue(key, value);
  1504. }
  1505. if (refreshPage) location.reload();
  1506. else {
  1507. // 更新配置信息
  1508. enableSegmentedTranslation = settings.enableSegmentedTranslation;
  1509. translation = settings.translation;
  1510. if (settings.translation === "openai") {
  1511. var selectedIndex = $('#config_bar_ul li input[type="radio"]:checked').closest('li').index();
  1512. if (selectedIndex !== opneaiConfig.choice) {
  1513. opneaiConfig = GM_getValue("chatgpt-config");
  1514. const configAtIndex = opneaiConfig.configurations[selectedIndex];
  1515. openai_model = configAtIndex.model;
  1516. openai_key = configAtIndex.key;
  1517. openai_proxy = configAtIndex.proxy;
  1518. openai_header = configAtIndex._header ?
  1519. configAtIndex._header.split("\n").map(header => {
  1520. const [key, value] = header.split(":");
  1521. return { [key.trim()]: value.trim() };
  1522. }) : [];
  1523. openai_data = configAtIndex._data ?
  1524. configAtIndex._data.split("\n").map(header => {
  1525. const [key, value] = header.split(":");
  1526. return { [key.trim()]: value.trim() };
  1527. }) : [];
  1528. }
  1529. }
  1530. }
  1531.  
  1532. $settingMenu.remove();
  1533. $settingBtns.prop("disabled", false).removeClass("open");
  1534. $(styleElement).remove();
  1535. }));
  1536.  
  1537. // 关闭
  1538. $settingMenu.on("click", ".btn-close", () => {
  1539. $settingMenu.remove();
  1540. $settingBtns.prop("disabled", false).removeClass("open");
  1541. $(styleElement).remove();
  1542. });
  1543. });
  1544. });
  1545.  
  1546. // html2md转换/处理规则
  1547. var turndownService = new TurndownService({ bulletListMarker: '-', escape: (text) => text });
  1548. var turndown = turndownService.turndown;
  1549.  
  1550. // 保留原始
  1551. turndownService.keep(['del']);
  1552.  
  1553. turndownService.addRule('removeByClass', {
  1554. filter: function (node) {
  1555. return node.classList.contains('html2md-panel') ||
  1556. node.classList.contains('div-btn-copy') ||
  1557. node.classList.contains('btn-copy') ||
  1558. node.classList.contains('code-copy-btn') ||
  1559. node.classList.contains('overlay')
  1560. },
  1561. replacement: function () {
  1562. return '';
  1563. }
  1564. });
  1565.  
  1566. // inline math
  1567. turndownService.addRule('inline-math1', {
  1568. filter: function (node, options) {
  1569. return node.tagName.toLowerCase() == "span" && node.className == "katex";
  1570. },
  1571. replacement: function (content, node) {
  1572. var text = $(node).find('annotation').text();
  1573. if (text == "") {
  1574. text = $(node).find('math').contents().filter(function () {
  1575. return this.nodeType === Node.TEXT_NODE;
  1576. }).text();
  1577. }
  1578. return "$" + text + "$";
  1579. }
  1580. });
  1581. turndownService.addRule('inline-math2', {
  1582. filter: function (node, options) {
  1583. return node.tagName.toLowerCase() == "span" && node.className == "katex-mathml";
  1584. },
  1585. replacement: function (content, node) {
  1586. var text = "";
  1587. $(node).contents().each(function () {
  1588. if (this.nodeType === Node.TEXT_NODE) {
  1589. text += $(this).text();
  1590. }
  1591. });
  1592. return "$" + text + "$";
  1593. }
  1594. });
  1595.  
  1596. // block math
  1597. turndownService.addRule('block-math', {
  1598. filter: function (node, options) {
  1599. return node.tagName.toLowerCase() == "span" && node.className == "katex-display";
  1600. },
  1601. replacement: function (content, node) {
  1602. return "\n$$\n" + $(node).find('annotation').text() + "\n$$\n";
  1603. }
  1604. });
  1605.  
  1606. // pre
  1607. turndownService.addRule('pre', {
  1608. filter: function (node, options) {
  1609. return node.tagName.toLowerCase() == "pre";
  1610. },
  1611. replacement: function (content, node) {
  1612. return "```\n" + content + "```\n";
  1613. }
  1614. });
  1615.  
  1616. // bordertable
  1617. turndownService.addRule('bordertable', {
  1618. filter: 'table',
  1619. replacement: function (content, node) {
  1620. if (node.classList.contains('table')) {
  1621. var output = [],
  1622. thead = '',
  1623. trs = node.querySelectorAll('tr');
  1624. if (trs.length > 0) {
  1625. var ths = trs[0].querySelectorAll('th');
  1626. if (ths.length > 0) {
  1627. thead = '| ' + Array.from(ths).map(th => turndownService.turndown(th.innerHTML.trim())).join(' | ') + ' |\n'
  1628. + '| ' + Array.from(ths).map(() => ' --- ').join('|') + ' |\n';
  1629. }
  1630. }
  1631. var rows = node.querySelectorAll('tr');
  1632. Array.from(rows).forEach(function (row, i) {
  1633. if (i > 0) {
  1634. var cells = row.querySelectorAll('td,th');
  1635. var trow = '| ' + Array.from(cells).map(cell => turndownService.turndown(cell.innerHTML.trim())).join(' | ') + ' |';
  1636. output.push(trow);
  1637. }
  1638. });
  1639. return thead + output.join('\n');
  1640. } else {
  1641. return content;
  1642. }
  1643. }
  1644. });
  1645.  
  1646.  
  1647. // 随机数生成
  1648. function getRandomNumber(numDigits) {
  1649. let min = Math.pow(10, numDigits - 1);
  1650. let max = Math.pow(10, numDigits) - 1;
  1651. return Math.floor(Math.random() * (max - min + 1)) + min;
  1652. }
  1653.  
  1654. // 按钮面板
  1655. function addButtonPanel(parent, suffix, type, is_simple = false) {
  1656. let htmlString = `<div class='html2md-panel'>
  1657. <button class='html2mdButton html2md-view${suffix}'>MarkDown视图</button>
  1658. <button class='html2mdButton html2md-cb${suffix}'>Copy</button>
  1659. <button class='html2mdButton translateButton${suffix}'>翻译</button>
  1660. </div>`;
  1661. if (type === "this_level") {
  1662. $(parent).before(htmlString);
  1663. } else if (type === "child_level") {
  1664. $(parent).prepend(htmlString);
  1665. }
  1666. if (is_simple) {
  1667. $('.html2md-panel').find('.html2mdButton.html2md-view' + suffix + ', .html2mdButton.html2md-cb' + suffix).remove();
  1668. }
  1669. }
  1670.  
  1671. function addButtonWithHTML2MD(parent, suffix, type) {
  1672. $(document).on("click", ".html2md-view" + suffix, function () {
  1673. var target, removedChildren = $();
  1674. if (type === "this_level") {
  1675. target = $(".html2md-view" + suffix).parent().next().get(0);
  1676. } else if (type === "child_level") {
  1677. target = $(".html2md-view" + suffix).parent().parent().get(0);
  1678. removedChildren = $(".html2md-view" + suffix).parent().parent().children(':first').detach();
  1679. }
  1680. if (target.viewmd) {
  1681. target.viewmd = false;
  1682. $(this).text("MarkDown视图");
  1683. $(this).removeClass("mdViewed");
  1684. $(target).html(target.original_html);
  1685. } else {
  1686. target.viewmd = true;
  1687. if (!target.original_html) {
  1688. target.original_html = $(target).html();
  1689. }
  1690. if (!target.markdown) {
  1691. target.markdown = turndownService.turndown($(target).html());
  1692. }
  1693. $(this).text("原始内容");
  1694. $(this).addClass("mdViewed");
  1695. $(target).html(`<span class="mdViewContent" oninput="$(this).parent().get(0).markdown=this.value;" style="width:auto; height:auto;">${target.markdown}</span>`);
  1696. }
  1697. // 恢复删除的元素
  1698. if (removedChildren) $(target).prepend(removedChildren);
  1699. });
  1700. }
  1701.  
  1702. function addButtonWithHTML2MD(parent, suffix, type) {
  1703. $(document).on("click", ".html2md-view" + suffix, debounce(function () {
  1704. var target, removedChildren = $();
  1705. if (type === "this_level") {
  1706. target = $(".html2md-view" + suffix).parent().next().get(0);
  1707. } else if (type === "child_level") {
  1708. target = $(".html2md-view" + suffix).parent().parent().get(0);
  1709. removedChildren = $(".html2md-view" + suffix).parent().parent().children(':first').detach();
  1710. }
  1711. if (target.viewmd) {
  1712. target.viewmd = false;
  1713. $(this).text("MarkDown视图");
  1714. $(this).removeClass("mdViewed");
  1715. $(target).html(target.original_html);
  1716. } else {
  1717. target.viewmd = true;
  1718. if (!target.original_html) {
  1719. target.original_html = $(target).html();
  1720. }
  1721. if (!target.markdown) {
  1722. target.markdown = turndownService.turndown($(target).html());
  1723. }
  1724. $(this).text("原始内容");
  1725. $(this).addClass("mdViewed");
  1726. $(target).html(`<span class="mdViewContent" oninput="$(this).parent().get(0).markdown=this.value;" style="width:auto; height:auto;">${target.markdown}</span>`);
  1727. }
  1728. // 恢复删除的元素
  1729. if (removedChildren) $(target).prepend(removedChildren);
  1730. }));
  1731.  
  1732. if (hoverTargetAreaDisplay) {
  1733. var previousCSS;
  1734. $(document).on("mouseover", ".html2md-view" + suffix, function () {
  1735. var target;
  1736.  
  1737. if (type === "this_level") {
  1738. target = $(".html2md-view" + suffix).parent().next().get(0);
  1739. } else if (type === "child_level") {
  1740. target = $(".html2md-view" + suffix).parent().parent().get(0);
  1741. }
  1742.  
  1743. $(target).append('<div class="overlay">目标转换区域</div>');
  1744. previousCSS = {
  1745. "position": $(target).css("position"),
  1746. "display": $(target).css("display")
  1747. };
  1748. $(target).css({
  1749. "position": "relative",
  1750. "display": "block"
  1751. });
  1752.  
  1753. $(".html2md-view" + suffix).parent().css({
  1754. "position": "relative",
  1755. "z-index": "99999"
  1756. })
  1757. });
  1758.  
  1759. $(document).on("mouseout", ".html2md-view" + suffix, function () {
  1760. var target;
  1761.  
  1762. if (type === "this_level") {
  1763. target = $(".html2md-view" + suffix).parent().next().get(0);
  1764. } else if (type === "child_level") {
  1765. target = $(".html2md-view" + suffix).parent().parent().get(0);
  1766. }
  1767.  
  1768. $(target).find('.overlay').remove();
  1769. $(target).css(previousCSS);
  1770. $(".html2md-view" + suffix).parent().css({
  1771. "position": "static"
  1772. })
  1773. });
  1774. }
  1775. }
  1776.  
  1777. function addButtonWithCopy(parent, suffix, type) {
  1778. $(document).on("click", ".html2md-cb" + suffix, debounce(function () {
  1779. var target, removedChildren;
  1780. if (type === "this_level") {
  1781. target = $(".translateButton" + suffix).parent().next().eq(0).clone();
  1782. } else if (type === "child_level") {
  1783. target = $(".translateButton" + suffix).parent().parent().eq(0).clone();
  1784. $(target).children(':first').remove();
  1785. }
  1786. if ($(target).find('.mdViewContent').length <= 0) {
  1787. text = turndownService.turndown($(target).html());
  1788. } else {
  1789. text = $(target).find('.mdViewContent').text();
  1790. }
  1791. GM_setClipboard(text);
  1792. $(this).addClass("copied");
  1793. $(this).text("Copied");
  1794. // 更新复制按钮文本
  1795. setTimeout(() => {
  1796. $(this).removeClass("copied");
  1797. $(this).text("Copy");
  1798. }, 2000);
  1799. $(target).remove();
  1800. }));
  1801.  
  1802. if (hoverTargetAreaDisplay) {
  1803. var previousCSS;
  1804. $(document).on("mouseover", ".html2md-cb" + suffix, function () {
  1805. var target;
  1806.  
  1807. if (type === "this_level") {
  1808. target = $(".html2md-cb" + suffix).parent().next().get(0);
  1809. } else if (type === "child_level") {
  1810. target = $(".html2md-cb" + suffix).parent().parent().get(0);
  1811. }
  1812.  
  1813. $(target).append('<div class="overlay">目标复制区域</div>');
  1814. previousCSS = {
  1815. "position": $(target).css("position"),
  1816. "display": $(target).css("display")
  1817. };
  1818.  
  1819. $(target).css({
  1820. "position": "relative",
  1821. "display": "block"
  1822. });
  1823. $(".html2md-cb" + suffix).parent().css({
  1824. "position": "relative",
  1825. "z-index": "99999"
  1826. })
  1827. });
  1828.  
  1829. $(document).on("mouseout", ".html2md-cb" + suffix, function () {
  1830. var target;
  1831.  
  1832. if (type === "this_level") {
  1833. target = $(".html2md-cb" + suffix).parent().next().get(0);
  1834. } else if (type === "child_level") {
  1835. target = $(".html2md-cb" + suffix).parent().parent().get(0);
  1836. }
  1837.  
  1838. $(target).find('.overlay').remove();
  1839. $(target).css(previousCSS);
  1840. $(".html2md-cb" + suffix).parent().css({
  1841. "position": "static"
  1842. })
  1843. });
  1844. }
  1845. }
  1846.  
  1847. async function addButtonWithTranslation(parent, suffix, type) {
  1848. var result;
  1849. $(document).on('click', '.translateButton' + suffix, debounce(async function () {
  1850. $(this).trigger('mouseout');
  1851. $(this).removeClass("translated");
  1852. $(this).text("翻译中");
  1853. $(this).css("cursor", "not-allowed");
  1854. $(this).prop("disabled", true);
  1855. var target, element_node, block, errerNum = 0;
  1856. if (type === "this_level") block = $(".translateButton" + suffix).parent().next();
  1857. else if (type === "child_level") block = $(".translateButton" + suffix).parent().parent();
  1858.  
  1859. // 重新翻译
  1860. if (result) {
  1861. if (result.translateDiv) {
  1862. $(result.translateDiv).remove();
  1863. }
  1864. if (result.copyDiv) {
  1865. $(result.copyDiv).remove();
  1866. }
  1867. if (result.copyButton) {
  1868. $(result.copyButton).remove();
  1869. }
  1870. // 移除旧的事件
  1871. $(document).off("mouseover", ".translateButton" + suffix);
  1872. $(document).off("mouseout", ".translateButton" + suffix);
  1873. // 重新绑定悬停事件
  1874. if (hoverTargetAreaDisplay) bindHoverEvents(suffix, type);
  1875. }
  1876.  
  1877. // 分段翻译
  1878. if (enableSegmentedTranslation) {
  1879. var pElements = block.find("p, li");
  1880. for (let i = 0; i < pElements.length; i++) {
  1881. target = $(pElements[i]).eq(0).clone();
  1882. if (type === "child_level") $(target).children(':first').remove();
  1883. element_node = pElements[i];
  1884. if (type === "child_level") {
  1885. $(pElements[i]).append("<div></div>");
  1886. element_node = $(pElements[i]).find("div:last-child").get(0);
  1887. }
  1888. result = await blockProcessing(target, element_node, $(".translateButton" + suffix));
  1889. if (result.status) errerNum += 1;
  1890. $(target).remove();
  1891. if (translation == "deepl") await new Promise(resolve => setTimeout(resolve, 2000));
  1892. }
  1893. } else {
  1894. target = block.eq(0).clone();
  1895. if (type === "child_level") $(target).children(':first').remove();
  1896. element_node = $(block).get(0);
  1897. if (type === "child_level") {
  1898. $(parent).append("<div></div>");
  1899. element_node = $(parent).find("div:last-child").get(0);
  1900. }
  1901. //是否跳过折叠块
  1902. if ($(target).find('.spoiler').length > 0) {
  1903. const shouldSkip = await skiFoldingBlocks();
  1904. if (shouldSkip) {
  1905. $(target).find('.spoiler').remove();
  1906. } else {
  1907. $(target).find('.html2md-panel').remove();
  1908. }
  1909. }
  1910. result = await blockProcessing(target, element_node, $(".translateButton" + suffix));
  1911. if (result.status) errerNum += 1;
  1912. $(target).remove();
  1913. }
  1914. if (!errerNum) {
  1915. $(this).addClass("translated")
  1916. .text("已翻译")
  1917. .css("cursor", "pointer")
  1918. .removeClass("error")
  1919. .prop("disabled", false);
  1920. } else {
  1921. $(this).prop("disabled", false);
  1922. }
  1923.  
  1924. // 重新翻译
  1925. let currentText, is_error;
  1926. $(document).on("mouseover", ".translateButton" + suffix, function () {
  1927. currentText = $(this).text();
  1928. $(this).text("重新翻译");
  1929. if ($(this).hasClass("error")) {
  1930. is_error = true;
  1931. $(this).removeClass("error");
  1932. }
  1933. });
  1934.  
  1935. $(document).on("mouseout", ".translateButton" + suffix, function () {
  1936. $(this).text(currentText);
  1937. if (is_error) $(this).addClass("error");
  1938. });
  1939. }));
  1940.  
  1941. // 目标区域指示
  1942. function bindHoverEvents(suffix, type) {
  1943. var previousCSS;
  1944.  
  1945. $(document).on("mouseover", ".translateButton" + suffix, function () {
  1946. var target;
  1947.  
  1948. if (type === "this_level") {
  1949. target = $(".translateButton" + suffix).parent().next().get(0);
  1950. } else if (type === "child_level") {
  1951. target = $(".translateButton" + suffix).parent().parent().get(0);
  1952. }
  1953.  
  1954. $(target).append('<div class="overlay">目标翻译区域</div>');
  1955. previousCSS = {
  1956. "position": $(target).css("position"),
  1957. "display": $(target).css("display")
  1958. };
  1959. $(target).css({
  1960. "position": "relative",
  1961. "display": "block"
  1962. });
  1963. $(".translateButton" + suffix).parent().css({
  1964. "position": "relative",
  1965. "z-index": "99999"
  1966. });
  1967. });
  1968.  
  1969. $(document).on("mouseout", ".translateButton" + suffix, function () {
  1970. var target;
  1971.  
  1972. if (type === "this_level") {
  1973. target = $(".translateButton" + suffix).parent().next().get(0);
  1974. } else if (type === "child_level") {
  1975. target = $(".translateButton" + suffix).parent().parent().get(0);
  1976. }
  1977.  
  1978. $(target).find('.overlay').remove();
  1979. if (previousCSS) {
  1980. $(target).css(previousCSS);
  1981. }
  1982. $(".translateButton" + suffix).parent().css({
  1983. "position": "static"
  1984. });
  1985. });
  1986. }
  1987.  
  1988. if (hoverTargetAreaDisplay) bindHoverEvents(suffix, type);
  1989. }
  1990.  
  1991. // 块处理
  1992. async function blockProcessing(target, element_node, button) {
  1993. if (!target.markdown) {
  1994. target.markdown = turndownService.turndown($(target).html());
  1995. }
  1996. const textarea = document.createElement('textarea');
  1997. textarea.value = target.markdown;
  1998. var result = await translateProblemStatement(textarea.value, element_node, $(button));
  1999. //
  2000. if (result.status == 1) {
  2001. $(button).addClass("error")
  2002. .text("翻译中止")
  2003. .css("cursor", "pointer")
  2004. .prop("disabled", false);
  2005. $(result.translateDiv).remove();
  2006. $(target).remove();
  2007. } else if (result.status == 2) {
  2008. result.translateDiv.classList.add("error_translate");
  2009. $(button).addClass("error")
  2010. .text("翻译出错")
  2011. .css("cursor", "pointer")
  2012. .prop("disabled", false);
  2013. $(target).remove();
  2014. }
  2015. return result;
  2016. }
  2017.  
  2018. function addConversionButton() {
  2019. // 添加按钮到题目部分
  2020. $('.subject-question').each(function () {
  2021. let id = "_" + getRandomNumber(8);
  2022. addButtonPanel(this, id, "this_level");
  2023. addButtonWithHTML2MD(this, id, "this_level");
  2024. addButtonWithCopy(this, id, "this_level");
  2025. addButtonWithTranslation(this, id, "this_level");
  2026. });
  2027.  
  2028. // 添加按钮到question-oi-bd部分
  2029. $('.question-oi-bd').each(function () {
  2030. let id = "_question-oi-bd_" + getRandomNumber(8);
  2031. addButtonPanel(this, id, "this_level");
  2032. addButtonWithHTML2MD(this, id, "this_level");
  2033. addButtonWithCopy(this, id, "this_level");
  2034. addButtonWithTranslation(this, id, "this_level");
  2035. });
  2036.  
  2037. // 添加按钮到pre部分
  2038. var selectorList = ['.question-oi-bd', '.CodeMirror'];//排除有这些祖宗节点的pre
  2039. $('pre').each(function () {
  2040. for (var i = 0; i < selectorList.length; i++) {
  2041. if ($(this).closest(selectorList[i]).length > 0) {
  2042. return true;
  2043. }
  2044. }
  2045. let id = "_pre_" + getRandomNumber(8);
  2046. addButtonPanel(this, id, "this_level");
  2047. addButtonWithHTML2MD(this, id, "this_level");
  2048. addButtonWithCopy(this, id, "this_level");
  2049. addButtonWithTranslation(this, id, "this_level");
  2050. });
  2051.  
  2052. // 添加按钮到题解部分
  2053. $('div.nc-post-content').each(function () {
  2054. let id = "_nc-post-content_" + getRandomNumber(8);
  2055. addButtonPanel(this, id, "this_level");
  2056. addButtonWithHTML2MD(this, id, "this_level");
  2057. addButtonWithCopy(this, id, "this_level");
  2058. addButtonWithTranslation(this, id, "this_level");
  2059. });
  2060. // 监听展开按钮
  2061. $(document).on('click', '.more-unfold', function (event) {
  2062. var interval = setInterval(function () {
  2063. if ($("div.nc-post-content:not(div.html2md-panel + div.nc-post-content)").length > 0) {
  2064. $("div.nc-post-content:not(div.html2md-panel + div.nc-post-content)").each(function () {
  2065. let id = "_nc-post-content_" + getRandomNumber(8);
  2066. addButtonPanel(this, id, "this_level");
  2067. addButtonWithHTML2MD(this, id, "this_level");
  2068. addButtonWithCopy(this, id, "this_level");
  2069. addButtonWithTranslation(this, id, "this_level");
  2070. });
  2071. clearInterval(interval);
  2072. }
  2073. }, 1000);
  2074. });
  2075. };
  2076.  
  2077. $(document).ready(function () {
  2078. var tip_SegmentedTranslation = $("<div></div>")
  2079. .addClass("alert alert-danger")
  2080. .html(`
  2081. Nowcoder Better! —— 注意!分段翻译已开启,这会造成负面效果,
  2082. <p>除非你现在需要翻译超长篇的博客或者题目,否则请前往设置关闭分段翻译</p>
  2083. `)
  2084. .css({
  2085. margin: "1em",
  2086. "text-align": "center",
  2087. "font-weight": "600",
  2088. position: "relative",
  2089. });
  2090.  
  2091. if (enableSegmentedTranslation)
  2092. $(".content-board").before(tip_SegmentedTranslation); //显示分段翻译警告
  2093.  
  2094. addConversionButton();
  2095. });
  2096.  
  2097. // 字数超限确认
  2098. function showWordsExceededDialog(button) {
  2099. return new Promise(resolve => {
  2100. const styleElement = GM_addStyle(darkenPageStyle);
  2101. $(button).removeClass("translated");
  2102. $(button).text("字数超限");
  2103. $(button).css("cursor", "not-allowed");
  2104. $(button).prop("disabled", true);
  2105. let htmlString = `
  2106. <div class="wordsExceeded">
  2107. <h3>字数超限!</h3>
  2108. <p>注意,即将翻译的内容字数超过了4950个字符,您可能选择了错误的翻译按钮</p>
  2109. <div style="display:flex; padding:5px 0px; align-items: center;">
  2110. `+ helpCircleHTML + `
  2111. <p>
  2112. 由于实现方式,区域中会出现多个翻译按钮,请点击更小的子区域中的翻译按钮,
  2113. <br>或者在设置面板中开启 分段翻译 后重试。
  2114. </p>
  2115. </div>
  2116. <p>对于免费的接口,大量请求可能导致你的IP被暂时禁止访问,对于GPT,会消耗大量的token</p>
  2117. <p>您确定要继续翻译吗?</p>
  2118. <div style="display:flex; padding-top:10px">
  2119. <button id="continueButton">继续</button><button id="cancelButton">取消</button>
  2120. </div>
  2121. </div>
  2122. `;
  2123. $('body').before(htmlString);
  2124. $("#continueButton").click(function () {
  2125. $(styleElement).remove();
  2126. $('.wordsExceeded').remove();
  2127. resolve(true);
  2128. });
  2129. $("#cancelButton").click(function () {
  2130. $(styleElement).remove();
  2131. $('.wordsExceeded').remove();
  2132. resolve(false);
  2133. });
  2134. });
  2135. }
  2136.  
  2137. // 跳过折叠块确认
  2138. function skiFoldingBlocks() {
  2139. return new Promise(resolve => {
  2140. const styleElement = GM_addStyle(darkenPageStyle);
  2141. let htmlString = `
  2142. <div class="wordsExceeded">
  2143. <h3>是否跳过折叠块?</h3>
  2144. <p></p>
  2145. <div style="display:grid; padding:5px 0px; align-items: center;">
  2146. <p>
  2147. 即将翻译的区域中包含折叠块,可能不需要翻译,现在您需要选择是否跳过这些折叠块,
  2148. </p>
  2149. <p>
  2150. 如果其中有您需要翻译的折叠块,可以稍后再单独点击这些折叠块内的翻译按钮进行翻译
  2151. </p>
  2152. </div>
  2153. <p>要跳过折叠块吗?(建议选择跳过)</p>
  2154. <div style="display:flex; padding-top:10px">
  2155. <button id="cancelButton">否</button><button id="skipButton">跳过</button>
  2156. </div>
  2157. </div>
  2158. `;
  2159. $('body').before(htmlString);
  2160. $("#skipButton").click(function () {
  2161. $(styleElement).remove();
  2162. $('.wordsExceeded').remove();
  2163. resolve(true);
  2164. });
  2165. $("#cancelButton").click(function () {
  2166. $(styleElement).remove();
  2167. $('.wordsExceeded').remove();
  2168. resolve(false);
  2169. });
  2170. });
  2171. }
  2172.  
  2173. // 翻译框/翻译处理器
  2174. var translatedText = "";
  2175. async function translateProblemStatement(text, element_node, button) {
  2176. let status = 0;
  2177. let id = getRandomNumber(8);
  2178. let matches = [];
  2179. let replacements = {};
  2180. // 创建元素并放在element_node的后面
  2181. const translateDiv = document.createElement('div');
  2182. translateDiv.setAttribute('id', id);
  2183. translateDiv.classList.add('translate-problem-statement');
  2184. const spanElement = document.createElement('span');
  2185. translateDiv.appendChild(spanElement);
  2186. element_node.insertAdjacentElement('afterend', translateDiv);
  2187. // 替换latex公式
  2188. if (translation != "openai") {
  2189. // 使用GPT翻译时不必替换latex公式
  2190. let i = 0;
  2191. // 块公式
  2192. matches = matches.concat(text.match(/\$\$([\s\S]*?)\$\$/g));
  2193. try {
  2194. for (i; i < matches.length; i++) {
  2195. let match = matches[i];
  2196. text = text.replace(match, `【${i + 1}】`);
  2197. replacements[`【${i + 1}】`] = match;
  2198. }
  2199. } catch (e) { }
  2200. // 行内公式
  2201. matches = matches.concat(text.match(/\$(.*?)\$/g));
  2202. try {
  2203. for (i; i < matches.length; i++) {
  2204. let match = matches[i];
  2205. text = text.replace(match, `【${i + 1}】`);
  2206. replacements[`【${i + 1}】`] = match;
  2207. }
  2208. } catch (e) { }
  2209. }
  2210. if (text.length > 4950) {
  2211. const shouldContinue = await showWordsExceededDialog(button);
  2212. if (!shouldContinue) {
  2213. status = 1;
  2214. return {
  2215. translateDiv: translateDiv,
  2216. status: status
  2217. };
  2218. }
  2219. }
  2220. // 翻译
  2221. if (translation == "deepl") {
  2222. translateDiv.innerHTML = "正在使用 deepl 翻译中……请稍等";
  2223. translatedText = await translate_deepl(text);
  2224. } else if (translation == "youdao") {
  2225. translateDiv.innerHTML = "正在使用 有道 翻译中……请稍等";
  2226. translatedText = await translate_youdao_mobile(text);
  2227. } else if (translation == "google") {
  2228. translateDiv.innerHTML = "正在使用 google 翻译中……请稍等";
  2229. translatedText = await translate_gg(text);
  2230. } else if (translation == "openai") {
  2231. try {
  2232. translateDiv.innerHTML = "正在使用 ChatGPT 翻译中……" +
  2233. "<br><br>应用的配置:" + opneaiConfig.configurations[opneaiConfig.choice].note +
  2234. "<br><br>使用 ChatGPT 翻译需要很长的时间,请耐心等待";
  2235. translatedText = await translate_openai(text);
  2236. } catch (error) {
  2237. status = 2;
  2238. translatedText = error;
  2239. }
  2240. }
  2241. if (/^翻译出错/.test(translatedText)) status = 2;
  2242. // 还原latex公式
  2243. translatedText = translatedText.replace(/】【/g, '】 【');
  2244. if (translation != "openai") {
  2245. try {
  2246. for (let i = 0; i < matches.length; i++) {
  2247. let match = matches[i];
  2248. let replacement = replacements[`【${i + 1}】`];
  2249. let regex;
  2250. regex = new RegExp(`【\\s*${i + 1}\\s*】`, 'g');
  2251. translatedText = translatedText.replace(regex, replacement);
  2252. regex = new RegExp(`\\[\\s*${i + 1}\\s*\\]`, 'g');
  2253. translatedText = translatedText.replace(regex, replacement);
  2254. regex = new RegExp(`【\\s*${i + 1}(?![】\\d])`, 'g');
  2255. translatedText = translatedText.replace(regex, replacement);
  2256. regex = new RegExp(`(?<![【\\d])${i + 1}\\s*】`, 'g');
  2257. translatedText = translatedText.replace(regex, " " + replacement);
  2258. }
  2259. } catch (e) { }
  2260. }
  2261.  
  2262. // 创建一个隐藏的元素来保存 translatedText 的值
  2263. var textElement = document.createElement("div");
  2264. textElement.style.display = "none";
  2265. textElement.textContent = translatedText;
  2266. translateDiv.parentNode.insertBefore(textElement, translateDiv);
  2267.  
  2268. // 翻译复制按钮
  2269. var copyButton = document.createElement("button");
  2270. copyButton.textContent = "Copy";
  2271. var wrapperDiv = document.createElement("div");
  2272. $(wrapperDiv).css({
  2273. display: "flex",
  2274. justifyContent: "flex-end"
  2275. });
  2276. $(wrapperDiv).append(copyButton);
  2277. $(copyButton).addClass("html2mdButton html2md-cb");
  2278.  
  2279. copyButton.addEventListener("click", function () {
  2280. var translatedText = textElement.textContent;
  2281. GM_setClipboard(translatedText);
  2282. $(this).addClass("copied").text("Copied");
  2283. // 更新复制按钮文本
  2284. setTimeout(() => {
  2285. $(this).removeClass("copied");
  2286. $(this).text("Copy");
  2287. }, 2000);
  2288. });
  2289. translateDiv.parentNode.insertBefore(wrapperDiv, translateDiv);
  2290.  
  2291. // 转义LaTex中的特殊符号
  2292. const escapeRules = [
  2293. { pattern: /(?<!\\)>(?!\s)/g, replacement: " &gt; " }, // >符号
  2294. { pattern: /(?<!\\)</g, replacement: " &lt; " }, // <符号
  2295. { pattern: /(?<!\\)\*/g, replacement: " &#42; " }, // *符号
  2296. { pattern: /(?<!\\)&(?=\s)/g, replacement: "\\&" }, // &符号
  2297. { pattern: /\\&/g, replacement: "\\\\&" }, // &符号
  2298. ];
  2299.  
  2300. let latexMatches = [...translatedText.matchAll(/\$\$([\s\S]*?)\$\$|\$(.*?)\$/g)];
  2301.  
  2302. for (const match of latexMatches) {
  2303. const matchedText = match[0];
  2304.  
  2305. for (const rule of escapeRules) {
  2306. const escapedText = matchedText.replaceAll(rule.pattern, rule.replacement);
  2307. translatedText = translatedText.replace(matchedText, escapedText);
  2308. }
  2309. }
  2310.  
  2311. // 渲染MarkDown
  2312. var md = window.markdownit();
  2313. var html = md.render(translatedText);
  2314. translateDiv.innerHTML = html;
  2315. // 渲染Latex
  2316. if (typeof renderMathInElement === 'function') {
  2317. renderMathInElement(translateDiv, {
  2318. delimiters: [{
  2319. left: "$$",
  2320. right: "$$",
  2321. display: true
  2322. }, {
  2323. left: "$",
  2324. right: "$",
  2325. display: false
  2326. }]
  2327. });
  2328. }
  2329. return {
  2330. translateDiv: translateDiv,
  2331. status: status,
  2332. copyDiv: textElement,
  2333. copyButton: copyButton
  2334. };
  2335.  
  2336. }
  2337.  
  2338. // ChatGPT
  2339. async function translate_openai(raw) {
  2340. var openai_retext = "";
  2341. var data = {
  2342. model: (openai_model !== null && openai_model !== "") ? openai_model : 'gpt-3.5-turbo',
  2343. messages: [{
  2344. role: "user",
  2345. content: "请将下面的文本翻译为中文,这是一道编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw
  2346. }],
  2347. temperature: 0.7,
  2348. ...Object.assign({}, ...openai_data)
  2349. };
  2350. return new Promise(function (resolve, reject) {
  2351. GM_xmlhttpRequest({
  2352. method: 'POST',
  2353. url: (openai_proxy !== null && openai_proxy !== "") ? openai_proxy : 'https://api.openai.com/v1/chat/completions',
  2354.  
  2355. data: JSON.stringify(data),
  2356. headers: {
  2357. 'Content-Type': 'application/json',
  2358. 'Authorization': 'Bearer ' + openai_key,
  2359. ...Object.assign({}, ...openai_header)
  2360. },
  2361. responseType: 'json',
  2362. onload: function (response) {
  2363. if (!response.response) {
  2364. reject("发生了未知的错误,如果你启用了代理API,请确认是否填写正确,并确保代理能够正常工作。\n\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/471106/feedback 反馈 请注意打码响应报文的敏感部分\n\n响应报文:" + JSON.stringify(response));
  2365. }
  2366. else if (!response.response.choices || response.response.choices.length < 1 || !response.response.choices[0].message) {
  2367. resolve("翻译出错,请重试\n\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/471106/feedback 反馈\n\n报错信息:" + JSON.stringify(response.response, null, ''));
  2368. } else {
  2369. openai_retext = response.response.choices[0].message.content;
  2370. resolve(openai_retext);
  2371. }
  2372. },
  2373. onerror: function (response) {
  2374. reject("发生了未知的错误,请确认你是否能正常访问OpenAi的接口,如果使用代理API,请检查是否正常工作\n\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/471106/feedback 反馈 请注意打码响应报文的敏感部分\n\n响应报文:" + JSON.stringify(response));
  2375. },
  2376. });
  2377.  
  2378. });
  2379. }
  2380.  
  2381. //--谷歌翻译--start
  2382. async function translate_gg(raw) {
  2383. return new Promise((resolve, reject) => {
  2384. const url = 'https://translate.google.com/m';
  2385. const params = `tl=zh-CN&q=${encodeURIComponent(raw)}`;
  2386.  
  2387. GM_xmlhttpRequest({
  2388. method: 'GET',
  2389. url: `${url}?${params}`,
  2390. onload: function (response) {
  2391. const html = response.responseText;
  2392. const translatedText = $(html).find('.result-container').text();
  2393. resolve(translatedText);
  2394. },
  2395. onerror: function (error) {
  2396. console.error('Error:', error);
  2397. reject(error);
  2398. }
  2399. });
  2400. });
  2401. }
  2402. //--谷歌翻译--end
  2403.  
  2404. //--有道翻译m--start
  2405. async function translate_youdao_mobile(raw) {
  2406. const options = {
  2407. method: "POST",
  2408. url: 'http://m.youdao.com/translate',
  2409. data: "inputtext=" + encodeURIComponent(raw) + "&type=AUTO",
  2410. anonymous: true,
  2411. headers: {
  2412. "Content-Type": "application/x-www-form-urlencoded",
  2413. 'Host': 'm.youdao.com',
  2414. 'Origin': 'http://m.youdao.com',
  2415. 'Referer': 'http://m.youdao.com/translate',
  2416. }
  2417. }
  2418. return await BaseTranslate('有道翻译mobile', raw, options, res => /id="translateResult">\s*?<li>([\s\S]*?)<\/li>\s*?<\/ul/.exec(res)[1])
  2419. }
  2420. //--有道翻译m--end
  2421.  
  2422. //--Deepl翻译--start
  2423. function getTimeStamp(iCount) {
  2424. const ts = Date.now();
  2425. if (iCount !== 0) {
  2426. iCount = iCount + 1;
  2427. return ts - (ts % iCount) + iCount;
  2428. } else {
  2429. return ts;
  2430. }
  2431. }
  2432.  
  2433. async function translate_deepl(raw) {
  2434. const id = (Math.floor(Math.random() * 99999) + 100000) * 1000;
  2435. const data = {
  2436. jsonrpc: '2.0',
  2437. method: 'LMT_handle_texts',
  2438. id,
  2439. params: {
  2440. splitting: 'newlines',
  2441. lang: {
  2442. source_lang_user_selected: 'auto',
  2443. target_lang: 'ZH',
  2444. },
  2445. texts: [{
  2446. text: raw,
  2447. requestAlternatives: 3
  2448. }],
  2449. timestamp: getTimeStamp(raw.split('i').length - 1)
  2450. }
  2451. }
  2452. let postData = JSON.stringify(data);
  2453. if ((id + 5) % 29 === 0 || (id + 3) % 13 === 0) {
  2454. postData = postData.replace('"method":"', '"method" : "');
  2455. } else {
  2456. postData = postData.replace('"method":"', '"method": "');
  2457. }
  2458. const options = {
  2459. method: 'POST',
  2460. url: 'https://www2.deepl.com/jsonrpc',
  2461. data: postData,
  2462. headers: {
  2463. 'Content-Type': 'application/json',
  2464. 'Host': 'www2.deepl.com',
  2465. 'Origin': 'https://www.deepl.com',
  2466. 'Referer': 'https://www.deepl.com/',
  2467. },
  2468. anonymous: true,
  2469. nocache: true,
  2470. }
  2471. return await BaseTranslate('Deepl翻译', raw, options, res => JSON.parse(res).result.texts[0].text)
  2472. }
  2473.  
  2474. //--Deepl翻译--end
  2475.  
  2476. //--异步请求包装工具--start
  2477. async function PromiseRetryWrap(task, options, ...values) {
  2478. const { RetryTimes, ErrProcesser } = options || {};
  2479. let retryTimes = RetryTimes || 5;
  2480. const usedErrProcesser = ErrProcesser || (err => { throw err });
  2481. if (!task) return;
  2482. while (true) {
  2483. try {
  2484. return await task(...values);
  2485. } catch (err) {
  2486. if (!--retryTimes) {
  2487. console.log(err);
  2488. return usedErrProcesser(err);
  2489. }
  2490. }
  2491. }
  2492. }
  2493.  
  2494. async function BaseTranslate(name, raw, options, processer) {
  2495. let errtext;
  2496. const toDo = async () => {
  2497. var tmp;
  2498. try {
  2499. const data = await Request(options);
  2500. tmp = data.responseText;
  2501. const result = await processer(tmp);
  2502. if (result) sessionStorage.setItem(name + '-' + raw, result);
  2503. return result
  2504. } catch (err) {
  2505. errtext = tmp;
  2506. throw {
  2507. responseText: tmp,
  2508. err: err
  2509. }
  2510. }
  2511. }
  2512. return await PromiseRetryWrap(toDo, { RetryTimes: 3, ErrProcesser: () => "翻译出错,请重试或更换翻译接口\n\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/471106/feedback 反馈 请注意打码报错信息的敏感部分\n\n报错信息:" + errtext })
  2513. }
  2514.  
  2515.  
  2516. function Request(options) {
  2517. return new Promise((reslove, reject) => GM_xmlhttpRequest({ ...options, onload: reslove, onerror: reject }))
  2518. }
  2519.  
  2520. //--异步请求包装工具--end
  2521.  
  2522.  
  2523. // 配置自动迁移代码(将在10个小版本后移除-1.20)
  2524. if (GM_getValue("openai_key") || GM_getValue("api2d_key")) {
  2525. const newConfig = { "choice": -1, "configurations": [] };
  2526. if (GM_getValue("openai_key")) {
  2527. let config1 = {
  2528. "note": "我的配置1",
  2529. "model": GM_getValue("openai_model"),
  2530. "key": GM_getValue("openai_key"),
  2531. "proxy": GM_getValue("openai_proxy"),
  2532. "_header": "",
  2533. "_data": ""
  2534. }
  2535. if (GM_getValue("translation") === "openai") newConfig.choice = 0;
  2536. newConfig.configurations.push(config1);
  2537. }
  2538. if (GM_getValue("api2d_key")) {
  2539. let config2 = {
  2540. "note": "api2d",
  2541. "model": GM_getValue("api2d_model"),
  2542. "key": GM_getValue("api2d_key"),
  2543. "proxy": GM_getValue("api2d_request_entry") + '/v1/chat/completions',
  2544. "_header": GM_getValue("x_api2d_no_cache") ? "" : " x-api2d-no-cache : 1",
  2545. "_data": ""
  2546. }
  2547. if (GM_getValue("translation") === "api2d") {
  2548. if (GM_getValue("openai_key")) newConfig.choice = 1;
  2549. else newConfig.choice = 0;
  2550. }
  2551. newConfig.configurations.push(config2);
  2552. }
  2553. GM_setValue("chatgpt-config", newConfig);
  2554. const keysToDelete = ["openai_key", "openai_model", "openai_proxy", "api2d_key", "api2d_model", "api2d_request_entry", "x_api2d_no_cache", "showOpneAiAdvanced"];
  2555. keysToDelete.forEach(key => {
  2556. if (GM_getValue(key) != undefined) GM_deleteValue(key);
  2557. });
  2558. if (GM_getValue("translation") === "api2d") GM_setValue("translation", "openai");
  2559. location.reload();
  2560. }