Nowcoder Better!

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

נכון ליום 02-09-2023. ראה הגרסה האחרונה.

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