Codeforces Better!

Codeforces界面汉化、黑暗模式支持、题目翻译,markdown视图,一键复制题目,跳转到洛谷、评论区分页

目前為 2023-09-15 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name Codeforces Better!
  3. // @namespace https://greasyfork.org/users/747162
  4. // @version 1.61
  5. // @description Codeforces界面汉化、黑暗模式支持、题目翻译,markdown视图,一键复制题目,跳转到洛谷、评论区分页
  6. // @author 北极小狐
  7. // @match *://*.codeforces.com/*
  8. // @run-at document-start
  9. // @connect www2.deepl.com
  10. // @connect m.youdao.com
  11. // @connect translate.google.com
  12. // @connect openai.api2d.net
  13. // @connect api.openai.com
  14. // @connect www.luogu.com.cn
  15. // @connect greasyfork.org
  16. // @connect *
  17. // @grant GM_xmlhttpRequest
  18. // @grant GM_info
  19. // @grant GM_setValue
  20. // @grant GM_getValue
  21. // @grant GM_deleteValue
  22. // @grant GM_addStyle
  23. // @grant GM_cookie
  24. // @grant GM_setClipboard
  25. // @icon https://aowuucdn.oss-cn-beijing.aliyuncs.com/codeforces.png
  26. // @require https://cdn.staticfile.org/turndown/7.1.2/turndown.min.js
  27. // @require https://cdn.staticfile.org/markdown-it/13.0.1/markdown-it.min.js
  28. // @license MIT
  29. // @compatible Chrome
  30. // @compatible Firefox
  31. // @compatible Edge
  32. // ==/UserScript==
  33.  
  34. // 状态与初始化
  35. const getGMValue = (key, defaultValue) => {
  36. const value = GM_getValue(key);
  37. if (value === undefined || value === "") {
  38. GM_setValue(key, defaultValue);
  39. return defaultValue;
  40. }
  41. return value;
  42. };
  43. var darkMode = getGMValue("darkMode", "follow");
  44. var is_mSite, is_acmsguru, is_oldLatex;
  45. var bottomZh_CN, showLoading, hoverTargetAreaDisplay, expandFoldingblocks, renderPerfOpt, enableSegmentedTranslation, translation;
  46. var openai_model, openai_key, openai_proxy, openai_header, openai_data, opneaiConfig;
  47. var commentPaging, showJumpToLuogu, loaded;
  48. function init() {
  49. is_mSite = window.location.hostname.startsWith('m');
  50. is_acmsguru = window.location.href.includes("acmsguru");
  51. is_oldLatex = $('.tex-span').length;
  52. // 说明为旧的latex渲染
  53. if (is_oldLatex) {
  54. var newElement = $("<div></div>").addClass("alert alert-warning ojbetter-alert").html(`
  55. 注意:当前页面存在使用非 MathJax 库渲染为 HTML Latex 公式(这通常是一道古老的题目),这导致 CodeforcesBetter! 无法将其还原回 Latex,因此当前页面部分功能不适用。
  56. <br>此外当前页面的翻译功能采用了特别的实现方式,因此可能会出现排版错位的情况。
  57. `).css({ "margin": "1em", "text-align": "center", "position": "relative" });
  58. $(".menu-box:first").next().after(newElement);
  59. }
  60. bottomZh_CN = getGMValue("bottomZh_CN", true);
  61. showLoading = getGMValue("showLoading", true);
  62. hoverTargetAreaDisplay = getGMValue("hoverTargetAreaDisplay", false);
  63. expandFoldingblocks = getGMValue("expandFoldingblocks", true);
  64. renderPerfOpt = getGMValue("renderPerfOpt", false);
  65. commentPaging = getGMValue("commentPaging", true);
  66. enableSegmentedTranslation = getGMValue("enableSegmentedTranslation", false);
  67. showJumpToLuogu = getGMValue("showJumpToLuogu", true);
  68. loaded = getGMValue("loaded", false);
  69. translation = getGMValue("translation", "deepl");
  70. //openai
  71. opneaiConfig = getGMValue("chatgpt-config", {
  72. "choice": -1,
  73. "configurations": []
  74. });
  75. if (opneaiConfig.choice !== -1 && opneaiConfig.configurations.length !== 0) {
  76. const configAtIndex = opneaiConfig.configurations[opneaiConfig.choice];
  77.  
  78. if (configAtIndex == undefined) {
  79. let existingConfig = GM_getValue('chatgpt-config');
  80. existingConfig.choice = 0;
  81. GM_setValue('chatgpt-config', existingConfig);
  82. location.reload();
  83. }
  84.  
  85. openai_model = configAtIndex.model;
  86. openai_key = configAtIndex.key;
  87. openai_proxy = configAtIndex.proxy;
  88. openai_header = configAtIndex._header ?
  89. configAtIndex._header.split("\n").map(header => {
  90. const [key, value] = header.split(":");
  91. return { [key.trim()]: value.trim() };
  92. }) : [];
  93. openai_data = configAtIndex._data ?
  94. configAtIndex._data.split("\n").map(header => {
  95. const [key, value] = header.split(":");
  96. return { [key.trim()]: value.trim() };
  97. }) : [];
  98. }
  99. }
  100.  
  101. // 常量
  102. 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>';
  103. 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: 999; }`;
  104. 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; }`;
  105.  
  106. // 报错信息捕获
  107. /*let errorMessages = "";
  108. const defaultError = console.error.bind(console);
  109. console.error = (message) => {
  110. const error = new Error();
  111. const stack = error.stack.split("\n").slice(2).join("\n");
  112. const now = new Date().toLocaleString();
  113. errorMessages += "\n## " + message + "\n### time: " + now +"\n" + stack + "\n";
  114. defaultError(message);
  115. };
  116. window.onerror = (message, source, lineno, colno, error) => {
  117. const now = new Date().toLocaleString();
  118. errorMessages += "\n## " + message + "\n### time: " + now +"\n" + error.stack + "\n";
  119. defaultError(message);
  120. return true;
  121. };*/
  122.  
  123. // 切换系统黑暗监听
  124. const mediaQueryList = window.matchMedia('(prefers-color-scheme: dark)');
  125. const changeEventListeners = [];
  126. function handleColorSchemeChange(event) {
  127. const newColorScheme = event.matches ? $('html').attr('data-theme', 'dark') : $('html').attr('data-theme', 'light');
  128. if (!event.matches) {
  129. var originalColor = $(this).data("original-color");
  130. $(this).css("background-color", originalColor);
  131. }
  132. }
  133.  
  134. // 黑暗模式
  135. (function setDark() {
  136. // 初始化
  137. function setDarkTheme() {
  138. const htmlElement = document.querySelector('html');
  139. if (htmlElement) {
  140. htmlElement.setAttribute('data-theme', 'dark');
  141. } else {
  142. setTimeout(setDarkTheme, 100);
  143. }
  144. }
  145. if (darkMode == "dark") {
  146. setDarkTheme();
  147. } else if (darkMode == "follow") {
  148. // 添加事件监听器
  149. changeEventListeners.push(handleColorSchemeChange);
  150. mediaQueryList.addEventListener('change', handleColorSchemeChange);
  151.  
  152. if (window.matchMedia('(prefers-color-scheme: dark)').matches) setDarkTheme();
  153. }
  154.  
  155. GM_addStyle(`
  156. /* 黑暗支持 */
  157. html[data-theme=dark]:root {
  158. color-scheme: light dark;
  159. }
  160. /* 文字颜色1 */
  161. html[data-theme=dark] .title,html[data-theme=dark] .problem-statement,
  162. html[data-theme=dark] .ttypography, html[data-theme=dark] .roundbox, html[data-theme=dark] .info,
  163. html[data-theme=dark] .ttypography .bordertable, html[data-theme=dark] .ttypography .bordertable thead th,
  164. html[data-theme=dark] .ttypography h1, html[data-theme=dark] .ttypography h2, html[data-theme=dark] .ttypography h3,
  165. html[data-theme=dark] .ttypography h4, html[data-theme=dark] .ttypography h5, html[data-theme=dark] .ttypography h6
  166. html[data-theme=dark] .datatable table, html[data-theme=dark] .problem-statement .sample-tests pre,
  167. html[data-theme=dark] .alert-success, html[data-theme=dark] .alert-info, html[data-theme=dark] .alert-error,
  168. html[data-theme=dark] .alert-warning, html[data-theme=dark] .markItUpEditor, html[data-theme=dark] #pageContent,
  169. html[data-theme=dark] .ace-chrome .ace_gutter, html[data-theme=dark] .translate-problem-statement,
  170. html[data-theme=dark] .setting-name, html[data-theme=dark] .CFBetter_setting_menu, html[data-theme=dark] .help_tip .tip_text,
  171. html[data-theme=dark] textarea, html[data-theme=dark] .user-black, html[data-theme=dark] .comments label.show-archived,
  172. html[data-theme=dark] .comments label.show-archived *, html[data-theme=dark] table,
  173. html[data-theme=dark] #items-per-page, html[data-theme=dark] #pagBar{
  174. color: #a0adb9 !important;
  175. }
  176. html[data-theme=dark] h1 a, html[data-theme=dark] h2 a, html[data-theme=dark] h3 a, html[data-theme=dark] h4 a{
  177. color: #adbac7;
  178. }
  179. /* 文字颜色2 */
  180. html[data-theme=dark] .second-level-menu-list li a, html[data-theme=dark] span, html[data-theme=dark] #footer,
  181. html[data-theme=dark] .ttypography .tt, html[data-theme=dark] select,
  182. html[data-theme=dark] .roundbox .caption, html[data-theme=dark] .topic .title *,
  183. html[data-theme=dark] .user-admin{
  184. color: #9099a3 !important;
  185. }
  186. /* 文字颜色3 */
  187. html[data-theme=dark] button.html2mdButton, html[data-theme=dark] input{
  188. color: #6385a6 !important;
  189. }
  190. /* 文字颜色4 */
  191. html[data-theme=dark] .ttypography .MathJax, html[data-theme=dark] .MathJax span{
  192. color: #cbd6e2 !important;
  193. }
  194. /* 链接颜色 */
  195. html[data-theme=dark] a:link {
  196. color: #3989c9;
  197. }
  198. html[data-theme=dark] a:visited {
  199. color: #8590a6;
  200. }
  201. html[data-theme=dark] .menu-box a, html[data-theme=dark] .sidebox th a{
  202. color: #9099a3 !important;
  203. }
  204. /* 按钮 */
  205. html[data-theme=dark] .second-level-menu-list li.backLava {
  206. border-radius: 6px;
  207. overflow: hidden;
  208. filter: invert(1) hue-rotate(.5turn);
  209. }
  210. html[data-theme=dark] input:hover{
  211. background-color: #22272e !important;
  212. }
  213. /* 背景层次1 */
  214. html[data-theme=dark] body, html[data-theme=dark] .ttypography .bordertable thead th,
  215. html[data-theme=dark] .datatable table, html[data-theme=dark] .datatable .dark, html[data-theme=dark] li#add_button,
  216. html[data-theme=dark] .problem-statement .sample-tests pre, html[data-theme=dark] .markItUpEditor,
  217. html[data-theme=dark] .SumoSelect>.CaptionCont, html[data-theme=dark] .SumoSelect>.optWrapper,
  218. html[data-theme=dark] .SumoSelect>.optWrapper.multiple>.options li.opt span i, html[data-theme=dark] .ace_scroller,
  219. html[data-theme=dark] .CFBetter_setting_menu, html[data-theme=dark] .help_tip .tip_text, html[data-theme=dark] li#add_button:hover,
  220. html[data-theme=dark] textarea, html[data-theme=dark] .state, html[data-theme=dark] .ace-chrome .ace_gutter-active-line,
  221. html[data-theme=dark] .sidebar-menu ul li:hover, html[data-theme=dark] .sidebar-menu ul li.active,
  222. html[data-theme=dark] label.config_bar_ul_li_text:hover, html[data-theme=dark] button.html2mdButton:hover{
  223. background-color: #22272e !important;
  224. }
  225. /* 背景层次2 */
  226. html[data-theme=dark] .roundbox, html[data-theme=dark] .roundbox .dark, html[data-theme=dark] .bottom-links,
  227. html[data-theme=dark] button.html2mdButton, html[data-theme=dark] .spoiler-content, html[data-theme=dark] input,
  228. html[data-theme=dark] .problem-statement .test-example-line-even, html[data-theme=dark] .highlight-blue,
  229. html[data-theme=dark] .ttypography .tt, html[data-theme=dark] select,
  230. html[data-theme=dark] .alert-success, html[data-theme=dark] .alert-info, html[data-theme=dark] .alert-error,
  231. html[data-theme=dark] .alert-warning, html[data-theme=dark] .SumoSelect>.optWrapper>.options li.opt:hover,
  232. html[data-theme=dark] .problems .accepted-problem td.act, html[data-theme=dark] .input-output-copier:hover,
  233. html[data-theme=dark] .aceEditorTd, html[data-theme=dark] .ace-chrome .ace_gutter,
  234. html[data-theme=dark] .translate-problem-statement, html[data-theme=dark] .datatable,
  235. html[data-theme=dark] .CFBetter_setting_list, html[data-theme=dark] #config_bar_list,
  236. html[data-theme=dark] .CFBetter_setting_menu hr, html[data-theme=dark] .wordsExceeded{
  237. background-color: #2d333b !important;
  238. }
  239. /* 实线边框颜色-圆角 */
  240. html[data-theme=dark] .roundbox, html[data-theme=dark] .roundbox .rtable td,
  241. html[data-theme=dark] button.html2mdButton, html[data-theme=dark] .sidebar-menu ul li,
  242. html[data-theme=dark] input, html[data-theme=dark] .ttypography .tt, html[data-theme=dark] #items-per-page,
  243. html[data-theme=dark] .datatable td, html[data-theme=dark] .datatable th,
  244. html[data-theme=dark] .alert-success, html[data-theme=dark] .alert-info, html[data-theme=dark] .alert-error,
  245. html[data-theme=dark] .alert-warning, html[data-theme=dark] .translate-problem-statement,
  246. html[data-theme=dark] textarea, html[data-theme=dark] .input-output-copier{
  247. border: 1px solid #424b56 !important;
  248. border-radius: 2px;
  249. }
  250. /* 实线边框颜色-无圆角 */
  251. html[data-theme=dark] .CFBetter_setting_list, html[data-theme=dark] #config_bar_list,
  252. html[data-theme=dark] label.config_bar_ul_li_text, html[data-theme=dark] .problem-statement .sample-tests .input,
  253. html[data-theme=dark] .problem-statement .sample-tests .output{
  254. border: 1px solid #424b56 !important;
  255. }
  256. html[data-theme=dark] .roundbox .titled, html[data-theme=dark] .roundbox .rtable th {
  257. border-bottom: 1px solid #424b56 !important;
  258. }
  259. html[data-theme=dark] .roundbox .bottom-links, html[data-theme=dark] #footer{
  260. border-top: 1px solid #424b56 !important;
  261. }
  262. html[data-theme=dark] .topic .content {
  263. border-left: 4px solid #424b56 !important;
  264. }
  265. /* 虚线边框颜色 */
  266. html[data-theme=dark] .comment-table, html[data-theme=dark] li#add_button,
  267. html[data-theme=dark] .CFBetter_setting_menu_label_text{
  268. border: 1px dashed #424b56 !important;
  269. }
  270. html[data-theme=dark] li#add_button:hover{
  271. border: 1px dashed #03A9F4 !important;
  272. background-color: #2d333b !important;
  273. color: #03A9F4 !important;
  274. }
  275. /* focus-visible */
  276. html[data-theme=dark] input:focus-visible, html[data-theme=dark] textarea, html[data-theme=dark] select{
  277. border-width: 1.5px !important;
  278. outline: none;
  279. }
  280. /* 图片-亮度 */
  281. html[data-theme=dark] img{
  282. opacity: .75;
  283. }
  284. /* 图片-反转 */
  285. html[data-theme=dark] .SumoSelect>.CaptionCont>label>i, html[data-theme=dark] .delete-resource-link{
  286. filter: invert(1) hue-rotate(.5turn);
  287. }
  288. /* 区域遮罩 */
  289. html[data-theme=dark] .overlay {
  290. background: repeating-linear-gradient(135deg, #49525f6e, #49525f6e 30px, #49525f29 0px, #49525f29 55px);
  291. color: #9099a3;
  292. text-shadow: 0px 0px 2px #000000;
  293. }
  294. /* 其他样式 */
  295. html[data-theme=dark] .rated-user{
  296. display: initial;
  297. }
  298. html[data-theme=dark] .datatable .ilt, html[data-theme=dark] .datatable .irt,
  299. html[data-theme=dark] .datatable .ilb, html[data-theme=dark] .datatable .irb,
  300. html[data-theme=dark] .datatable .lt, html[data-theme=dark] .datatable .rt,
  301. html[data-theme=dark] .datatable .lb, html[data-theme=dark] .datatable .rb{
  302. background: none;
  303. }
  304. html[data-theme=dark] .problems .accepted-problem td.id{
  305. border-left: 6px solid #009688 !important;
  306. }
  307. html[data-theme=dark] .CFBetter_setting_menu{
  308. box-shadow: 0px 0px 0px 4px #2d333b;
  309. border: 1px solid #2d333b;
  310. }
  311. html[data-theme=dark] .collapsible-topic.collapsed .content .collapsible-topic-options:before{
  312. background-image: linear-gradient(#22272e00, #22272e);
  313. }
  314. html[data-theme=dark] .alert{
  315. text-shadow: none;
  316. }
  317. html[data-theme=dark] input[type="radio"]:checked+.CFBetter_setting_menu_label_text {
  318. color: #a0adb9 !important;
  319. border: 1px solid #326154 !important;
  320. }
  321. `);
  322. })()
  323.  
  324. // 样式
  325. GM_addStyle(`
  326. html {
  327. scroll-behavior: smooth;
  328. }
  329. :root {
  330. --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";
  331. }
  332. span.mdViewContent {
  333. white-space: pre-wrap;
  334. }
  335. /*翻译区域提示*/
  336. .overlay {
  337. pointer-events: none;
  338. position: absolute;
  339. top: 0;
  340. left: 0;
  341. width: 100%;
  342. height: 100%;
  343. background: repeating-linear-gradient(135deg, #97e7cacc, #97e7cacc 30px, #e9fbf1cc 0px, #e9fbf1cc 55px);
  344. border-radius: 5px;
  345. display: flex;
  346. align-items: center;
  347. justify-content: center;
  348. color: #00695C;
  349. font-size: 16px;
  350. font-weight: bold;
  351. text-shadow: 0px 0px 2px #edfcf4;
  352. }
  353. /*翻译div*/
  354. .translate-problem-statement {
  355. justify-items: start;
  356. letter-spacing: 1.8px;
  357. color: #059669;
  358. background-color: #f9f9fa;
  359. border: 1px solid #10b981;
  360. border-radius: 0.3rem;
  361. padding: 5px;
  362. margin: 10px 0px;
  363. width: 100%;
  364. box-sizing: border-box;
  365. font-size: 13px;
  366. }
  367. .translate-problem-statement.error_translate {
  368. color: red;
  369. border-color: red;
  370. }
  371. .translate-problem-statement a {
  372. color: #10b981;
  373. font-weight: 600;
  374. background: 0 0;
  375. text-decoration: none;
  376. }
  377. .translate-problem-statement ol, .translate-problem-statement ul {
  378. display: grid;
  379. margin-inline-start: 0.8em;
  380. margin-block-start: 0em;
  381. margin: 0.5em 0 0 3em;
  382. }
  383. .translate-problem-statement li {
  384. display: list-item;
  385. height: auto;
  386. word-wrap: break-word;
  387. }
  388. .translate-problem-statement ol li {
  389. list-style-type: auto;
  390. }
  391. .translate-problem-statement ul li {
  392. list-style-type: disc;
  393. }
  394. .translate-problem-statement img {
  395. max-width: 100.0%;
  396. max-height: 100.0%;
  397. }
  398. .ttypography .translate-problem-statement .MathJax {
  399. color: #059669!important;
  400. }
  401. .translate-problem-statement span.math {
  402. margin: 0px 2.5px !important;
  403. }
  404. .translate-problem-statement a:hover {
  405. background-color: #800;
  406. color: #fff;
  407. text-decoration: none;
  408. }
  409. .html2md-panel {
  410. display: flex;
  411. justify-content: flex-end;
  412. }
  413. .html2md-panel a {
  414. text-decoration: none;
  415. }
  416. button.html2mdButton {
  417. display: flex;
  418. align-items: center;
  419. cursor: pointer;
  420. background-color: #ffffff;
  421. color: #606266;
  422. height: 22px;
  423. width: auto;
  424. font-size: 13px;
  425. border-radius: 0.3rem;
  426. padding: 1px 5px;
  427. margin: 5px !important;
  428. border: 1px solid #dcdfe6;
  429. }
  430. button.html2mdButton:hover {
  431. color: #409eff;
  432. border-color: #409eff;
  433. background-color: #f1f8ff;
  434. }
  435. button.html2mdButton.copied {
  436. background-color: #f0f9eb;
  437. color: #67c23e;
  438. border: 1px solid #b3e19d;
  439. }
  440. button.html2mdButton.mdViewed {
  441. background-color: #fdf6ec;
  442. color: #e6a23c;
  443. border: 1px solid #f3d19e;
  444. }
  445. button.html2mdButton.error {
  446. background-color: #fef0f0;
  447. color: #f56c6c;
  448. border: 1px solid #fab6b6;
  449. }
  450. button.translated {
  451. background-color: #f0f9eb;
  452. color: #67c23e;
  453. border: 1px solid #b3e19d;
  454. }
  455. button.html2mdButton.reTranslation {
  456. background-color: #f4f4f5;
  457. color: #909399;
  458. border: 1px solid #c8c9cc;
  459. }
  460. .translate-problem-statement table {
  461. border: 1px #ccc solid !important;
  462. margin: 1.5em 0 !important;
  463. color: #059669 !important;
  464. }
  465. .translate-problem-statement table thead th {
  466. border: 1px #ccc solid !important;
  467. color: #059669 !important;
  468. }
  469. .translate-problem-statement table td {
  470. border-right: 1px solid #ccc;
  471. border-top: 1px solid #ccc;
  472. padding: 0.7143em 0.5em;
  473. }
  474. .translate-problem-statement table th {
  475. padding: 0.7143em 0.5em;
  476. }
  477. .translate-problem-statement p:not(:first-child) {
  478. margin: 1.5em 0 0;
  479. }
  480. .translate-problem-statement p {
  481. line-height: 20px !important;
  482. }
  483. /*设置面板*/
  484. header .enter-or-register-box, header .languages {
  485. position: absolute;
  486. right: 170px;
  487. }
  488. button.html2mdButton.CFBetter_setting {
  489. float: right;
  490. height: 30px;
  491. background: #60a5fa;
  492. color: white;
  493. margin: 10px;
  494. border: 0px;
  495. }
  496.  
  497. button.html2mdButton.CFBetter_setting.open {
  498. background-color: #e6e6e6;
  499. color: #727378;
  500. cursor: not-allowed;
  501. }
  502.  
  503. .CFBetter_setting_menu {
  504. z-index: 9999;
  505. box-shadow: 0px 0px 0px 4px #ffffff;
  506. display: grid;
  507. position: fixed;
  508. top: 50%;
  509. left: 50%;
  510. width: 485px;
  511. max-height: 90vh;
  512. overflow-y: auto;
  513. transform: translate(-50%, -50%);
  514. border-radius: 6px;
  515. background-color: #edf1ff;
  516. border-collapse: collapse;
  517. border: 1px solid #ffffff;
  518. color: #697e91;
  519. font-family: var(--vp-font-family-base);
  520. padding: 10px 20px 20px 20px;
  521. box-sizing: content-box;
  522. }
  523. .CFBetter_setting_menu h3 {
  524. margin-top: 10px;
  525. }
  526. .CFBetter_setting_menu h4,.CFBetter_setting_menu h5 {
  527. font-weight: 600;
  528. }
  529. .CFBetter_setting_menu hr {
  530. border: none;
  531. height: 1px;
  532. background-color: #ccc;
  533. margin: 10px 0;
  534. }
  535. /*设置面板-滚动条*/
  536. .CFBetter_setting_menu::-webkit-scrollbar {
  537. width: 5px;
  538. height: 7px;
  539. background-color: #aaa;
  540. }
  541. .CFBetter_setting_menu::-webkit-scrollbar-thumb {
  542. background-clip: padding-box;
  543. background-color: #d7d9e4;
  544. }
  545. .CFBetter_setting_menu::-webkit-scrollbar-track {
  546. background-color: #f1f1f1;
  547. }
  548. /*设置面板-关闭按钮*/
  549. .CFBetter_setting_menu .tool-box {
  550. position: absolute;
  551. align-items: center;
  552. justify-content: center;
  553. width: 20px;
  554. height: 20px;
  555. overflow: hidden;
  556. border-radius: 10px;
  557. top: 3px;
  558. right: 3px;
  559. }
  560.  
  561. .CFBetter_setting_menu .btn-close {
  562. display: flex;
  563. text-align: center;
  564. width: 20px;
  565. height: 20px;
  566. color: transparent;
  567. font-size: 0;
  568. cursor: pointer;
  569. background-color: #ff000080;
  570. border: none;
  571. margin: 0px;
  572. padding: 0px;
  573. overflow: hidden;
  574. transition: .15s ease all;
  575. align-items: center;
  576. justify-content: center;
  577. box-sizing: border-box;
  578. }
  579.  
  580. .CFBetter_setting_menu .btn-close:hover {
  581. width: 20px;
  582. height: 20px !important;
  583. font-size: 17px;
  584. color: #ffffff;
  585. background-color: #ff0000cc;
  586. box-shadow: 0 5px 5px 0 #00000026;
  587. }
  588.  
  589. .CFBetter_setting_menu .btn-close:active {
  590. width: 20px;
  591. height: 20px;
  592. font-size: 1px;
  593. color: #ffffffde;
  594. --shadow-btn-close: 0 3px 3px 0 #00000026;
  595. box-shadow: var(--shadow-btn-close);
  596. }
  597.  
  598. /*设置面板-checkbox*/
  599. .CFBetter_setting_menu input[type=checkbox]:focus {
  600. outline: 0px;
  601. }
  602.  
  603. .CFBetter_setting_menu input[type="checkbox"] {
  604. margin: 0px;
  605. appearance: none;
  606. -webkit-appearance: none;
  607. width: 40px;
  608. height: 20px !important;
  609. border: 1.5px solid #D7CCC8;
  610. padding: 0px !important;
  611. border-radius: 20px;
  612. background: #efebe978;
  613. position: relative;
  614. box-sizing: border-box;
  615. }
  616.  
  617. .CFBetter_setting_menu input[type="checkbox"]::before {
  618. content: "";
  619. width: 14px;
  620. height: 14px;
  621. background: #D7CCC8;
  622. border: 1.5px solid #BCAAA4;
  623. border-radius: 50%;
  624. position: absolute;
  625. top: 0;
  626. left: 0;
  627. transform: translate(2%, 2%);
  628. transition: all 0.3s ease-in-out;
  629. }
  630.  
  631. .CFBetter_setting_menu input[type="checkbox"]::after {
  632. 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");
  633. position: absolute;
  634. top: 0;
  635. left: 24px;
  636. }
  637.  
  638. .CFBetter_setting_menu input[type="checkbox"]:checked {
  639. border: 1.5px solid #C5CAE9;
  640. background: #E8EAF6;
  641. }
  642.  
  643. .CFBetter_setting_menu input[type="checkbox"]:checked::before {
  644. background: #C5CAE9;
  645. border: 1.5px solid #7986CB;
  646. transform: translate(122%, 2%);
  647. transition: all 0.3s ease-in-out;
  648. }
  649.  
  650. .CFBetter_setting_menu input[type="checkbox"]:checked::after {
  651. 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");
  652. position: absolute;
  653. top: 1.5px;
  654. left: 4.5px;
  655. }
  656.  
  657. .CFBetter_setting_menu label {
  658. font-size: 16px;
  659. }
  660.  
  661. .CFBetter_setting_list {
  662. display: flex;
  663. align-items: center;
  664. padding: 10px;
  665. margin: 5px 0px;
  666. background-color: #ffffff;
  667. border-bottom: 1px solid #c9c6c696;
  668. border-radius: 8px;
  669. justify-content: space-between;
  670. }
  671.  
  672. /*设置面板-radio*/
  673. .CFBetter_setting_menu>label {
  674. display: grid;
  675. list-style-type: none;
  676. padding-inline-start: 0px;
  677. overflow-x: auto;
  678. max-width: 100%;
  679. margin: 0px;
  680. align-items: center;
  681. margin: 3px 0px;
  682. }
  683.  
  684. .CFBetter_setting_menu_label_text {
  685. display: flex;
  686. border: 1px dashed #00aeeccc;
  687. height: 35px;
  688. width: 100%;
  689. color: gray;
  690. font-weight: 300;
  691. font-size: 14px;
  692. letter-spacing: 2px;
  693. padding: 7px;
  694. align-items: center;
  695. -webkit-box-sizing: border-box;
  696. -moz-box-sizing: border-box;
  697. box-sizing: border-box;
  698. }
  699.  
  700. input[type="radio"]:checked+.CFBetter_setting_menu_label_text {
  701. background: #41e49930;
  702. border: 1px solid green;
  703. color: green;
  704. font-weight: 500;
  705. }
  706.  
  707. .CFBetter_setting_menu label input[type="radio"] {
  708. appearance: none;
  709. list-style: none;
  710. padding: 0px !important;
  711. margin: 0px;
  712. clip: rect(0 0 0 0);
  713. -webkit-clip-path: inset(100%);
  714. clip-path: inset(100%);
  715. height: 1px;
  716. overflow: hidden;
  717. position: absolute;
  718. white-space: nowrap;
  719. width: 1px;
  720. }
  721.  
  722. .CFBetter_setting_menu input[type="text"] {
  723. display: block;
  724. height: 25px !important;
  725. width: 100%;
  726. background-color: #ffffff;
  727. color: #727378;
  728. font-size: 12px;
  729. border-radius: 0.3rem;
  730. padding: 1px 5px !important;
  731. box-sizing: border-box;
  732. margin: 5px 0px 5px 0px;
  733. border: 1px solid #00aeeccc;
  734. box-shadow: 0 0 1px #0000004d;
  735. }
  736.  
  737. .CFBetter_setting_menu input[type="text"]:focus-visible{
  738. border-style: solid;
  739. border-color: #3f51b5;
  740. outline: none;
  741. }
  742.  
  743. .CFBetter_setting_menu_input {
  744. width: 100%;
  745. display: grid;
  746. margin-top: 5px;
  747. -webkit-box-sizing: border-box;
  748. -moz-box-sizing: border-box;
  749. box-sizing: border-box;
  750. }
  751. .CFBetter_setting_menu input::placeholder {
  752. color: #727378;
  753. }
  754. .CFBetter_setting_menu input.no_default::placeholder{
  755. color: #BDBDBD;
  756. }
  757. .CFBetter_setting_menu input.is_null::placeholder{
  758. color: red;
  759. border-width: 1.5px;
  760. }
  761. .CFBetter_setting_menu input.is_null{
  762. border-color: red;
  763. }
  764. .CFBetter_setting_menu textarea {
  765. display: block;
  766. width: 100%;
  767. height: 60px;
  768. background-color: #ffffff;
  769. color: #727378;
  770. font-size: 12px;
  771. padding: 1px 5px !important;
  772. box-sizing: border-box;
  773. margin: 5px 0px 5px 0px;
  774. border: 1px solid #00aeeccc;
  775. box-shadow: 0 0 1px #0000004d;
  776. }
  777. .CFBetter_setting_menu textarea:focus-visible{
  778. border-style: solid;
  779. border-color: #3f51b5;
  780. outline: none;
  781. }
  782. .CFBetter_setting_menu textarea::placeholder{
  783. color: #BDBDBD;
  784. font-size: 14px;
  785. }
  786.  
  787. .CFBetter_setting_menu #save {
  788. cursor: pointer;
  789. display: inline-flex;
  790. padding: 5px;
  791. background-color: #1aa06d;
  792. color: #ffffff;
  793. font-size: 14px;
  794. line-height: 1.5rem;
  795. font-weight: 500;
  796. justify-content: center;
  797. width: 100%;
  798. border-radius: 0.375rem;
  799. border: none;
  800. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  801. margin-top: 20px
  802. }
  803. .CFBetter_setting_menu button#debug_button.debug_button {
  804. width: 18%;
  805. }
  806.  
  807. .CFBetter_setting_menu span.tip {
  808. color: #999;
  809. font-size: 12px;
  810. font-weight: 500;
  811. padding: 5px 0px;
  812. }
  813. /*设置面板-tip*/
  814. .help_tip {
  815. margin-right: auto;
  816. }
  817. span.input_label {
  818. font-size: 14px;
  819. }
  820. .help_tip .tip_text {
  821. display: none;
  822. position: absolute;
  823. color: #697e91;
  824. font-weight: 400;
  825. font-size: 14px;
  826. letter-spacing: 0px;
  827. background-color: #ffffff;
  828. padding: 10px;
  829. margin: 5px 0px;
  830. border-radius: 4px;
  831. border: 1px solid #e4e7ed;
  832. box-shadow: 0px 0px 12px rgba(0, 0, 0, .12);
  833. z-index: 999;
  834. }
  835. .help_tip .tip_text p {
  836. margin-bottom: 5px;
  837. }
  838. .help_tip .tip_text:before {
  839. content: "";
  840. position: absolute;
  841. top: -20px;
  842. right: -10px;
  843. bottom: -10px;
  844. left: -10px;
  845. z-index: -1;
  846. }
  847. .help-icon {
  848. cursor: help;
  849. width: 15px;
  850. color: #b4b9d4;
  851. margin-left: 5px;
  852. margin-top: 3px;
  853. }
  854. .CFBetter_setting_menu .CFBetter_setting_menu_label_text .help_tip .help-icon {
  855. color: #7fbeb2;
  856. }
  857. .help_tip .help-icon:hover + .tip_text, .help_tip .tip_text:hover {
  858. display: block;
  859. cursor: help;
  860. width: 250px;
  861. }
  862.  
  863. /*确认弹窗*/
  864. .wordsExceeded {
  865. z-index: 9999;
  866. box-shadow: 0px 0px 5px 1px rgb(0 0 0 / 10%), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  867. display: grid;
  868. position: fixed;
  869. top: 50%;
  870. left: 50%;
  871. transform: translate(-50%, -50%);
  872. border-radius: 4px;
  873. background-color: #ffffff;
  874. border: 1px solid #e4e7ed;
  875. color: #697e91;
  876. font-family: var(--vp-font-family-base);
  877. padding: 10px 20px 20px 20px;
  878. }
  879. .wordsExceeded button {
  880. display: inline-flex;
  881. justify-content: center;
  882. align-items: center;
  883. line-height: 1;
  884. white-space: nowrap;
  885. cursor: pointer;
  886. text-align: center;
  887. box-sizing: border-box;
  888. outline: none;
  889. transition: .1s;
  890. user-select: none;
  891. vertical-align: middle;
  892. -webkit-appearance: none;
  893. height: 24px;
  894. padding: 5px 11px;
  895. font-size: 12px;
  896. border-radius: 4px;
  897. color: #ffffff;
  898. background: #409eff;
  899. border-color: #409eff;
  900. border: none;
  901. margin-right: 12px;
  902. }
  903. .wordsExceeded button:hover{
  904. background-color:#79bbff;
  905. }
  906. .wordsExceeded .help-icon {
  907. margin: 0px 8px 0px 0px;
  908. height: 1em;
  909. width: 1em;
  910. line-height: 1em;
  911. display: inline-flex;
  912. justify-content: center;
  913. align-items: center;
  914. position: relative;
  915. fill: currentColor;
  916. font-size: inherit;
  917. }
  918. .wordsExceeded p {
  919. margin: 5px 0px;
  920. }
  921. /*更新检查*/
  922. div#update_panel {
  923. z-index: 9999;
  924. position: fixed;
  925. top: 50%;
  926. left: 50%;
  927. width: 240px;
  928. transform: translate(-50%, -50%);
  929. box-shadow: 0px 0px 4px 0px #0000004d;
  930. padding: 10px 20px 20px 20px;
  931. color: #444242;
  932. background-color: #f5f5f5;
  933. border: 1px solid #848484;
  934. border-radius: 8px;
  935. }
  936. div#update_panel #updating {
  937. cursor: pointer;
  938. display: inline-flex;
  939. padding: 3px;
  940. background-color: #1aa06d;
  941. color: #ffffff;
  942. font-size: 14px;
  943. line-height: 1.5rem;
  944. font-weight: 500;
  945. justify-content: center;
  946. width: 100%;
  947. border-radius: 0.375rem;
  948. border: none;
  949. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  950. }
  951. div#update_panel #updating a {
  952. text-decoration: none;
  953. color: white;
  954. display: flex;
  955. position: inherit;
  956. top: 0;
  957. left: 0;
  958. width: 100%;
  959. height: 22px;
  960. font-size: 14px;
  961. justify-content: center;
  962. align-items: center;
  963. }
  964. #skip_menu {
  965. display: flex;
  966. margin-top: 10px;
  967. justify-content: flex-end;
  968. align-items: center;
  969. }
  970. #skip_menu .help_tip {
  971. margin-right: 5px;
  972. margin-left: -5px;
  973. }
  974. #skip_menu .help-icon {
  975. color: #f44336;
  976. }
  977. /* 配置管理 */
  978. .embed-responsive {
  979. height: max-content;
  980. padding-bottom: 0px;
  981. }
  982. .config_bar {
  983. height: 70px;
  984. width: 100%;
  985. display: flex;
  986. justify-content: space-between;
  987. }
  988. li#add_button {
  989. cursor: pointer;
  990. height: 40px;
  991. border: 1px dashed #BDBDBD;
  992. border-radius: 8px;
  993. background-color: #fcfbfb36;
  994. color: #bdbdbd;
  995. font-size: 14px;
  996. align-items: center;
  997. justify-content: center;
  998. }
  999. li#add_button:hover {
  1000. border: 1px dashed #03A9F4;
  1001. background-color: #d7f0fb8c;
  1002. color: #03A9F4;
  1003. }
  1004. div#config_bar_list {
  1005. display: flex;
  1006. width: 480px;
  1007. border: 1px solid #c5cae9;
  1008. border-radius: 8px;
  1009. background-color: #f0f8ff;
  1010. box-sizing: border-box;
  1011. }
  1012. div#config_bar_list input[type="radio"] {
  1013. appearance: none;
  1014. width: 0;
  1015. height: 0;
  1016. overflow: hidden;
  1017. }
  1018. div#config_bar_list input[type="radio"] {
  1019. margin: 0px;
  1020. }
  1021. div#config_bar_list input[type=radio]:focus {
  1022. outline: 0px;
  1023. }
  1024. label.config_bar_ul_li_text {
  1025. display: flex;
  1026. align-items: center;
  1027. justify-content: center;
  1028. max-width: 100%;
  1029. height: 40px;
  1030. overflow-x: auto;
  1031. font-size: 14px;
  1032. font-weight: 400;
  1033. margin: 0px 4px;
  1034. padding: 3px;
  1035. border: 1px solid #dedede;
  1036. border-radius: 10px;
  1037. box-shadow: 0px 2px 4px 0px rgba(0,0,0,.05);
  1038. box-sizing: border-box;
  1039. }
  1040. ul#config_bar_ul li button {
  1041. background-color: #e6e6e6;
  1042. color: #727378;
  1043. height: 23px;
  1044. font-size: 14px;
  1045. border-radius: 0.3rem;
  1046. padding: 1px 5px;
  1047. margin: 5px;
  1048. border: none;
  1049. box-shadow: 0 0 1px #0000004d;
  1050. }
  1051. ul#config_bar_ul {
  1052. display: flex;
  1053. align-items: center;
  1054. list-style-type: none;
  1055. padding-inline-start: 0px;
  1056. overflow-x: auto;
  1057. max-width: 100%;
  1058. margin: 0px;
  1059. }
  1060. ul#config_bar_ul li {
  1061. width: 80px;
  1062. display: grid;
  1063. margin: 4px 4px;
  1064. min-width: 100px;
  1065. box-sizing: border-box;
  1066. }
  1067. label.config_bar_ul_li_text:hover {
  1068. background-color: #eae4dc24;
  1069. }
  1070. input[type="radio"]:checked + .config_bar_ul_li_text {
  1071. background: #41b3e430;
  1072. border: 1px solid #5e7ce0;
  1073. color: #5e7ce0;
  1074. }
  1075. ul#config_bar_ul::-webkit-scrollbar {
  1076. width: 5px;
  1077. height: 5px;
  1078. }
  1079. ul#config_bar_ul::-webkit-scrollbar-thumb {
  1080. background-clip: padding-box;
  1081. background-color: #d7d9e4;
  1082. border-radius: 8px;
  1083. }
  1084. ul#config_bar_ul::-webkit-scrollbar-button:start:decrement {
  1085. width: 4px;
  1086. background-color: transparent;
  1087. }
  1088. ul#config_bar_ul::-webkit-scrollbar-button:end:increment {
  1089. width: 4px;
  1090. background-color: transparent;
  1091. }
  1092. ul#config_bar_ul::-webkit-scrollbar-track {
  1093. background-color: #f1f1f1;
  1094. border-radius: 5px;
  1095. }
  1096. label.config_bar_ul_li_text::-webkit-scrollbar {
  1097. width: 5px;
  1098. height: 7px;
  1099. background-color: #aaa;
  1100. }
  1101. label.config_bar_ul_li_text::-webkit-scrollbar-thumb {
  1102. background-clip: padding-box;
  1103. background-color: #d7d9e4;
  1104. }
  1105. label.config_bar_ul_li_text::-webkit-scrollbar-track {
  1106. background-color: #f1f1f1;
  1107. }
  1108. .config_bar_list_add_div {
  1109. display: flex;
  1110. height: 40px;
  1111. margin: 4px 2px;
  1112. }
  1113. /* 修改菜单 */
  1114. div#config_bar_menu {
  1115. z-index: 99999;
  1116. position: absolute;
  1117. width: 60px;
  1118. background: #ffffff;
  1119. box-shadow: 1px 1px 4px 0px #0000004d;
  1120. border: 0px solid rgba(0,0,0,0.04);
  1121. border-radius: 4px;
  1122. padding: 8px 0;
  1123. }
  1124. div.config_bar_menu_item {
  1125. cursor: pointer;
  1126. padding: 2px 6px;
  1127. display: flex;
  1128. justify-content: center;
  1129. align-items: center;
  1130. height: 32px;
  1131. color: rgba(0,0,0,0.75);
  1132. font-size: 14px;
  1133. font-weight: 500;
  1134. box-shadow: inset 0px 0px 0px 0px #8bb2d9;
  1135. }
  1136. div#config_bar_menu_edit:hover {
  1137. background-color: #00aeec;
  1138. color: white;
  1139. }
  1140. div#config_bar_menu_delete:hover {
  1141. background-color: #FF5722;
  1142. color: white;
  1143. }
  1144. /* 配置页面 */
  1145. #config_edit_menu {
  1146. z-index: 11000;
  1147. width: 450px;
  1148. }
  1149. /* 黑暗模式选项 */
  1150. .dark-mode-selection {
  1151. display: flex;
  1152. justify-content: center;
  1153. align-items: center;
  1154. max-width: 350px;
  1155. -webkit-user-select: none;
  1156. -moz-user-select: none;
  1157. -ms-user-select: none;
  1158. user-select: none;
  1159. }
  1160. .dark-mode-selection > * {
  1161. margin: 6px;
  1162. }
  1163. .dark-mode-selection .CFBetter_setting_menu_label_text {
  1164. border-radius: 8px;
  1165. }
  1166. `);
  1167.  
  1168. // 工具
  1169. // 获取cookie
  1170. function getCookie(name) {
  1171. const cookies = document.cookie.split(";");
  1172. for (let i = 0; i < cookies.length; i++) {
  1173. const cookie = cookies[i].trim();
  1174. const [cookieName, cookieValue] = cookie.split("=");
  1175.  
  1176. if (cookieName === name) {
  1177. return decodeURIComponent(cookieValue);
  1178. }
  1179. }
  1180. return "";
  1181. }
  1182.  
  1183. // 防抖函数
  1184. function debounce(callback) {
  1185. let timer;
  1186. let immediateExecuted = false;
  1187. const delay = 500;
  1188. return function () {
  1189. clearTimeout(timer);
  1190. if (!immediateExecuted) { callback.call(this); immediateExecuted = true; }
  1191. timer = setTimeout(() => { immediateExecuted = false; }, delay);
  1192. };
  1193. }
  1194.  
  1195. // 为元素添加鼠标拖动
  1196. function addDraggable(element) {
  1197. let isDragging = false;
  1198. let initialX, initialY; // 元素的初始位置
  1199. let startX, startY, offsetX, offsetY; // 鼠标起始位置,移动偏移量
  1200. let isSpecialMouseDown = false; // 选取某些元素时不拖动
  1201.  
  1202. element.on('mousedown', function (e) {
  1203. var elem = $(this);
  1204. var elemOffset = elem.offset();
  1205. var centerX = elemOffset.left + elem.outerWidth() / 2;
  1206. var centerY = elemOffset.top + elem.outerHeight() / 2;
  1207. initialX = centerX - window.pageXOffset;
  1208. initialY = centerY - window.pageYOffset;
  1209.  
  1210. isDragging = true;
  1211. startX = e.clientX;
  1212. startY = e.clientY;
  1213.  
  1214. isSpecialMouseDown = $(e.target).is('label, p, input, textarea, span');
  1215. if (isSpecialMouseDown) return;
  1216. $('body').css('cursor', 'all-scroll');
  1217. });
  1218.  
  1219. $(document).on('mousemove', function (e) {
  1220. if (!isDragging) return;
  1221. // 不执行拖动操作
  1222. if ($(e.target).is('label, p, input, textarea, span') || isSpecialMouseDown && !$(e.target).is('input, textarea')) return;
  1223. e.preventDefault();
  1224. offsetX = e.clientX - startX;
  1225. offsetY = e.clientY - startY;
  1226. element.css({ top: initialY + offsetY + 'px', left: initialX + offsetX + 'px' });
  1227. });
  1228.  
  1229. $(document).on('mouseup', function () {
  1230. isDragging = false;
  1231. isSpecialMouseDown = false;
  1232. $('body').css('cursor', 'default');
  1233. });
  1234. }
  1235.  
  1236. // 更新检查
  1237. function checkScriptVersion() {
  1238. function compareVersions(version1 = "0", version2 = "0") {
  1239. const v1Array = String(version1).split(".");
  1240. const v2Array = String(version2).split(".");
  1241. const minLength = Math.min(v1Array.length, v2Array.length);
  1242. let result = 0;
  1243. for (let i = 0; i < minLength; i++) {
  1244. const curV1 = Number(v1Array[i]);
  1245. const curV2 = Number(v2Array[i]);
  1246. if (curV1 > curV2) {
  1247. result = 1;
  1248. break;
  1249. } else if (curV1 < curV2) {
  1250. result = -1;
  1251. break;
  1252. }
  1253. }
  1254. if (result === 0 && v1Array.length !== v2Array.length) {
  1255. const v1IsBigger = v1Array.length > v2Array.length;
  1256. const maxLenArray = v1IsBigger ? v1Array : v2Array;
  1257. for (let i = minLength; i < maxLenArray.length; i++) {
  1258. const curVersion = Number(maxLenArray[i]);
  1259. if (curVersion > 0) {
  1260. v1IsBigger ? result = 1 : result = -1;
  1261. break;
  1262. }
  1263. }
  1264. }
  1265. return result;
  1266. }
  1267.  
  1268. GM_xmlhttpRequest({
  1269. method: "GET",
  1270. url: "https://greasyfork.org/zh-CN/scripts/465777.json",
  1271. timeout: 10 * 1e3,
  1272. onload: function (response) {
  1273. const scriptData = JSON.parse(response.responseText);
  1274. const skipUpdate = getCookie("skipUpdate");
  1275.  
  1276. if (
  1277. scriptData.name === GM_info.script.name &&
  1278. compareVersions(scriptData.version, GM_info.script.version) === 1 &&
  1279. skipUpdate !== "true"
  1280. ) {
  1281. const styleElement = GM_addStyle(darkenPageStyle);
  1282. $("body").append(`
  1283. <div id='update_panel'>
  1284. <h3>${GM_info.script.name}有新版本!</h3>
  1285. <hr>
  1286. <div class='update_panel_menu'>
  1287. <span class ='tip'>版本信息:${GM_info.script.version} ${scriptData.version}</span>
  1288. </div>
  1289. <br>
  1290. <div id="skip_menu">
  1291. <div class="help_tip">
  1292. `+ helpCircleHTML + `
  1293. <div class="tip_text">
  1294. <p><b>更新遇到了问题?</b></p>
  1295. <p>由于 Greasyfork 平台的原因,当新版本刚发布时,点击 Greasyfork 上的更新按钮<u>可能</u>会出现<u>实际更新/安装的却是上一个版本</u>的情况</p>
  1296. <p>通常你只需要稍等几分钟,然后再次前往更新/安装即可</p>
  1297. <p>你也可以<u>点击下方按钮,在本次浏览器会话期间将不再提示更新</u></p>
  1298. <button id='skip_update' class='html2mdButton'>暂不更新</button>
  1299. </div>
  1300. </div>
  1301. <button id='updating'><a target="_blank" href="${scriptData.url}">更新</a></button>
  1302. </div>
  1303. </div>
  1304. `);
  1305.  
  1306. $("#skip_update").click(function () {
  1307. document.cookie = "skipUpdate=true; expires=session; path=/";
  1308. styleElement.remove();
  1309. $("#update_panel").remove();
  1310. });
  1311. }
  1312. }
  1313. });
  1314.  
  1315. };
  1316.  
  1317. // 汉化替换
  1318. function toZH_CN() {
  1319. if (!bottomZh_CN) return;
  1320. // 设置语言为zh
  1321. var htmlTag = document.getElementsByTagName("html")[0];
  1322. htmlTag.setAttribute("lang", "zh-CN");
  1323.  
  1324. // 文本节点遍历替换
  1325. function traverseTextNodes(node, rules) {
  1326. if (!node) return;
  1327. if (node.nodeType === Node.TEXT_NODE) {
  1328. rules.forEach(rule => {
  1329. const regex = new RegExp(rule.match, 'g');
  1330. node.textContent = node.textContent.replace(regex, rule.replace);
  1331. });
  1332. } else {
  1333. $(node).contents().each((_, child) => traverseTextNodes(child, rules));
  1334. }
  1335. }
  1336.  
  1337. // 严格
  1338. function strictTraverseTextNodes(node, rules) {
  1339. if (!node) return;
  1340. if (node.nodeType === Node.TEXT_NODE) {
  1341. const nodeText = node.textContent.trim();
  1342. rules.forEach(rule => {
  1343. if (nodeText === rule.match) {
  1344. node.textContent = rule.replace;
  1345. }
  1346. });
  1347. } else {
  1348. $(node).contents().each((_, child) => strictTraverseTextNodes(child, rules));
  1349. }
  1350. }
  1351.  
  1352. const rules1 = [
  1353. { match: 'Virtual participation', replace: '参加虚拟重现赛' },
  1354. { match: 'Enter', replace: '进入' },
  1355. { match: 'Current standings', replace: '当前榜单' },
  1356. { match: 'Final standings', replace: '最终榜单' },
  1357. { match: 'Preliminary results', replace: '初步结果' },
  1358. { match: 'open hacking:', replace: '公开黑客攻击中(即尝试提交数据加强,对已通过的代码重测)' },
  1359. { match: 'School/University/City/Region Championship', replace: '学校/大学/城市/区域比赛' },
  1360. { match: 'Official School Contest', replace: '学校官方比赛' },
  1361. { match: 'Training Contest', replace: '训练赛' },
  1362. { match: 'Training Camp Contest', replace: '训练营比赛' },
  1363. { match: 'Official ICPC Contest', replace: 'ICPC官方比赛' },
  1364. { match: 'Official International Personal Contest', replace: '官方国际个人赛' },
  1365. { match: 'China', replace: '中国' },
  1366. { match: 'Statements', replace: '题目描述' },
  1367. { match: 'in Chinese', replace: '中文' },
  1368. { match: 'Trainings', replace: '训练' },
  1369. { match: 'Prepared by', replace: '编写人' },
  1370. { match: 'Current or upcoming contests', replace: '当前或即将举行的比赛' },
  1371. { match: 'Past contests', replace: '过去的比赛' },
  1372. { match: 'Exclusions', replace: '排除' },
  1373. { match: 'Before start', replace: '距比赛开始还有' },
  1374. { match: 'Before registration', replace: '距报名开始还有' },
  1375. { match: 'Until closing ', replace: '距报名结束还有' },
  1376. { match: 'Before extra registration', replace: '额外报名还未开始' },
  1377. { match: 'Register »', replace: '报名 »' },
  1378. { match: 'Registration completed', replace: '已报名' },
  1379. { match: 'Registration closed', replace: '报名已结束' },
  1380. { match: 'Problems', replace: '问题集' },
  1381. { match: 'Questions about problems', replace: '关于问题的提问' },
  1382. { match: 'Contest status', replace: '比赛状态' },
  1383. ];
  1384. traverseTextNodes($('.datatable'), rules1);
  1385.  
  1386. const rules2 = [
  1387. { match: 'Home', replace: '主页' },
  1388. { match: 'Top', replace: '热门' },
  1389. { match: 'Catalog', replace: '指南目录' },
  1390. { match: 'Contests', replace: '比赛' },
  1391. { match: 'Gym', replace: '训练营' },
  1392. { match: 'Problemset', replace: '题单' },
  1393. { match: 'Groups', replace: '团体' },
  1394. { match: 'Rating', replace: 'Rating(评级)排行榜' },
  1395. { match: 'Edu', replace: '培训' },
  1396. { match: 'Calendar', replace: '日历' },
  1397. { match: 'Help', replace: '帮助' }
  1398. ];
  1399. traverseTextNodes($('.menu-list.main-menu-list'), rules2);
  1400.  
  1401. const rules3 = [
  1402. { match: 'Settings', replace: '设置' },
  1403. { match: 'Blog', replace: '博客' },
  1404. { match: 'Teams', replace: '队伍' },
  1405. { match: 'Submissions', replace: '提交' },
  1406. { match: 'Favourites', replace: '收藏' },
  1407. { match: 'Talks', replace: '私信' },
  1408. { match: 'Contests', replace: '比赛' },
  1409. ];
  1410. traverseTextNodes($('.nav-links'), rules3);
  1411.  
  1412. const rules4 = [
  1413. { match: 'Before contest', replace: '即将进行的比赛' },
  1414. { match: 'Contest is running', replace: '比赛进行中' },
  1415. ];
  1416. traverseTextNodes($('.contest-state-phase'), rules4);
  1417.  
  1418. const rules5 = [
  1419. { match: 'has extra registration', replace: '有额外的报名时期' },
  1420. { match: 'If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes.', replace: '如果您在比赛开始前5分钟前还未报名,您可以在额外的报名期间稍后报名。额外的报名将在比赛开始后10分钟开放,并持续25分钟。' },
  1421. ];
  1422. traverseTextNodes($('.notice'), rules5);
  1423.  
  1424. const rules6 = [
  1425. { match: 'Contribution', replace: '贡献' },
  1426. ];
  1427. traverseTextNodes($('.propertyLinks'), rules6);
  1428.  
  1429. const rules7 = [
  1430. { match: 'Contest history', replace: '比赛历史' },
  1431. ];
  1432. traverseTextNodes($('.contests-table'), rules7);
  1433.  
  1434. const rules8 = [
  1435. { match: 'Register now', replace: '现在报名' },
  1436. { match: 'No tag edit access', replace: '没有标签编辑权限' },
  1437. { match: 'Language:', replace: '语言:' },
  1438. { match: 'Choose file:', replace: '选择文件:' },
  1439. ];
  1440. traverseTextNodes($('.roundbox.sidebox.borderTopRound '), rules8);
  1441.  
  1442. const rules9 = [
  1443. { match: 'Add to exclusions', replace: '添加到排除列表' },
  1444. ];
  1445. traverseTextNodes($('.icon-eye-close.icon-large'), rules9);
  1446.  
  1447. const rules10 = [
  1448. { match: 'Add to exclusions for gym contests filter', replace: '添加训练营过滤器的排除项' },
  1449. ];
  1450. traverseTextNodes($("._ContestFilterExclusionsManageFrame_addExclusionLink"), rules10);
  1451.  
  1452. const rules11 = [
  1453. { match: 'Announcement', replace: '公告' },
  1454. { match: 'Statements', replace: '统计报表' },
  1455. { match: 'Tutorial', replace: '题解' },
  1456. ];
  1457. traverseTextNodes($('.roundbox.sidebox.sidebar-menu.borderTopRound '), rules11);
  1458.  
  1459. const rules12 = [
  1460. { match: 'Problems', replace: '问题' },
  1461. { match: 'Submit Code', replace: '提交代码' },
  1462. { match: 'My Submissions', replace: '我的提交' },
  1463. { match: 'Status', replace: '状态' },
  1464. { match: 'Standings', replace: '榜单' },
  1465. { match: 'Custom Invocation', replace: '自定义调试' },
  1466. { match: 'Common standings', replace: '全部排行' },
  1467. { match: 'Friends standings', replace: '只看朋友' },
  1468. { match: 'Submit', replace: '提交' },
  1469. { match: 'Hacks', replace: '黑客' },
  1470. { match: 'Room', replace: '房间' },
  1471. { match: 'Custom test', replace: '自定义测试' },
  1472. { match: 'Blog', replace: '博客' },
  1473. { match: 'Teams', replace: '队伍' },
  1474. { match: 'Submissions', replace: '提交记录' },
  1475. { match: 'Groups', replace: '团体' },
  1476. { match: 'Favourites', replace: '收藏' },
  1477. { match: 'Contests', replace: '比赛' },
  1478. { match: 'Members', replace: '成员' },
  1479. { match: '问题etting', replace: '参与编写的问题' },
  1480. { match: 'Streams', replace: '直播' },
  1481. { match: 'Gym', replace: '训练营' },
  1482. { match: 'Mashups', replace: '组合混搭' },
  1483. { match: 'Posts', replace: '帖子' },
  1484. { match: 'Comments', replace: '回复' },
  1485. { match: 'Main', replace: '主要的' },
  1486. { match: 'Settings', replace: '设置' },
  1487. { match: 'Lists', replace: '列表' },
  1488. { match: 'General', replace: '基本' },
  1489. { match: 'Sidebar', replace: '侧边栏' },
  1490. { match: 'Social', replace: '社会信息' },
  1491. { match: 'Address', replace: '地址' },
  1492. { match: 'Wallets', replace: '钱包' },
  1493. ];
  1494. traverseTextNodes($('.second-level-menu'), rules12);
  1495. if (is_mSite) {
  1496. traverseTextNodes($('nav'), rules12);
  1497. }
  1498.  
  1499. const rules13 = [
  1500. { match: 'Expand', replace: '展开' }
  1501. ];
  1502. traverseTextNodes($('.topic-toggle-collapse'), rules13);
  1503.  
  1504. const rules14 = [
  1505. { match: 'Full text and comments', replace: '阅读全文/评论' }
  1506. ];
  1507. traverseTextNodes($('.topic-read-more'), rules14);
  1508.  
  1509. const rules15 = [
  1510. { match: 'Switch off editor', replace: '关闭编辑器语法高亮' }
  1511. ];
  1512. traverseTextNodes($('.toggleEditorCheckboxLabel'), rules15);
  1513.  
  1514. const rules16 = [
  1515. { match: 'Registration for the contest', replace: '比赛报名' }
  1516. ];
  1517. traverseTextNodes($('.submit'), rules16);
  1518.  
  1519. const rules17 = [
  1520. { match: 'Difficulty:', replace: '难度:' },
  1521. ];
  1522. traverseTextNodes($('._FilterByTagsFrame_difficulty'), rules17);
  1523.  
  1524. const rules18 = [
  1525. { match: 'Add tag', replace: '添加标签' }
  1526. ];
  1527. traverseTextNodes($('._FilterByTagsFrame_addTagLink'), rules18);
  1528.  
  1529. const rules19 = [
  1530. { match: 'Rating changes for last rounds are temporarily rolled back. They will be returned soon.', replace: '上一轮的评级变化暂时回滚。它们将很快恢复。' },
  1531. { match: 'Reminder: in case of any technical issues, you can use the lightweight website', replace: '提醒:如果出现任何技术问题,您可以使用轻量网站' },
  1532. { match: 'Please subscribe to the official Codeforces channel in Telegram via the link ', replace: '请通过链接订阅Codeforces的官方Telegram频道' }
  1533. ];
  1534. traverseTextNodes($('.alert'), rules19);
  1535.  
  1536. const rules20 = [
  1537. { match: 'Enter', replace: '登录' },
  1538. { match: 'Register', replace: '注册' },
  1539. { match: 'Contest rating', replace: '测试 rating' },
  1540. { match: 'Logout', replace: '退出登录' }
  1541. ];
  1542. traverseTextNodes($('.lang-chooser'), rules20);
  1543.  
  1544. const rules21 = [
  1545. { match: 'Change photo', replace: '更换图片' },
  1546. { match: 'Contest rating', replace: '比赛Rating' },
  1547. { match: 'Contribution', replace: '贡献' },
  1548. { match: 'My friends', replace: '我的好友' },
  1549. { match: 'Change settings', replace: '改变设置' },
  1550. { match: 'Last visit', replace: '最后访问' },
  1551. { match: 'Registered', replace: '注册于' },
  1552. { match: 'Blog entries', replace: '博客条目' },
  1553. { match: 'comments', replace: '评论' },
  1554. { match: 'Write new entry', replace: '编写新条目' },
  1555. { match: 'View my talks', replace: '查看我的私信' },
  1556. { match: 'Talks', replace: '私信' },
  1557. { match: 'Send message', replace: '发送消息' },
  1558. ];
  1559. traverseTextNodes($('.userbox'), rules21);
  1560.  
  1561. const rules22 = [
  1562. { match: 'Reset', replace: '重置' },
  1563. ];
  1564. traverseTextNodes($('#vote-reset-filterDifficultyLowerBorder'), rules22);
  1565. traverseTextNodes($('#vote-reset-filterDifficultyUpperBorder'), rules22);
  1566.  
  1567. const rules23 = [
  1568. { match: 'The problem statement has recently been changed.', replace: '题目描述最近已被更改。\n(说明:有极小概率可能是Codeforces Better!插入翻译按钮导致的)' },
  1569. { match: 'View the changes.', replace: '查看更改' },
  1570. ];
  1571. traverseTextNodes($('.alert.alert-info'), rules23);
  1572.  
  1573. const rules24 = [
  1574. { match: 'Fill in the form to login into Codeforces.', replace: '填写表单以登录到Codeforces。' },
  1575. { match: 'You can use', replace: '你也可以使用' },
  1576. { match: 'as an alternative way to enter.', replace: '登录' },
  1577. ];
  1578. traverseTextNodes($('.enterPage'), rules24);
  1579.  
  1580. const rules25 = [
  1581. { match: '\\* To view the complete list, click ', replace: '* 要查看完整列表,请点击' },
  1582. ];
  1583. traverseTextNodes($('.notice.small'), rules25);
  1584.  
  1585. const rules26 = [
  1586. { match: 'Contest type:', replace: '比赛类型:' },
  1587. { match: 'Rated:', replace: '已评级:' },
  1588. { match: 'Tried:', replace: '已尝试' },
  1589. { match: 'Substring:', replace: '关键字' },
  1590. ];
  1591. traverseTextNodes($('.setting-name'), rules26);
  1592.  
  1593. // 元素选择替换
  1594. // 侧栏titled汉化
  1595. (function () {
  1596. var translations = {
  1597. "Pay attention": "→ 注意",
  1598. "Top rated": "→ 评级排行",
  1599. "Top contributors": "→ 贡献者排行",
  1600. "Find user": "→ 查找用户",
  1601. "Recent actions": "→ 最新动态",
  1602. "Training filter": "→ 过滤筛选",
  1603. "Find training": "→ 搜索比赛/问题",
  1604. "Virtual participation": "→ 什么是虚拟参赛",
  1605. "Contest materials": "→ 比赛相关资料",
  1606. "Settings": "→ 设置",
  1607. "Create Mashup Contest": "→ 克隆比赛到组合混搭",
  1608. "Clone Contest to Mashup": "→ 克隆比赛到组合混搭",
  1609. "Create Mashup Contest": "→ 创建混搭比赛",
  1610. "Submit": "→ 提交",
  1611. "Practice": "→ 练习",
  1612. "Problem tags": "→ 问题标签",
  1613. "Filter Problems": "→ 过滤问题",
  1614. "Attention": "→ 注意",
  1615. "Past contests filter": "→ 过去的比赛筛选",
  1616. "About Contest": "→ 关于比赛",
  1617. "Last submissions": "→ 提交历史",
  1618. "Streams": "→ 直播",
  1619. "Coach rights": "→ 教练权限",
  1620. "Advices to fill address": "→ 填写地址的建议",
  1621. "Hacks filter": "→ 黑客过滤器",
  1622. "Score table": "→ 评分表",
  1623. "Contests": "→ 比赛",
  1624. "History": "→ 编辑历史",
  1625. "Login into Codeforces": "登录 Codeforces",
  1626. };
  1627.  
  1628. $(".caption.titled").each(function () {
  1629. var tag = $(this).text();
  1630. for (var property in translations) {
  1631. if (tag.match(property)) {
  1632. $(this).addClass(property);
  1633. $(this).text(translations[property]);
  1634. break;
  1635. }
  1636. }
  1637. });
  1638. })();
  1639. // 题目Tag汉化
  1640. (function () {
  1641. var parentElement = $('._FilterByTagsFrame_addTagLabel');
  1642. var selectElement = parentElement.find('select');
  1643. var translations = {
  1644. "*combine tags by OR": "*按逻辑或组合我选择的标签",
  1645. "combine-tags-by-or": "*按逻辑或组合我选择的标签(combine-tags-by-or)",
  1646. "2-sat": "二分图可满足性问题(2-sat)",
  1647. "binary search": "二分搜索(binary search)",
  1648. "bitmasks": "位掩码(bitmasks)",
  1649. "brute force": "暴力枚举(brute force)",
  1650. "chinese remainder theorem": "中国剩余定理(chinese remainder theorem)",
  1651. "combinatorics": "组合数学(combinatorics)",
  1652. "constructive algorithms": "构造算法(constructive algorithms)",
  1653. "data structures": "数据结构(data structures)",
  1654. "dfs and similar": "深度优先搜索及其变种(dfs and similar)",
  1655. "divide and conquer": "分治算法(divide and conquer)",
  1656. "dp": "动态规划(dp)",
  1657. "dsu": "并查集(dsu)",
  1658. "expression parsing": "表达式解析(expression parsing)",
  1659. "fft": "快速傅里叶变换(fft)",
  1660. "flows": "流(flows)",
  1661. "games": "博弈论(games)",
  1662. "geometry": "计算几何(geometry)",
  1663. "graph matchings": "图匹配(graph matchings)",
  1664. "graphs": "图论(graphs)",
  1665. "greedy": "贪心策略(greedy)",
  1666. "hashing": "哈希表(hashing)",
  1667. "implementation": "实现问题,编程技巧,模拟(implementation)",
  1668. "interactive": "交互性问题(interactive)",
  1669. "math": "数学(math)",
  1670. "matrices": "矩阵(matrices)",
  1671. "meet-in-the-middle": "meet-in-the-middle算法(meet-in-the-middle)",
  1672. "number theory": "数论(number theory)",
  1673. "probabilities": "概率论(probabilities)",
  1674. "schedules": "调度算法(schedules)",
  1675. "shortest paths": "最短路算法(shortest paths)",
  1676. "sortings": "排序算法(sortings)",
  1677. "string suffix structures": "字符串后缀结构(string suffix structures)",
  1678. "strings": "字符串处理(strings)",
  1679. "ternary search": "三分搜索(ternary search)",
  1680. "trees": "树形结构(trees)",
  1681. "two pointers": "双指针算法(two pointers)"
  1682. };
  1683. selectElement.find("option").each(function () {
  1684. var optionValue = $(this).val();
  1685. if (translations[optionValue]) {
  1686. $(this).text(translations[optionValue]);
  1687. }
  1688. });
  1689. $("._FilterByTagsFrame_tagBoxCaption").each(function () {
  1690. var tag = $(this).text();
  1691. if (tag in translations) {
  1692. $(this).text(translations[tag]);
  1693. }
  1694. });
  1695. $(".notice").each(function () {
  1696. var tag = $(this).text();
  1697. if (tag in translations) {
  1698. $(this).text(translations[tag]);
  1699. }
  1700. });
  1701. $(".tag-box").each(function () {
  1702. var tag = $(this).text();
  1703. for (var property in translations) {
  1704. property = property.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
  1705. if (tag.match(property)) {
  1706. $(this).text(translations[property]);
  1707. break;
  1708. }
  1709. }
  1710. });
  1711. })();
  1712. // 题目过滤器选项汉化
  1713. (function () {
  1714. var parentElement = $('#gym-filter-form');
  1715. var selectElement = parentElement.find('div');
  1716. var translations = {
  1717. "Contest type:": "比赛类型:",
  1718. "ICPC region:": "ICPC地区:",
  1719. "Contest format:": "比赛形式:",
  1720. "Order by:": "排序方式:",
  1721. "Secondary order by:": "次要排序方式:",
  1722. "Hide, if participated:": "隐藏我参加过的:",
  1723. };
  1724. selectElement.find("label").each(function () {
  1725. var optionValue = $(this).text();
  1726. if (translations[optionValue]) {
  1727. $(this).text(translations[optionValue]);
  1728. }
  1729. });
  1730. translations = {
  1731. "Season:": "时间范围(年度)",
  1732. "Duration, hours:": "持续时间(小时):",
  1733. "Difficulty:": "难度:"
  1734. };
  1735. selectElement.each(function () {
  1736. var optionValue = $(this).text();
  1737. if (translations[optionValue]) {
  1738. $(this).text(translations[optionValue]);
  1739. }
  1740. });
  1741. })();
  1742. (function () {
  1743. var parentElement = $('.setting-value');
  1744. var selectElement = parentElement.find('select');
  1745. var translations = {
  1746. "Official ACM-ICPC Contest": "ICPC官方比赛",
  1747. "Official School Contest": "学校官方比赛",
  1748. "Opencup Contest": "Opencup比赛",
  1749. "School/University/City/Region Championship": "学校/大学/城市/地区锦标赛",
  1750. "Training Camp Contest": "训练营比赛",
  1751. "Official International Personal Contest": "官方国际个人赛",
  1752. "Training Contest": "训练比赛",
  1753. "ID_ASC": "创建时间(升序)",
  1754. "ID_DESC": "创建时间(降序)",
  1755. "RATING_ASC": "评分(升序)",
  1756. "RATING_DESC": "评分(降序)",
  1757. "DIFFICULTY_ASC": "难度(升序)",
  1758. "DIFFICULTY_DESC": "难度(降序)",
  1759. "START_TIME_ASC": "开始时间(升序)",
  1760. "START_TIME_DESC": "开始时间(降序)",
  1761. "DURATION_ASC": "持续时间(升序)",
  1762. "DURATION_DESC": "持续时间(降序)",
  1763. "POPULARITY_ASC": "热度(升序)",
  1764. "POPULARITY_DESC": "热度(降序)",
  1765. "UPDATE_TIME_ASC": "更新时间(升序)",
  1766. "UPDATE_TIME_DESC": "更新时间(降序)"
  1767. };
  1768. selectElement.find("option").each(function () {
  1769. var optionValue = $(this).val();
  1770. if (translations[optionValue]) {
  1771. $(this).text(translations[optionValue]);
  1772. }
  1773. });
  1774. parentElement = $('.setting-last-value');
  1775. selectElement = parentElement.find('select');
  1776. selectElement.find("option").each(function () {
  1777. var optionValue = $(this).val();
  1778. if (translations[optionValue]) {
  1779. $(this).text(translations[optionValue]);
  1780. }
  1781. });
  1782. })();
  1783. // 比赛过滤器选项汉化
  1784. (function () {
  1785. var parentElement = $('.options');
  1786. var selectElement = parentElement.find('li');
  1787. var translations = {
  1788. "Educational": "教育性",
  1789. "Global": "全球",
  1790. "VK Cup": "VK杯",
  1791. "Long Rounds": "长期回合",
  1792. "April Fools": "愚人节",
  1793. "Team Contests": "团队比赛",
  1794. "ICPC Scoring": "ICPC计分",
  1795. "Doesn't matter": "----",
  1796. "Any": "所有",
  1797. "Yes": "是",
  1798. "No": "否",
  1799. "No submission(s)": "无提交",
  1800. "Have submission(s)": "有提交",
  1801. "No solved problem(s)": "无解决问题",
  1802. "Have solved problem(s)": "有解决问题"
  1803. };
  1804. selectElement.find('label').each(function () {
  1805. var optionValue = $(this).text();
  1806. if (translations[optionValue]) {
  1807. $(this).text(translations[optionValue]);
  1808. }
  1809. });
  1810. $('.CaptionCont').find('span').each(function () {
  1811. var optionValue = $(this).text();
  1812. if (translations[optionValue]) {
  1813. $(this).text(translations[optionValue]);
  1814. }
  1815. });
  1816. })();
  1817. // 右侧sidebox通用汉化
  1818. (function () {
  1819. var parentElement = $('.sidebox');
  1820. var selectElement = parentElement.find('div');
  1821. var translations = {
  1822. "Show tags for unsolved problems": "显示未解决问题的标签",
  1823. "Hide solved problems": "隐藏已解决的问题",
  1824. };
  1825. selectElement.find("label").each(function () {
  1826. var optionValue = $(this).text();
  1827. if (translations[optionValue]) {
  1828. $(this).text(translations[optionValue]);
  1829. }
  1830. });
  1831. })();
  1832. // 表单字段名汉化
  1833. (function () {
  1834. var translations = {
  1835. "Problem:": "题目:",
  1836. "Language:": "语言:",
  1837. "Source code:": "源代码:",
  1838. "Or choose file:": "或者选择文件:",
  1839. "Choose file:": "选择文件:",
  1840. "Notice:": "注意:",
  1841. "virtual participation:": "虚拟参与:",
  1842. "Registration for the contest:": "比赛报名:",
  1843. "Take part:": "参与:",
  1844. "as individual participant:": "作为个人参与者:",
  1845. "as a team member:": "作为团队成员:",
  1846. "Virtual start time:": "虚拟开始时间:",
  1847. "Complete problemset:": "完整的问题集:",
  1848. "First name (English)": "名字(英文)",
  1849. "Last name (English)": "姓氏(英文)",
  1850. "First name (Native)": "名字(本地语言)",
  1851. "Last name (Native)": "姓氏(本地语言)",
  1852. "Birth date": "出生日期",
  1853. "Country": "国家",
  1854. "City": "城市",
  1855. "Organization": "组织",
  1856. "Handle/Email": "账号/邮箱",
  1857. "Password": "密码",
  1858. };
  1859. $(".field-name").each(function () {
  1860. var optionValue = $(this).text();
  1861. if (translations[optionValue]) {
  1862. $(this).text(translations[optionValue]);
  1863. }
  1864. });
  1865. })();
  1866. (function () {
  1867. var translations = {
  1868. "Terms of agreement:": "协议条款:",
  1869. "Choose team:": "选择团队:"
  1870. };
  1871. $(".field-name label").each(function () {
  1872. var optionValue = $(this).text();
  1873. if (translations[optionValue]) {
  1874. $(this).text(translations[optionValue]);
  1875. }
  1876. });
  1877. })();
  1878. (function () {
  1879. var translations = {
  1880. "Hide sidebar block \"Find user\"": "隐藏侧边栏块“查找用户”",
  1881. "Hide sidebar block \"Current user\"": "隐藏侧边栏块“当前用户”",
  1882. "Hide sidebar block \"Recent аctions\"": "隐藏侧边栏块“最新动态”",
  1883. "Hide sidebar block \"Favourite groups\"": "隐藏侧边栏块“收藏组”",
  1884. "Hide sidebar block \"Top contributors\"": "隐藏侧边栏块“贡献者排行”",
  1885. "Hide sidebar block \"Top rated\"": "隐藏侧边栏块“评级排行”",
  1886. "Hide sidebar block \"Streams\"": "隐藏侧边栏块“直播”",
  1887. "Old password": "旧密码",
  1888. "New password": "新密码",
  1889. "Confirm new password": "确认新密码",
  1890. "Contest email notification": "比赛邮件通知",
  1891. "Send email on new user talk": "在有新用户对话时发送电子邮件",
  1892. "Send email on new comment": "在有新评论时发送电子邮件",
  1893. "Hide contact information": "隐藏联系人信息",
  1894. "Remember me by Gmail, Facebook and etc": "通过 Gmail、Facebook 等记住我",
  1895. "Show tags for unsolved problems": "显示未解决问题的标签",
  1896. "Hide solved problems from problemset": "从问题集中隐藏已解决的问题",
  1897. "Hide low rated blogs": "隐藏评级较低的博客",
  1898. "Offer to publish great rating rises": "提供展示Rating显著提升的机会",
  1899. "Enforce https": "强制 HTTPS",
  1900. "Show private activity in the profile": "在个人资料中显示私人活动",
  1901. "Show diagnostics": "显示诊断信息"
  1902. };
  1903. $(".field-name").each(function () {
  1904. var tag = $(this).text();
  1905. for (var property in translations) {
  1906. property = property.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
  1907. if (tag.match(property)) {
  1908. $(this).text(translations[property]);
  1909. break;
  1910. }
  1911. }
  1912. });
  1913. })();
  1914. (function () {
  1915. var translations = {
  1916. "Postal/zip code": "邮政编码/邮编",
  1917. "Country (English)": "国家(英文)",
  1918. "State (English)": "州/省份(英文)",
  1919. "City (English)": "城市(英文)",
  1920. "Address (English)": "地址(英文)",
  1921. "Recipient (English)": "收件人姓名(英文)",
  1922. "Country (Native)": "国家(本地语言)",
  1923. "State (Native)": "州/省份(本地语言)",
  1924. "City (Native)": "城市(本地语言)",
  1925. "Address (Native)": "地址(本地语言)",
  1926. "Recipient (Native)": "收件人姓名(本地语言)",
  1927. "Phone": "电话",
  1928. "TON Wallet:": "TON 钱包:",
  1929. "Secret Code:": "验证码:"
  1930. };
  1931. $("td.field-name label").each(function () {
  1932. var optionValue = $(this).text();
  1933. if (translations[optionValue]) {
  1934. $(this).text(translations[optionValue]);
  1935. }
  1936. });
  1937. })();
  1938.  
  1939. // 按钮汉化input[type="submit"]
  1940. (function () {
  1941. var translations = {
  1942. "Register for virtual participation": "报名虚拟参赛",
  1943. "Register for practice": "登录以开始练习",
  1944. "Apply": "应用",
  1945. "Register": "报名",
  1946. "Login": "登录",
  1947. "Run": "运行",
  1948. "Start virtual contest": "开始虚拟参赛",
  1949. "Clone Contest": "克隆比赛",
  1950. "Submit": "提交",
  1951. "Save changes": "保存设置",
  1952. "Filter": "过滤",
  1953. "Find": "查找",
  1954. "Create Mashup Contest": "创建混搭比赛"
  1955. };
  1956. $('input[type="submit"]').each(function () {
  1957. var optionValue = $(this).val();
  1958. if (translations[optionValue]) {
  1959. $(this).val(translations[optionValue]);
  1960. }
  1961. });
  1962. })();
  1963. (function () {
  1964. var translations = {
  1965. "Reset": "重置",
  1966. };
  1967. $('input[type="button"]').each(function () {
  1968. var optionValue = $(this).val();
  1969. if (translations[optionValue]) {
  1970. $(this).val(translations[optionValue]);
  1971. }
  1972. });
  1973. })();
  1974.  
  1975. // 选项汉化input[type="radio"]
  1976. (function () {
  1977. var translations = {
  1978. "as individual participant": "个人",
  1979. "as a team member": "作为一个团队成员",
  1980. };
  1981. $('input[type="radio"]').each(function () {
  1982. var tag = $(this).parent().contents().filter(function () {
  1983. return this.nodeType === Node.TEXT_NODE;
  1984. });
  1985. for (var i = 0; i < tag.length; i++) {
  1986. var text = tag[i].textContent.trim();
  1987. if (translations.hasOwnProperty(text)) {
  1988. $(this).addClass(text);
  1989. tag[i].replaceWith(translations[text]);
  1990. break;
  1991. }
  1992. }
  1993. });
  1994. })();
  1995.  
  1996.  
  1997. // 杂项
  1998. (function () {
  1999. var translations = {
  2000. "(standard input\/output)": "标准输入/输出",
  2001. };
  2002. $("div.notice").each(function () {
  2003. var tag = $(this).children().eq(0).text();
  2004. for (var property in translations) {
  2005. if (tag.match(property)) {
  2006. $(this).children().eq(0).text(translations[property]);
  2007. break;
  2008. }
  2009. }
  2010. });
  2011. })();
  2012. (function () {
  2013. var translations = {
  2014. "Ask a question": "提一个问题",
  2015. };
  2016. $(".ask-question-link").each(function () {
  2017. var optionValue = $(this).text();
  2018. if (translations[optionValue]) {
  2019. $(this).text(translations[optionValue]);
  2020. }
  2021. });
  2022. })();
  2023.  
  2024. // 轻量站特殊
  2025. if (is_mSite) {
  2026. (function () {
  2027. var translations = {
  2028. "Announcements": "公告",
  2029. "Submissions": "提交记录",
  2030. "Contests": "比赛",
  2031. };
  2032. $(".caption").each(function () {
  2033. var optionValue = $(this).text();
  2034. if (translations[optionValue]) {
  2035. $(this).text(translations[optionValue]);
  2036. }
  2037. });
  2038. })();
  2039. }
  2040. };
  2041.  
  2042. // 配置管理函数
  2043. function setupConfigManagement(element, tempConfig, structure, configHTML, checkable) {
  2044. let counter = 0;
  2045. createControlBar();
  2046. createContextMenu();
  2047.  
  2048. // 键值对校验
  2049. function valiKeyValue(value) {
  2050. const keyValuePairs = value.split('\n');
  2051. const regex = /^[a-zA-Z0-9_-]+\s*:\s*[a-zA-Z0-9_-]+$/;
  2052. for (let i = 0; i < keyValuePairs.length; i++) {
  2053. if (!regex.test(keyValuePairs[i])) {
  2054. return false;
  2055. }
  2056. }
  2057. return true;
  2058. }
  2059.  
  2060. // 新增数据
  2061. function onAdd() {
  2062. const styleElement = createWindow();
  2063.  
  2064. const settingMenu = $("#config_edit_menu");
  2065. settingMenu.on("click", "#save", () => {
  2066. const config = {};
  2067. let allFieldsValid = true;
  2068. for (const key in structure) {
  2069. let value = $(key).val();
  2070. if (value || $(key).attr('require') === 'false') {
  2071. config[structure[key]] = $(key).val();
  2072. $(key).removeClass('is_null');
  2073. } else {
  2074. $(key).addClass('is_null');
  2075. allFieldsValid = false;
  2076. }
  2077. }
  2078.  
  2079. // 校验提示
  2080. for (let i = 0, len = checkable.length; i < len; i++) {
  2081. let value = $(checkable[i]).val();
  2082. if (value && !valiKeyValue(value)) {
  2083. if (!$(checkable[i]).prev('span.text-error').length) {
  2084. $(checkable[i]).before('<span class="text-error" style="color: red;">格式不符或存在非法字符</span>');
  2085. }
  2086. allFieldsValid = false;
  2087. } else {
  2088. $(checkable[i]).prev('span.text-error').remove();
  2089. }
  2090. }
  2091.  
  2092. if (!allFieldsValid) return;
  2093. tempConfig.configurations.push(config);
  2094.  
  2095. const list = $("#config_bar_ul");
  2096. createListItemElement(config[structure['#note']]).insertBefore($('#add_button'));
  2097.  
  2098. settingMenu.remove();
  2099. $(styleElement).remove();
  2100. });
  2101.  
  2102. settingMenu.on("click", ".btn-close", () => {
  2103. settingMenu.remove();
  2104. $(styleElement).remove();
  2105. });
  2106. }
  2107.  
  2108. // 编辑数据
  2109. function onEdit() {
  2110. const menu = $("#config_bar_menu");
  2111. menu.css({ display: "none" });
  2112.  
  2113. const list = $("#config_bar_ul");
  2114. const index = Array.from(list.children()).indexOf(this);
  2115.  
  2116. const styleElement = createWindow();
  2117.  
  2118. const settingMenu = $("#config_edit_menu");
  2119. const configAtIndex = tempConfig.configurations[index];
  2120.  
  2121. if (configAtIndex) {
  2122. for (const key in structure) {
  2123. $(key).val(configAtIndex[structure[key]]);
  2124. }
  2125. }
  2126.  
  2127. settingMenu.on("click", "#save", () => {
  2128. const config = {};
  2129. let allFieldsValid = true;
  2130. for (const key in structure) {
  2131. let value = $(key).val();
  2132. if (value || $(key).attr('require') === 'false') {
  2133. config[structure[key]] = $(key).val();
  2134. $(key).removeClass('is_null');
  2135. } else {
  2136. $(key).addClass('is_null');
  2137. allFieldsValid = false;
  2138. }
  2139. }
  2140.  
  2141. // 校验提示
  2142. for (let i = 0, len = checkable.length; i < len; i++) {
  2143. let value = $(checkable[i]).val();
  2144. if (value && !valiKeyValue(value)) {
  2145. if (!$(checkable[i]).prev('span.text-error').length) {
  2146. $(checkable[i]).before('<span class="text-error" style="color: red;">格式不符或存在非法字符</span>');
  2147. }
  2148. allFieldsValid = false;
  2149. } else {
  2150. $(checkable[i]).prev('span.text-error').remove();
  2151. }
  2152. }
  2153.  
  2154. if (!allFieldsValid) return;
  2155. tempConfig.configurations[index] = config;
  2156.  
  2157. settingMenu.remove();
  2158. $(styleElement).remove();
  2159. menu.css({ display: "none" });
  2160.  
  2161. list.children().eq(index).find("label").text(config.note);
  2162. });
  2163.  
  2164. // 关闭按钮
  2165. settingMenu.on("click", ".btn-close", () => {
  2166. settingMenu.remove();
  2167. $(styleElement).remove();
  2168. });
  2169. }
  2170.  
  2171. // 删除数据
  2172. function onDelete() {
  2173. const menu = $("#config_bar_menu");
  2174. menu.css({ display: "none" });
  2175.  
  2176. const list = $("#config_bar_ul");
  2177. const index = Array.from(list.children()).indexOf(this);
  2178.  
  2179. tempConfig.configurations.splice(index, 1);
  2180.  
  2181. list.children().eq(index).remove();
  2182. }
  2183.  
  2184. // 创建编辑窗口
  2185. function createWindow() {
  2186. const styleElement = GM_addStyle(darkenPageStyle2);
  2187. $("body").append(configHTML);
  2188. addDraggable($('#config_edit_menu'));
  2189. return styleElement;
  2190. }
  2191.  
  2192. // 创建控制面板
  2193. function createControlBar() {
  2194. $(element).append(`
  2195. <div id='configControlTip' style='color:red;'></div>
  2196. <div class='config_bar'>
  2197. <div class='config_bar_list' id='config_bar_list'>
  2198. <ul class='config_bar_ul' id='config_bar_ul'></ul>
  2199. </div>
  2200. </div>
  2201. `);
  2202. }
  2203.  
  2204. // 创建右键菜单
  2205. function createContextMenu() {
  2206. const menu = $("<div id='config_bar_menu' style='display: none;'></div>");
  2207. menu.html(`
  2208. <div class='config_bar_menu_item' id='config_bar_menu_edit'>修改</div>
  2209. <div class='config_bar_menu_item' id='config_bar_menu_delete'>删除</div>
  2210. `);
  2211. $("body").append(menu);
  2212. }
  2213.  
  2214. // 创建新的li元素
  2215. function createListItemElement(text) {
  2216. const li = $("<li></li>");
  2217. const radio = $("<input type='radio' name='config_item'></input>").appendTo(li);
  2218. radio.attr("value", counter).attr("id", counter++);
  2219. const label = $("<label class='config_bar_ul_li_text'></label>").text(text).attr("for", radio.attr("value")).appendTo(li);
  2220.  
  2221. // 添加右键菜单
  2222. li.on("contextmenu", function (event) {
  2223. event.preventDefault();
  2224. const menu = $("#config_bar_menu");
  2225. menu.css({ display: "block", left: event.pageX, top: event.pageY });
  2226.  
  2227. const deleteItem = $("#config_bar_menu_delete");
  2228. const editItem = $("#config_bar_menu_edit");
  2229.  
  2230. // 移除旧事件
  2231. deleteItem.off("click");
  2232. editItem.off("click");
  2233.  
  2234. deleteItem.on("click", onDelete.bind(this));
  2235. editItem.on("click", onEdit.bind(this));
  2236.  
  2237. $(document).one("click", (event) => {
  2238. if (!menu.get(0).contains(event.target)) {
  2239. menu.css({ display: "none" });
  2240. deleteItem.off("click", onDelete);
  2241. editItem.off("click", onEdit);
  2242. }
  2243. });
  2244. });
  2245.  
  2246.  
  2247. return li;
  2248. }
  2249.  
  2250. // 渲染列表
  2251. function renderList() {
  2252. const listContainer = $("#config_bar_list");
  2253. const list = $("#config_bar_ul");
  2254. list.empty();
  2255. tempConfig.configurations.forEach((item) => {
  2256. list.append(createListItemElement(item[structure['#note']]));
  2257. });
  2258.  
  2259. list.append(`
  2260. <li id='add_button'>
  2261. <span>+ 添加</span>
  2262. </li>
  2263. `);
  2264. const addItem = $('#add_button');
  2265. addItem.on("click", onAdd);
  2266. };
  2267.  
  2268. renderList();
  2269. return tempConfig;
  2270. }
  2271.  
  2272. const CFBetterSettingMenuHTML = `
  2273. <div class='CFBetter_setting_menu' id='CFBetter_setting_menu'>
  2274. <div class="tool-box">
  2275. <button class="btn-close">×</button>
  2276. </div>
  2277. <h3>基本设置</h3>
  2278. <hr>
  2279. <div class='CFBetter_setting_list' style="padding: 0px 10px;">
  2280. <span style="font-size: 16px;">黑暗模式</span>
  2281. <div class="dark-mode-selection">
  2282. <label>
  2283. <input class="radio-input" type="radio" name="darkMode" value="dark" />
  2284. <span class="CFBetter_setting_menu_label_text">黑暗</span>
  2285. <span class="radio-icon"> </span>
  2286. </label>
  2287. <label>
  2288. <input checked="" class="radio-input" type="radio" name="darkMode" value="light" />
  2289. <span class="CFBetter_setting_menu_label_text">白天</span>
  2290. <span class="radio-icon"> </span>
  2291. </label>
  2292. <label>
  2293. <input class="radio-input" type="radio" name="darkMode" value="follow" />
  2294. <span class="CFBetter_setting_menu_label_text">跟随系统</span>
  2295. <span class="radio-icon"> </span>
  2296. </label>
  2297. </div>
  2298. </div>
  2299. <div class='CFBetter_setting_list'>
  2300. <label for="bottomZh_CN">界面汉化</label>
  2301. <input type="checkbox" id="bottomZh_CN" name="bottomZh_CN">
  2302. </div>
  2303. <div class='CFBetter_setting_list'>
  2304. <label for="showLoading">显示加载提示信息</label>
  2305. <div class="help_tip">
  2306. `+ helpCircleHTML + `
  2307. <div class="tip_text">
  2308. <p>当你开启 显示加载信息 时,每次加载页面时会在上方显示加载信息提示:“Codeforces Better! —— xxx”</p>
  2309. <p>这用于了解脚本当前的工作情况,<strong>如果你不想看到,可以选择关闭</strong></p>
  2310. <p><u>需要说明的是,如果你需要反馈脚本的任何加载问题,请开启该选项后再截图,以便于分析问题</u></p>
  2311. </div>
  2312. </div>
  2313. <input type="checkbox" id="showLoading" name="showLoading">
  2314. </div>
  2315. <div class='CFBetter_setting_list'>
  2316. <label for="hoverTargetAreaDisplay">显示目标区域范围</label>
  2317. <div class="help_tip">
  2318. `+ helpCircleHTML + `
  2319. <div class="tip_text">
  2320. <p>开启后当鼠标悬浮在 MD视图/复制/翻译 按钮上时,会显示其目标区域的范围</p>
  2321. </div>
  2322. </div>
  2323. <input type="checkbox" id="hoverTargetAreaDisplay" name="hoverTargetAreaDisplay">
  2324. </div>
  2325. <div class='CFBetter_setting_list'>
  2326. <label for="expandFoldingblocks">自动展开折叠块</label>
  2327. <input type="checkbox" id="expandFoldingblocks" name="expandFoldingblocks">
  2328. </div>
  2329. <div class='CFBetter_setting_list'>
  2330. <label for="renderPerfOpt">折叠块渲染优化</label>
  2331. <div class="help_tip">
  2332. `+ helpCircleHTML + `
  2333. <div class="tip_text">
  2334. <p>为折叠块元素启用可见渲染(content-visibility: auto)</p>
  2335. <p>如果您的浏览器查看大量折叠块时比较卡顿,开启后会有一定程度的改善</p>
  2336. <p>注意:本特性有小概率可能导致页面在某些位置时上下快速跳动闪屏</p>
  2337. </div>
  2338. </div>
  2339. <input type="checkbox" id="renderPerfOpt" name="renderPerfOpt">
  2340. </div>
  2341. <div class='CFBetter_setting_list'>
  2342. <label for="commentPaging">评论区分页</label>
  2343. <div class="help_tip">
  2344. `+ helpCircleHTML + `
  2345. <div class="tip_text">
  2346. <p>对评论区分页显示,每页显示指定数量的<strong>主楼</strong></p>
  2347. </div>
  2348. </div>
  2349. <input type="checkbox" id="commentPaging" name="commentPaging">
  2350. </div>
  2351. <div class='CFBetter_setting_list'>
  2352. <label for="showJumpToLuogu">显示跳转到洛谷</label>
  2353. <div class="help_tip">
  2354. `+ helpCircleHTML + `
  2355. <div class="tip_text">
  2356. <p>洛谷OJ上收录了Codeforces的部分题目,一些题目有翻译和题解</p>
  2357. <p>开启显示后,如果当前题目被收录,则会在题目的右上角显示洛谷标志,</p>
  2358. <p>点击即可一键跳转到该题洛谷的对应页面。</strong></p>
  2359. </div>
  2360. </div>
  2361. <input type="checkbox" id="showJumpToLuogu" name="showJumpToLuogu">
  2362. </div>
  2363. <div class='CFBetter_setting_list'>
  2364. <label for="loaded"><span style="font-size: 14px;">兼容选项-不等待页面资源加载</span></label>
  2365. <div class="help_tip">
  2366. `+ helpCircleHTML + `
  2367. <div class="tip_text">
  2368. <p>为了防止在页面资源未加载完成前(主要是各种js)执行脚本产生意外的错误,脚本默认会等待 window.onload 事件</p>
  2369. <p>如果您的页面上方的加载信息始终停留在:“等待页面资源加载”,即使页面已经完成加载</p>
  2370. <p><u>您首先应该确认是否是网络问题,</u></p>
  2371. <p>如果不是,那这可能是由于 window.onload 事件在您的浏览器中触发过早(早于DOMContentLoaded),</p>
  2372. <p>您可以尝试开启该选项来不再等待 window.onload 事件</p>
  2373. <p><u>注意:如果没有上述问题,请不要开启该选项</u></p>
  2374. </div>
  2375. </div>
  2376. <input type="checkbox" id="loaded" name="loaded">
  2377. </div>
  2378. <h3>翻译设置</h3>
  2379. <hr>
  2380. <div class='CFBetter_setting_list'>
  2381. <label for="enableSegmentedTranslation">分段翻译</label>
  2382. <div class="help_tip">
  2383. `+ helpCircleHTML + `
  2384. <div class="tip_text">
  2385. <p>分段翻译会对区域内的每一个&#60;&#112;&#47;&#62;和&#60;&#105;&#47;&#62;标签依次进行翻译,</p>
  2386. <p>这通常在翻译<strong>长篇博客</strong>或者<strong>超长的题目</strong>时很有用。</p>
  2387. <p><u>注意:开启分段翻译会产生如下问题:</u></p>
  2388. <p>- 使得翻译接口无法知晓整个文本的上下文信息,会降低翻译质量。</p>
  2389. <p>- 会有<strong>部分内容不会被翻译</strong>,因为它们不是&#60;&#112;&#47;&#62;或&#60;&#105;&#47;&#62;元素</p>
  2390. </div>
  2391. </div>
  2392. <input type="checkbox" id="enableSegmentedTranslation" name="enableSegmentedTranslation">
  2393. </div>
  2394. <label>
  2395. <input type='radio' name='translation' value='deepl'>
  2396. <span class='CFBetter_setting_menu_label_text'>deepl翻译</span>
  2397. </label>
  2398. <label>
  2399. <input type='radio' name='translation' value='youdao'>
  2400. <span class='CFBetter_setting_menu_label_text'>有道翻译</span>
  2401. </label>
  2402. <label>
  2403. <input type='radio' name='translation' value='google'>
  2404. <span class='CFBetter_setting_menu_label_text'>Google翻译</span>
  2405. </label>
  2406. <label>
  2407. <input type='radio' name='translation' value='openai'>
  2408. <span class='CFBetter_setting_menu_label_text'>使用ChatGPT翻译(API)
  2409. <div class="help_tip">
  2410. `+ helpCircleHTML + `
  2411. <div class="tip_text">
  2412. <p><b>请在下方添加并选定你想使用的配置信息</b></p>
  2413. <p>具体请阅读脚本页的介绍</p>
  2414. </div>
  2415. </div>
  2416. </span>
  2417. </label>
  2418. <div class='CFBetter_setting_menu_input' id='openai' style='display: none;'>
  2419. <div id="chatgpt-config"></div>
  2420. </div>
  2421. <button id='save'>保存</button>
  2422. </div>
  2423. `;
  2424.  
  2425. const chatgptConfigEditHTML = `
  2426. <div class='CFBetter_setting_menu' id='config_edit_menu'>
  2427. <div class="tool-box">
  2428. <button class="btn-close">×</button>
  2429. </div>
  2430. <h4>配置</h4>
  2431. <h5>基本</h5>
  2432. <hr>
  2433. <label for='note'>
  2434. <span class="input_label">备注:</span>
  2435. </label>
  2436. <input type='text' id='note' class='no_default' placeholder='请为该配置取一个备注名' require = true>
  2437. <label for='openai_model'>
  2438. <div style="display: flex;align-items: center;">
  2439. <span class="input_label">模型:</span>
  2440. <div class="help_tip">
  2441. `+ helpCircleHTML + `
  2442. <div class="tip_text">
  2443. <p>留空则默认为:gpt-3.5-turbo</p>
  2444. <p>模型列表请查阅<a target="_blank" href="https://platform.openai.com/docs/models">OpenAI官方文档</a></p>
  2445. <p><strong>此外,如果您使用的是服务商提供的代理API,请确认服务商是否支持对应模型</strong></p>
  2446. </div>
  2447. </div>
  2448. </div>
  2449. </label>
  2450. <input type='text' id='openai_model' placeholder='gpt-3.5-turbo' require = false>
  2451. <label for='openai_key'>
  2452. <div style="display: flex;align-items: center;">
  2453. <span class="input_label">KEY:</span>
  2454. <div class="help_tip">
  2455. `+ helpCircleHTML + `
  2456. <div class="tip_text">
  2457. <p>您需要输入自己的OpenAI key,<a target="_blank" href="https://platform.openai.com/account/usage">官网</a></p>
  2458. <p><b>如果您使用的是服务商提供的代理API,则应该填写服务商提供的 Key</b></p>
  2459. </div>
  2460. </div>
  2461. </div>
  2462. </label>
  2463. <input type='text' id='openai_key' class='no_default' placeholder='请输入KEY' require = true>
  2464. <label for='openai_proxy'>
  2465. <div style="display: flex;align-items: center;">
  2466. <span class="input_label">Proxy API:</span>
  2467. <div class="help_tip">
  2468. `+ helpCircleHTML + `
  2469. <div class="tip_text">
  2470. <p>留空则默认为OpenAI官方API</p>
  2471. <p>您也可以填写指定的API来代理访问OpenAIAPI,</p>
  2472. <p>如果您使用的是服务商提供的代理APIKEY,则这里应该填写其提供的<strong>完整</strong>API地址,详请阅读脚本说明</p>
  2473. <p><strong>由于您指定了自定义的APITampermonkey会对您的跨域请求进行警告,您需要自行授权</strong></p>
  2474. </div>
  2475. </div>
  2476. </div>
  2477. </label>
  2478. <input type='text' id='openai_proxy' placeholder='https://api.openai.com/v1/chat/completions' require = false>
  2479. <h5>高级</h5>
  2480. <hr>
  2481. <label for='_header'>
  2482. <div style="display: flex;align-items: center;">
  2483. <span class="input_label">自定义header</span>
  2484. <div class="help_tip">
  2485. `+ helpCircleHTML + `
  2486. <div class="tip_text">
  2487. <p>格式样例:</p>
  2488. <div style="border: 1px solid #795548; padding: 10px;">
  2489. <p>name1 : 123<br>name2 : cccc</p>
  2490. </div>
  2491. </div>
  2492. </div>
  2493. </div>
  2494. </label>
  2495. <textarea id="_header" placeholder='(选填)您可以在这里填写向请求header中额外添加的键值对' require = false></textarea>
  2496. <label for='_data'>
  2497. <div style="display: flex;align-items: center;">
  2498. <span class="input_label">自定义data</span>
  2499. <div class="help_tip">
  2500. `+ helpCircleHTML + `
  2501. <div class="tip_text">
  2502. <p>格式样例:</p>
  2503. <div style="border: 1px solid #795548; padding: 10px;">
  2504. <p>name1 : 123<br>name2 : cccc</p>
  2505. </div>
  2506. </div>
  2507. </div>
  2508. </div>
  2509. </label>
  2510. <textarea id="_data" placeholder='(选填)您可以在这里填写向请求data中额外添加的键值对' require = false></textarea>
  2511. <button id='save'>保存</button>
  2512. </div>
  2513. `;
  2514.  
  2515. // 设置按钮面板
  2516. function settingPanel() {
  2517. $("div[class='lang-chooser']").each(function () {
  2518. $(this).before(
  2519. "<button class='html2mdButton CFBetter_setting'>CodeforcesBetter设置</button>"
  2520. );
  2521. });
  2522. $("div[class='enter-or-register-box']").each(function () {
  2523. $(this).after(
  2524. "<button class='html2mdButton CFBetter_setting'>CodeforcesBetter设置</button>"
  2525. );
  2526. });
  2527.  
  2528. const $settingBtns = $(".CFBetter_setting");
  2529. $settingBtns.click(() => {
  2530. const styleElement = GM_addStyle(darkenPageStyle);
  2531. $settingBtns.prop("disabled", true).addClass("open");
  2532. $("body").append(CFBetterSettingMenuHTML);
  2533.  
  2534. // 窗口初始化
  2535. addDraggable($('#CFBetter_setting_menu'));
  2536. const chatgptStructure = {
  2537. '#note': 'note',
  2538. '#openai_model': 'model',
  2539. '#openai_key': 'key',
  2540. '#openai_proxy': 'proxy',
  2541. '#_header': '_header',
  2542. '#_data': '_data',
  2543. }
  2544. const checkable = [
  2545. '#_header',
  2546. '#_data',
  2547. ]
  2548. let tempConfig = GM_getValue('chatgpt-config'); // 缓存配置信息
  2549. tempConfig = setupConfigManagement('#chatgpt-config', tempConfig, chatgptStructure, chatgptConfigEditHTML, checkable);
  2550.  
  2551. // 状态更新
  2552. $("#bottomZh_CN").prop("checked", GM_getValue("bottomZh_CN") === true);
  2553. $("input[name='darkMode'][value='" + darkMode + "']").prop("checked", true);
  2554. $("#showLoading").prop("checked", GM_getValue("showLoading") === true);
  2555. $("#expandFoldingblocks").prop("checked", GM_getValue("expandFoldingblocks") === true);
  2556. $("#enableSegmentedTranslation").prop("checked", GM_getValue("enableSegmentedTranslation") === true);
  2557. $("#renderPerfOpt").prop("checked", GM_getValue("renderPerfOpt") === true);
  2558. $("#commentPaging").prop("checked", GM_getValue("commentPaging") === true);
  2559. $("#showJumpToLuogu").prop("checked", GM_getValue("showJumpToLuogu") === true);
  2560. $("#loaded").prop("checked", GM_getValue("loaded") === true);
  2561. $("#hoverTargetAreaDisplay").prop("checked", GM_getValue("hoverTargetAreaDisplay") === true);
  2562. $("input[name='translation'][value='" + translation + "']").prop("checked", true);
  2563. $("input[name='translation']").css("color", "gray");
  2564. if (translation == "openai") {
  2565. $("#openai").show();
  2566. if (tempConfig) {
  2567. $("input[name='config_item'][value='" + tempConfig.choice + "']").prop("checked", true);
  2568. }
  2569. }
  2570.  
  2571. // 翻译选择情况监听
  2572. $("input[name='translation']").change(function () {
  2573. var selected = $(this).val(); // 获取当前选中的值
  2574. if (selected === "openai") {
  2575. $("#openai").show();
  2576. if (tempConfig) {
  2577. $("input[name='config_item'][value='" + tempConfig.choice + "']").prop("checked", true);
  2578. }
  2579. } else {
  2580. $("#openai").hide();
  2581. }
  2582. });
  2583.  
  2584. // 配置选择情况监听
  2585. $("input[name='config_item']").change(function () {
  2586. var selected = $(this).val(); // 获取当前选中的值
  2587. tempConfig.choice = selected;
  2588. });
  2589.  
  2590. const $settingMenu = $(".CFBetter_setting_menu");
  2591.  
  2592. $("#save").click(debounce(function () {
  2593. const settings = {
  2594. bottomZh_CN: $("#bottomZh_CN").prop("checked"),
  2595. darkMode: $("input[name='darkMode']:checked").val(),
  2596. showLoading: $("#showLoading").prop("checked"),
  2597. hoverTargetAreaDisplay: $("#hoverTargetAreaDisplay").prop("checked"),
  2598. expandFoldingblocks: $("#expandFoldingblocks").prop("checked"),
  2599. renderPerfOpt: $("#renderPerfOpt").prop("checked"),
  2600. commentPaging: $("#commentPaging").prop("checked"),
  2601. enableSegmentedTranslation: $("#enableSegmentedTranslation").prop("checked"),
  2602. showJumpToLuogu: $("#showJumpToLuogu").prop("checked"),
  2603. loaded: $("#loaded").prop("checked"),
  2604. translation: $("input[name='translation']:checked").val()
  2605. };
  2606. if (settings.translation === "openai") {
  2607. var selectedIndex = $('input[name="config_item"]:checked').closest('li').index();
  2608. if (selectedIndex === -1) {
  2609. $('#configControlTip').text('请选择一项配置!')
  2610. return;
  2611. }
  2612. }
  2613. GM_setValue('chatgpt-config', tempConfig);
  2614. let refreshPage = false; // 是否需要刷新页面
  2615. for (const [key, value] of Object.entries(settings)) {
  2616. if (!refreshPage && !(key == 'enableSegmentedTranslation' || key == 'translation' || key == 'darkMode')) {
  2617. if (GM_getValue(key) != value) refreshPage = true;
  2618. }
  2619. GM_setValue(key, value);
  2620. }
  2621.  
  2622. if (refreshPage) location.reload();
  2623. else {
  2624. // 切换黑暗模式
  2625. if (darkMode != settings.darkMode) {
  2626. darkMode = settings.darkMode;
  2627. // 移除旧的事件监听器
  2628. changeEventListeners.forEach(listener => {
  2629. mediaQueryList.removeEventListener('change', listener);
  2630. });
  2631.  
  2632. if (darkMode == "follow") {
  2633. changeEventListeners.push(handleColorSchemeChange);
  2634. mediaQueryList.addEventListener('change', handleColorSchemeChange);
  2635. $('html').removeAttr('data-theme');
  2636. } else if (darkMode == "dark") {
  2637. $('html').attr('data-theme', 'dark');
  2638. } else {
  2639. $('html').attr('data-theme', 'light');
  2640. // 移除旧的事件监听器
  2641. const mediaQueryList = window.matchMedia('(prefers-color-scheme: dark)');
  2642. window.matchMedia('(prefers-color-scheme: dark)');
  2643. }
  2644. }
  2645. // 更新配置信息
  2646. enableSegmentedTranslation = settings.enableSegmentedTranslation;
  2647. translation = settings.translation;
  2648. if (settings.translation === "openai") {
  2649. var selectedIndex = $('#config_bar_ul li input[type="radio"]:checked').closest('li').index();
  2650. if (selectedIndex !== opneaiConfig.choice) {
  2651. opneaiConfig = GM_getValue("chatgpt-config");
  2652. const configAtIndex = opneaiConfig.configurations[selectedIndex];
  2653. openai_model = configAtIndex.model;
  2654. openai_key = configAtIndex.key;
  2655. openai_proxy = configAtIndex.proxy;
  2656. openai_header = configAtIndex._header ?
  2657. configAtIndex._header.split("\n").map(header => {
  2658. const [key, value] = header.split(":");
  2659. return { [key.trim()]: value.trim() };
  2660. }) : [];
  2661. openai_data = configAtIndex._data ?
  2662. configAtIndex._data.split("\n").map(header => {
  2663. const [key, value] = header.split(":");
  2664. return { [key.trim()]: value.trim() };
  2665. }) : [];
  2666. }
  2667. }
  2668. }
  2669.  
  2670. $settingMenu.remove();
  2671. $settingBtns.prop("disabled", false).removeClass("open");
  2672. $(styleElement).remove();
  2673. }));
  2674.  
  2675. // 关闭
  2676. $settingMenu.on("click", ".btn-close", () => {
  2677. $settingMenu.remove();
  2678. $settingBtns.prop("disabled", false).removeClass("open");
  2679. $(styleElement).remove();
  2680. });
  2681. });
  2682. };
  2683.  
  2684. // html2md转换/处理规则
  2685. var turndownService = new TurndownService({ bulletListMarker: '-' });
  2686. var turndown = turndownService.turndown;
  2687.  
  2688. // 保留原始
  2689. turndownService.keep(['del']);
  2690.  
  2691. // 丢弃
  2692. turndownService.addRule('remove-by-class', {
  2693. filter: function (node) {
  2694. return node.classList.contains('sample-tests') ||
  2695. node.classList.contains('header') ||
  2696. node.classList.contains('overlay') ||
  2697. node.classList.contains('html2md-panel');
  2698. },
  2699. replacement: function (content, node) {
  2700. return "";
  2701. }
  2702. });
  2703. turndownService.addRule('remove-script', {
  2704. filter: function (node, options) {
  2705. return node.tagName.toLowerCase() == "script" && node.type.startsWith("math/tex");
  2706. },
  2707. replacement: function (content, node) {
  2708. return "";
  2709. }
  2710. });
  2711.  
  2712. // inline math
  2713. turndownService.addRule('inline-math', {
  2714. filter: function (node, options) {
  2715. return node.tagName.toLowerCase() == "span" && node.className == "MathJax";
  2716. },
  2717. replacement: function (content, node) {
  2718. var latex = $(node).next().text();
  2719. latex = latex.replace(/</g, "&lt;").replace(/>/g, "&gt;");
  2720. return "$" + latex + "$";
  2721. }
  2722. });
  2723.  
  2724. // block math
  2725. turndownService.addRule('block-math', {
  2726. filter: function (node, options) {
  2727. return node.tagName.toLowerCase() == "div" && node.className == "MathJax_Display";
  2728. },
  2729. replacement: function (content, node) {
  2730. var latex = $(node).next().text();
  2731. latex = latex.replace(/</g, "&lt;").replace(/>/g, "&gt;");
  2732. return "\n$$\n" + latex + "\n$$\n";
  2733. }
  2734. });
  2735.  
  2736. // texFontStyle
  2737. turndownService.addRule('texFontStyle', {
  2738. filter: function (node) {
  2739. return (
  2740. node.nodeName === 'SPAN' &&
  2741. node.classList.contains('tex-font-style-bf')
  2742. )
  2743. },
  2744. replacement: function (content) {
  2745. return '**' + content + '**'
  2746. }
  2747. })
  2748.  
  2749. // sectionTitle
  2750. turndownService.addRule('sectionTitle', {
  2751. filter: function (node) {
  2752. return (
  2753. node.nodeName === 'DIV' &&
  2754. node.classList.contains('section-title')
  2755. )
  2756. },
  2757. replacement: function (content) {
  2758. return '**' + content + '**'
  2759. }
  2760. })
  2761.  
  2762. // bordertable
  2763. turndownService.addRule('bordertable', {
  2764. filter: 'table',
  2765. replacement: function (content, node) {
  2766. if (node.classList.contains('bordertable')) {
  2767. var output = [],
  2768. thead = '',
  2769. trs = node.querySelectorAll('tr');
  2770. if (trs.length > 0) {
  2771. var ths = trs[0].querySelectorAll('td,th');
  2772. if (ths.length > 0) {
  2773. thead = '| ' + Array.from(ths).map(th => turndownService.turndown(th.innerHTML.trim())).join(' | ') + ' |\n'
  2774. + '| ' + Array.from(ths).map(() => ' --- ').join('|') + ' |\n';
  2775. }
  2776. }
  2777. var rows = node.querySelectorAll('tr');
  2778. Array.from(rows).forEach(function (row, i) {
  2779. if (i > 0) {
  2780. var cells = row.querySelectorAll('td,th');
  2781. var trow = '| ' + Array.from(cells).map(cell => turndownService.turndown(cell.innerHTML.trim())).join(' | ') + ' |';
  2782. output.push(trow);
  2783. }
  2784. });
  2785. return thead + output.join('\n');
  2786. } else {
  2787. return content;
  2788. }
  2789. }
  2790. });
  2791.  
  2792. // 随机数生成
  2793. function getRandomNumber(numDigits) {
  2794. let min = Math.pow(10, numDigits - 1);
  2795. let max = Math.pow(10, numDigits) - 1;
  2796. return Math.floor(Math.random() * (max - min + 1)) + min;
  2797. }
  2798.  
  2799. // 题目markdown转换/翻译面板
  2800. function addButtonPanel(parent, suffix, type, is_simple = false) {
  2801. let htmlString = `<div class='html2md-panel'>
  2802. <button class='html2mdButton html2md-view${suffix}'>MarkDown视图</button>
  2803. <button class='html2mdButton html2md-cb${suffix}'>Copy</button>
  2804. <button class='html2mdButton translateButton${suffix}'>翻译</button>
  2805. </div>`;
  2806. if (type === "this_level") {
  2807. $(parent).before(htmlString);
  2808. var block = $(".translateButton" + suffix).parent().next();
  2809. } else if (type === "child_level") {
  2810. $(parent).prepend(htmlString);
  2811. var block = $(".translateButton" + suffix).parent().parent();
  2812. }
  2813. if (is_simple) {
  2814. $('.html2md-panel').find('.html2mdButton.html2md-view' + suffix + ', .html2mdButton.html2md-cb' + suffix).remove();
  2815. }
  2816.  
  2817. if (block.css("display") === "none" || block.hasClass('ojbetter-alert')) $(".translateButton" + suffix).parent().remove();
  2818. }
  2819. function addButtonWithHTML2MD(parent, suffix, type) {
  2820. if (is_oldLatex) {
  2821. $(".html2md-view" + suffix).css({
  2822. "cursor": "not-allowed",
  2823. "background-color": "#ffffff",
  2824. "color": "#a8abb2",
  2825. "border": "1px solid #e4e7ed"
  2826. });
  2827. $(".html2md-view" + suffix).prop("disabled", true);
  2828. }
  2829. $(document).on("click", ".html2md-view" + suffix, debounce(function () {
  2830. var target, removedChildren = $();
  2831. if (type === "this_level") {
  2832. target = $(".html2md-view" + suffix).parent().next().get(0);
  2833. } else if (type === "child_level") {
  2834. target = $(".html2md-view" + suffix).parent().parent().get(0);
  2835. removedChildren = $(".html2md-view" + suffix).parent().parent().children(':first').detach();
  2836. }
  2837. if (target.viewmd) {
  2838. target.viewmd = false;
  2839. $(this).text("MarkDown视图");
  2840. $(this).removeClass("mdViewed");
  2841. $(target).html(target.original_html);
  2842. } else {
  2843. target.viewmd = true;
  2844. if (!target.original_html) {
  2845. target.original_html = $(target).html();
  2846. }
  2847. if (!target.markdown) {
  2848. target.markdown = turndownService.turndown($(target).html());
  2849. }
  2850. $(this).text("原始内容");
  2851. $(this).addClass("mdViewed");
  2852. $(target).html(`<span class="mdViewContent" oninput="$(this).parent().get(0).markdown=this.value;" style="width:auto; height:auto;">${target.markdown}</span>`);
  2853. }
  2854. // 恢复删除的元素
  2855. if (removedChildren) $(target).prepend(removedChildren);
  2856. }));
  2857.  
  2858. if (hoverTargetAreaDisplay && !is_oldLatex) {
  2859. var previousCSS;
  2860. $(document).on("mouseover", ".html2md-view" + suffix, function () {
  2861. var target;
  2862.  
  2863. if (type === "this_level") {
  2864. target = $(".html2md-view" + suffix).parent().next().get(0);
  2865. } else if (type === "child_level") {
  2866. target = $(".html2md-view" + suffix).parent().parent().get(0);
  2867. }
  2868.  
  2869. $(target).append('<div class="overlay">目标转换区域</div>');
  2870.  
  2871. previousCSS = {
  2872. "position": $(target).css("position"),
  2873. "display": $(target).css("display")
  2874. };
  2875. $(target).css({
  2876. "position": "relative",
  2877. "display": "block"
  2878. });
  2879.  
  2880. $(".html2md-view" + suffix).parent().css({
  2881. "position": "relative",
  2882. "z-index": "99999"
  2883. });
  2884. });
  2885.  
  2886. $(document).on("mouseout", ".html2md-view" + suffix, function () {
  2887. var target;
  2888.  
  2889. if (type === "this_level") {
  2890. target = $(".html2md-view" + suffix).parent().next().get(0);
  2891. } else if (type === "child_level") {
  2892. target = $(".html2md-view" + suffix).parent().parent().get(0);
  2893. }
  2894.  
  2895. $(target).find('.overlay').remove();
  2896. if (previousCSS) {
  2897. $(target).css(previousCSS);
  2898. }
  2899. $(".html2md-view" + suffix).parent().css({
  2900. "position": "static"
  2901. });
  2902. });
  2903. }
  2904. }
  2905.  
  2906. function addButtonWithCopy(parent, suffix, type) {
  2907. if (is_oldLatex) {
  2908. $(".html2md-cb" + suffix).css({
  2909. "cursor": "not-allowed",
  2910. "background-color": "#ffffff",
  2911. "color": "#a8abb2",
  2912. "border": "1px solid #e4e7ed"
  2913. });
  2914. $(".html2md-cb" + suffix).prop("disabled", true);
  2915. }
  2916. $(document).on("click", ".html2md-cb" + suffix, debounce(function () {
  2917. var target, removedChildren;
  2918. if (type === "this_level") {
  2919. target = $(".translateButton" + suffix).parent().next().eq(0).clone();
  2920. } else if (type === "child_level") {
  2921. target = $(".translateButton" + suffix).parent().parent().eq(0).clone();
  2922. $(target).children(':first').remove();
  2923. }
  2924. if ($(target).find('.mdViewContent').length <= 0) {
  2925. text = turndownService.turndown($(target).html());
  2926. } else {
  2927. text = $(target).find('.mdViewContent').text();
  2928. }
  2929. GM_setClipboard(text);
  2930. $(this).addClass("copied");
  2931. $(this).text("Copied");
  2932. // 更新复制按钮文本
  2933. setTimeout(() => {
  2934. $(this).removeClass("copied");
  2935. $(this).text("Copy");
  2936. }, 2000);
  2937. $(target).remove();
  2938. }));
  2939.  
  2940. if (hoverTargetAreaDisplay && !is_oldLatex) {
  2941. var previousCSS;
  2942. $(document).on("mouseover", ".html2md-cb" + suffix, function () {
  2943. var target;
  2944.  
  2945. if (type === "this_level") {
  2946. target = $(".html2md-cb" + suffix).parent().next().get(0);
  2947. } else if (type === "child_level") {
  2948. target = $(".html2md-cb" + suffix).parent().parent().get(0);
  2949. }
  2950.  
  2951. $(target).append('<div class="overlay">目标复制区域</div>');
  2952. previousCSS = {
  2953. "position": $(target).css("position"),
  2954. "display": $(target).css("display")
  2955. };
  2956. $(target).css({
  2957. "position": "relative",
  2958. "display": "block"
  2959. });
  2960. $(".html2md-cb" + suffix).parent().css({
  2961. "position": "relative",
  2962. "z-index": "99999"
  2963. })
  2964. });
  2965.  
  2966. $(document).on("mouseout", ".html2md-cb" + suffix, function () {
  2967. var target;
  2968.  
  2969. if (type === "this_level") {
  2970. target = $(".html2md-cb" + suffix).parent().next().get(0);
  2971. } else if (type === "child_level") {
  2972. target = $(".html2md-cb" + suffix).parent().parent().get(0);
  2973. }
  2974.  
  2975. $(target).find('.overlay').remove();
  2976. if (previousCSS) {
  2977. $(target).css(previousCSS);
  2978. }
  2979. $(".html2md-cb" + suffix).parent().css({
  2980. "position": "static"
  2981. })
  2982. });
  2983. }
  2984. }
  2985.  
  2986. async function addButtonWithTranslation(parent, suffix, type) {
  2987. var result;
  2988. $(document).on('click', '.translateButton' + suffix, debounce(async function () {
  2989. $(this).trigger('mouseout');
  2990. $(this).removeClass("translated");
  2991. $(this).text("翻译中");
  2992. $(this).css("cursor", "not-allowed");
  2993. $(this).prop("disabled", true);
  2994. var target, element_node, block, errerNum = 0;
  2995. if (type === "this_level") block = $(".translateButton" + suffix).parent().next();
  2996. else if (type === "child_level") block = $(".translateButton" + suffix).parent().parent();
  2997.  
  2998. // 重新翻译
  2999. if (result) {
  3000. if (result.translateDiv) {
  3001. $(result.translateDiv).remove();
  3002. }
  3003. if (!is_oldLatex) {
  3004. if (result.copyDiv) {
  3005. $(result.copyDiv).remove();
  3006. }
  3007. if (result.copyButton) {
  3008. $(result.copyButton).remove();
  3009. }
  3010. }
  3011. // 移除旧的事件
  3012. $(document).off("mouseover", ".translateButton" + suffix);
  3013. $(document).off("mouseout", ".translateButton" + suffix);
  3014. // 重新绑定悬停事件
  3015. if (hoverTargetAreaDisplay) bindHoverEvents(suffix, type);
  3016. }
  3017.  
  3018. // 分段翻译
  3019. if (enableSegmentedTranslation) {
  3020. var pElements = block.find("p, li");
  3021. for (let i = 0; i < pElements.length; i++) {
  3022. target = $(pElements[i]).eq(0).clone();
  3023. if (type === "child_level") $(target).children(':first').remove();
  3024. element_node = pElements[i];
  3025. if (type === "child_level") {
  3026. $(pElements[i]).append("<div></div>");
  3027. element_node = $(pElements[i]).find("div:last-child").get(0);
  3028. }
  3029. result = await blockProcessing(target, element_node, $(".translateButton" + suffix));
  3030. if (result.status) errerNum += 1;
  3031. $(target).remove();
  3032. if (translation == "deepl") await new Promise(resolve => setTimeout(resolve, 2000));
  3033. }
  3034. } else {
  3035. target = block.eq(0).clone();
  3036. if (type === "child_level") $(target).children(':first').remove();
  3037. element_node = $(block).get(0);
  3038. if (type === "child_level") {
  3039. $(parent).append("<div></div>");
  3040. element_node = $(parent).find("div:last-child").get(0);
  3041. }
  3042. //是否跳过折叠块
  3043. if ($(target).find('.spoiler').length > 0) {
  3044. const shouldSkip = await skiFoldingBlocks();
  3045. if (shouldSkip) {
  3046. $(target).find('.spoiler').remove();
  3047. } else {
  3048. $(target).find('.html2md-panel').remove();
  3049. }
  3050. }
  3051. result = await blockProcessing(target, element_node, $(".translateButton" + suffix));
  3052. if (result.status) errerNum += 1;
  3053. $(target).remove();
  3054. }
  3055.  
  3056. if (!errerNum) {
  3057. $(this).addClass("translated")
  3058. .text("已翻译")
  3059. .css("cursor", "pointer")
  3060. .removeClass("error")
  3061. .prop("disabled", false);
  3062. } else {
  3063. $(this).prop("disabled", false);
  3064. }
  3065.  
  3066. // 重新翻译
  3067. let currentText, is_error;
  3068. $(document).on("mouseover", ".translateButton" + suffix, function () {
  3069. currentText = $(this).text();
  3070. $(this).text("重新翻译");
  3071. if ($(this).hasClass("error")) {
  3072. is_error = true;
  3073. $(this).removeClass("error");
  3074. }
  3075. });
  3076.  
  3077. $(document).on("mouseout", ".translateButton" + suffix, function () {
  3078. $(this).text(currentText);
  3079. if (is_error) $(this).addClass("error");
  3080. });
  3081. }));
  3082.  
  3083. // 目标区域指示
  3084. function bindHoverEvents(suffix, type) {
  3085. var previousCSS;
  3086.  
  3087. $(document).on("mouseover", ".translateButton" + suffix, function () {
  3088. var target;
  3089.  
  3090. if (type === "this_level") {
  3091. target = $(".translateButton" + suffix).parent().next().get(0);
  3092. } else if (type === "child_level") {
  3093. target = $(".translateButton" + suffix).parent().parent().get(0);
  3094. }
  3095.  
  3096. $(target).append('<div class="overlay">目标翻译区域</div>');
  3097.  
  3098. previousCSS = {
  3099. "position": $(target).css("position"),
  3100. "display": $(target).css("display")
  3101. };
  3102. $(target).css({
  3103. "position": "relative",
  3104. "display": ($(target).hasClass('question-response')) ? "block" : $(target).css("display")
  3105. });
  3106.  
  3107. $(".translateButton" + suffix).parent().css({
  3108. "position": "relative",
  3109. "z-index": "99999"
  3110. });
  3111. });
  3112.  
  3113. $(document).on("mouseout", ".translateButton" + suffix, function () {
  3114. var target;
  3115.  
  3116. if (type === "this_level") {
  3117. target = $(".translateButton" + suffix).parent().next().get(0);
  3118. } else if (type === "child_level") {
  3119. target = $(".translateButton" + suffix).parent().parent().get(0);
  3120. }
  3121.  
  3122. $(target).find('.overlay').remove();
  3123.  
  3124. if (previousCSS) {
  3125. $(target).css(previousCSS);
  3126. }
  3127.  
  3128. $(".translateButton" + suffix).parent().css({
  3129. "position": "static"
  3130. });
  3131. });
  3132. }
  3133.  
  3134. if (hoverTargetAreaDisplay) bindHoverEvents(suffix, type);
  3135. }
  3136.  
  3137. // 块处理
  3138. async function blockProcessing(target, element_node, button) {
  3139. if (is_oldLatex) {
  3140. $(target).find('.overlay').remove();
  3141. target.markdown = $(target).html();
  3142. } else if (!target.markdown) {
  3143. target.markdown = turndownService.turndown($(target).html());
  3144. }
  3145. const textarea = document.createElement('textarea');
  3146. textarea.value = target.markdown;
  3147. var result = await translateProblemStatement(textarea.value, element_node, $(button));
  3148. //
  3149. if (result.status == 1) {
  3150. $(button).addClass("error")
  3151. .text("翻译中止")
  3152. .css("cursor", "pointer")
  3153. .prop("disabled", false);
  3154. $(result.translateDiv).remove();
  3155. $(target).remove();
  3156. } else if (result.status == 2) {
  3157. result.translateDiv.classList.add("error_translate");
  3158. $(button).addClass("error")
  3159. .text("翻译出错")
  3160. .css("cursor", "pointer")
  3161. .prop("disabled", false);
  3162. $(target).remove();
  3163. }
  3164. return result;
  3165. }
  3166.  
  3167. function addConversionButton() {
  3168. // 题目页添加按钮
  3169. if (window.location.href.includes("problem")) {
  3170. var exContentsPageClasses = ["sample-tests",];
  3171. $('.problem-statement').children('div').each(function () {
  3172. var className = $(this).attr('class');
  3173. if (!exContentsPageClasses.includes(className)) {
  3174. var id = "_" + getRandomNumber(8);
  3175. addButtonPanel(this, id, "this_level");
  3176. addButtonWithHTML2MD(this, id, "this_level");
  3177. addButtonWithCopy(this, id, "this_level");
  3178. addButtonWithTranslation(this, id, "this_level");
  3179. }
  3180. });
  3181. }
  3182. // 添加按钮到ttypography部分
  3183. $(".ttypography").each(function () {
  3184. // 题目页特判
  3185. if (!$(this).parent().hasClass('problemindexholder')) {
  3186. let id = "_comment_" + getRandomNumber(8);
  3187. addButtonPanel(this, id, "this_level");
  3188. addButtonWithHTML2MD(this, id, "this_level");
  3189. addButtonWithCopy(this, id, "this_level");
  3190. addButtonWithTranslation(this, id, "this_level");
  3191. }
  3192. });
  3193.  
  3194. // 添加按钮到spoiler部分
  3195. $('.spoiler-content').each(function () {
  3196. if ($(this).find('.html2md-panel').length === 0) {
  3197. let id = "_spoiler_" + getRandomNumber(8);
  3198. addButtonPanel(this, id, "child_level");
  3199. addButtonWithHTML2MD(this, id, "child_level");
  3200. addButtonWithCopy(this, id, "child_level");
  3201. addButtonWithTranslation(this, id, "child_level");
  3202. }
  3203. });
  3204.  
  3205. // 添加按钮到titled部分
  3206. (function () {
  3207. var elements = [".Virtual.participation", ".Attention", ".Practice"];//只为部分titled添加
  3208. $.each(elements, function (index, value) {
  3209. $(value).each(function () {
  3210. let id = "_titled_" + getRandomNumber(8);
  3211. var $nextDiv = $(this).next().children().get(0);
  3212. addButtonPanel($nextDiv, id, "child_level", true);
  3213. addButtonWithTranslation($nextDiv, id, "child_level");
  3214. });
  3215. });
  3216. })();
  3217. if (is_mSite) {
  3218. $("div[class='_IndexPage_notice']").each(function () {
  3219. let id = "_titled_" + getRandomNumber(8);
  3220. addButtonPanel(this, id, "this_level", true);
  3221. addButtonWithTranslation(this, id, "this_level");
  3222. });
  3223. }
  3224.  
  3225. // 添加按钮到比赛QA部分
  3226. $(".question-response").each(function () {
  3227. let id = "_question_" + getRandomNumber(8);
  3228. addButtonPanel(this, id, "this_level", true);
  3229. addButtonWithTranslation(this, id, "this_level");
  3230. });
  3231. if (is_mSite) {
  3232. $("div._ProblemsPage_announcements table tbody tr:gt(0)").each(function () {
  3233. var $nextDiv = $(this).find("td:first");
  3234. let id = "_question_" + getRandomNumber(8);
  3235. addButtonPanel($nextDiv, id, "this_level", true);
  3236. addButtonWithTranslation($nextDiv, id, "this_level");
  3237. });
  3238. }
  3239.  
  3240. // 添加按钮到弹窗confirm-proto部分
  3241. $(".confirm-proto").each(function () {
  3242. let id = "_titled_" + getRandomNumber(8);
  3243. var $nextDiv = $(this).children().get(0);
  3244. addButtonPanel($nextDiv, id, "this_level", true);
  3245. addButtonWithTranslation($nextDiv, id, "this_level");
  3246. });
  3247.  
  3248. // 添加按钮到_CatalogHistorySidebarFrame_item部分
  3249. $("._CatalogHistorySidebarFrame_item").each(function () {
  3250. let id = "_history_sidebar_" + getRandomNumber(8);
  3251. addButtonPanel(this, id, "this_level", true);
  3252. addButtonWithTranslation(this, id, "this_level");
  3253. });
  3254.  
  3255. $(".problem-lock-link").on("click", function () {
  3256. $(".popup .content div").each(function () {
  3257. let id = "_popup_" + getRandomNumber(8);
  3258. addButtonPanel(this, id, "this_level", true);
  3259. addButtonWithTranslation(this, id, "this_level");
  3260. });
  3261. });
  3262.  
  3263. // 添加按钮到弹窗alert部分
  3264. $(".alert:not(.CFBetter_alert)").each(function () {
  3265. let id = "_alert_" + getRandomNumber(8);
  3266. addButtonPanel(this, id, "this_level", true);
  3267. addButtonWithTranslation(this, id, "this_level");
  3268. });
  3269.  
  3270. // 添加按钮到talk-text部分
  3271. $(".talk-text").each(function () {
  3272. let id = "_talk-text_" + getRandomNumber(8);
  3273. addButtonPanel(this, id, "child_level", true);
  3274. addButtonWithTranslation(this, id, "child_level");
  3275. });
  3276. };
  3277.  
  3278. //弹窗翻译
  3279. function alertZh() {
  3280. var _alert = window.alert;
  3281. window.alert = async function (msg) {
  3282. _alert(msg + "\n=========翻译=========\n" + await translate_deepl(msg));
  3283. return true;
  3284. }
  3285. };
  3286.  
  3287. // 折叠块
  3288. function ExpandFoldingblocks() {
  3289. $('.spoiler').addClass('spoiler-open');
  3290. $('.spoiler-content').attr('style', '');
  3291. };
  3292.  
  3293. // 折叠块渲染优化
  3294. function RenderPerfOpt() {
  3295. return new Promise(function (resolve) {
  3296. var currentIndex = 0;
  3297. var delay = 50;
  3298. var maxDelay = 1000;
  3299.  
  3300. var elements = $('.spoiler-content');
  3301. var batchSize = 10;
  3302. var initialDelay = 50;
  3303.  
  3304. function processBatch(callback) {
  3305. var endIndex = currentIndex + batchSize;
  3306. for (var i = currentIndex; i < endIndex; i++) {
  3307. if (i >= elements.length) {
  3308. callback();
  3309. resolve();
  3310. return;
  3311. }
  3312. var element = elements.eq(i);
  3313. var height = element.outerHeight();
  3314. element.css('contain-intrinsic-size', height + 'px');
  3315. }
  3316.  
  3317. currentIndex += batchSize;
  3318.  
  3319. // 延时
  3320. delay *= 2;
  3321. if (delay >= maxDelay) delay = initialDelay;
  3322.  
  3323. setTimeout(function () {
  3324. processBatch(callback); // 递归
  3325. }, delay);
  3326. }
  3327.  
  3328. processBatch(function () {
  3329. GM_addStyle(`
  3330. .spoiler-content {
  3331. content-visibility: auto;
  3332. }
  3333. `);
  3334. });
  3335. });
  3336. }
  3337.  
  3338. // 分页
  3339. function CommentPagination() {
  3340. GM_addStyle(`
  3341. .comments > .comment {
  3342. display: none;
  3343. }
  3344. #next-page-btn, #prev-page-btn {
  3345. display: none;
  3346. }
  3347. #jump-input, #items-per-page{
  3348. height: 22px;
  3349. border: 1px solid #dcdfe6;
  3350. border-radius: 0.3rem;
  3351. }
  3352. #jump-input:focus-visible{
  3353. border-style: solid;
  3354. border-color: #3f51b5;
  3355. outline: none;
  3356. }
  3357. `);
  3358. $('.comments').after(`
  3359. <div id="pagBar" style="display: flex; align-items: center; justify-content: center; color: #606266;">
  3360. <label for="items-per-page">每页展示主楼数:</label>
  3361. <select id="items-per-page" style="margin-right: 15px;">
  3362. <option value="5">5</option>
  3363. <option value="10">10</option>
  3364. <option value="20">20</option>
  3365. </select>
  3366. <div class="paging" style="margin-right: 15px;">
  3367. <span id="current-page">1</span> / <span id="total-pages"></span>
  3368. </div>
  3369. <input type="text" id="jump-input" placeholder="跳转到页码">
  3370. <button type="button" id="jump-btn" class="html2mdButton">跳转</button>
  3371. <button id="prev-page-btn" class="html2mdButton">上一页</button>
  3372. <button id="next-page-btn" class="html2mdButton">下一页</button>
  3373. </div>
  3374. `);
  3375.  
  3376. let batchSize = 5;
  3377. let elements = $(".comments > .comment").slice(0, -1);
  3378. let start = 0;
  3379. let end = batchSize;
  3380. let currentPage = 1;
  3381. let displayedIndexes = []; // 存储已显示元素的索引
  3382.  
  3383. function showBatch(start, end) {
  3384. // 隐藏上一页
  3385. for (var i = 0; i < displayedIndexes.length; i++) {
  3386. elements.eq(displayedIndexes[i]).hide();
  3387. }
  3388.  
  3389. displayedIndexes = [];
  3390.  
  3391. // 显示当前页
  3392. elements.slice(start, end).each(function (index) {
  3393. $(this).show();
  3394. displayedIndexes.push(start + index);
  3395. });
  3396.  
  3397. // 更新页码和翻页按钮
  3398. $("#current-page").text(currentPage);
  3399. $("#total-pages").text(Math.ceil(elements.length / batchSize));
  3400.  
  3401. if (currentPage === 1) $("#prev-page-btn").hide();
  3402. else $("#prev-page-btn").show();
  3403.  
  3404. if (end >= elements.length) $("#next-page-btn").hide();
  3405. else $("#next-page-btn").show();
  3406. }
  3407.  
  3408. // 初始化
  3409. var commentID = null;
  3410. var pageURL = window.location.href;
  3411. if (pageURL.includes("#comment-")) {
  3412. // 带评论区锚点的链接
  3413. var startIndex = pageURL.lastIndexOf("#comment-") + 9;
  3414. commentID = pageURL.substring(startIndex);
  3415. var indexInComments = null;
  3416. $(".comments > .comment").each(function (index) {
  3417. $(this).find(".comment-table").each(function () {
  3418. var tableCommentID = $(this).attr("commentid");
  3419. if (tableCommentID === commentID) {
  3420. indexInComments = index;
  3421. return false;
  3422. }
  3423. });
  3424. });
  3425. let page = Math.ceil((indexInComments + 1) / batchSize);
  3426. currentPage = !page ? 1 : page;
  3427. showBatch((currentPage - 1) * batchSize, currentPage * batchSize);
  3428. setTimeout(function () {
  3429. window.location.href = pageURL;
  3430. }, 1000);
  3431. } else {
  3432. showBatch(0, batchSize);
  3433. }
  3434.  
  3435. $("#prev-page-btn").on("click", function () {
  3436. var itemsPerPage = parseInt($("#items-per-page").val());
  3437. start = (currentPage - 2) * itemsPerPage;
  3438. end = (currentPage - 1) * itemsPerPage;
  3439. currentPage--;
  3440. showBatch(start, end);
  3441. });
  3442.  
  3443. $("#next-page-btn").on("click", function () {
  3444. var itemsPerPage = parseInt($("#items-per-page").val());
  3445. start = currentPage * itemsPerPage;
  3446. end = (currentPage + 1) * itemsPerPage;
  3447. currentPage++;
  3448. showBatch(start, end);
  3449. });
  3450.  
  3451. $("#jump-btn").on("click", function () {
  3452. var inputPage = parseInt($("#jump-input").val());
  3453.  
  3454. if (inputPage >= 1 && inputPage <= Math.ceil(elements.length / parseInt($("#items-per-page").val()))) {
  3455. var itemsPerPage = parseInt($("#items-per-page").val());
  3456. start = (inputPage - 1) * itemsPerPage;
  3457. end = inputPage * itemsPerPage;
  3458. currentPage = inputPage; // 更新当前页码
  3459. showBatch(start, end);
  3460. }
  3461. });
  3462.  
  3463. $("#items-per-page").on("change", function () {
  3464. batchSize = parseInt($(this).val());
  3465. let page = Math.ceil(end / batchSize);
  3466. currentPage = !page ? 1 : page;
  3467. let maxPage = Math.ceil(elements.length / batchSize);
  3468. if (currentPage > maxPage) currentPage = maxPage;
  3469. showBatch((currentPage - 1) * batchSize, currentPage * batchSize);
  3470. });
  3471. }
  3472.  
  3473. // 跳转洛谷
  3474. async function CF2luogu() {
  3475. const getProblemId = () => {
  3476. const url = window.location.href;
  3477. const regex = url.includes('/contest/')
  3478. ? /\/contest\/(\d+)\/problem\/([A-Za-z\d]+)/
  3479. : /\/problemset\/problem\/(\d+)\/([A-Za-z\d]+)/;
  3480. const matchResult = url.match(regex);
  3481. return matchResult && matchResult.length >= 3
  3482. ? `${matchResult[1]}${matchResult[2]}`
  3483. : '';
  3484. };
  3485.  
  3486. const checkLinkExistence = (url) => {
  3487. return new Promise((resolve, reject) => {
  3488. GM.xmlHttpRequest({
  3489. method: "GET",
  3490. url,
  3491. headers: { "Range": "bytes=0-9999" }, // 获取前10KB数据
  3492. onload(response) {
  3493. if (response.responseText.match(/题目未找到/g)) {
  3494. resolve(false);
  3495. } else {
  3496. resolve(true);
  3497. }
  3498. },
  3499. onerror(error) {
  3500. reject(error);
  3501. }
  3502. });
  3503. });
  3504. };
  3505. const panelElement = $("<div>")
  3506. .addClass("html2md-panel")
  3507. .attr("id", "CF2luoguPanel")
  3508. .insertBefore('.problemindexholder');
  3509.  
  3510. const url = `https://www.luogu.com.cn/problem/CF${getProblemId()}`;
  3511. const result = await checkLinkExistence(url);
  3512. if (getProblemId() && result) {
  3513. const problemLink = $("<a>")
  3514. .attr("id", "problemLink")
  3515. .attr("href", url)
  3516. .attr("target", "_blank")
  3517. .html(`<button style="height: 25px;" class="html2mdButton"><img style="width:45px; margin-right:2px;" src="https://cdn.luogu.com.cn/fe/logo.png"></button>`);
  3518. panelElement.append(problemLink);
  3519. }
  3520. }
  3521.  
  3522. // 等待Latex渲染队列全部完成
  3523. function waitUntilIdleThenDo(callback) {
  3524. var intervalId = setInterval(function () {
  3525. var queue = MathJax.Hub.queue;
  3526. if (queue.pending === 0 && queue.running === 0) {
  3527. clearInterval(intervalId);
  3528. callback();
  3529. }
  3530. }, 100);
  3531. }
  3532.  
  3533. // 字数超限确认
  3534. function showWordsExceededDialog(button) {
  3535. return new Promise(resolve => {
  3536. const styleElement = GM_addStyle(darkenPageStyle);
  3537. $(button).removeClass("translated");
  3538. $(button).text("字数超限");
  3539. $(button).css("cursor", "not-allowed");
  3540. $(button).prop("disabled", true);
  3541. let htmlString = `
  3542. <div class="wordsExceeded">
  3543. <h2>字数超限!</h2>
  3544. <p>注意,即将翻译的内容字数超过了4950个字符,您可能选择了错误的翻译按钮</p>
  3545. <div style="display:flex; padding:5px 0px; align-items: center;">
  3546. `+ helpCircleHTML + `
  3547. <p>
  3548. 由于实现方式,区域中会出现多个翻译按钮,请点击更小的子区域中的翻译按钮,
  3549. <br>或者在设置面板中开启 分段翻译 后重试。
  3550. </p>
  3551. </div>
  3552. <p>对于免费的接口,大量请求可能导致你的IP被暂时禁止访问,对于GPT,会消耗大量的token</p>
  3553. <p>您确定要继续翻译吗?</p>
  3554. <div style="display:flex; padding-top:10px">
  3555. <button id="continueButton">继续</button><button id="cancelButton">取消</button>
  3556. </div>
  3557. </div>
  3558. `;
  3559. $('body').before(htmlString);
  3560. $("#continueButton").click(function () {
  3561. $(styleElement).remove();
  3562. $('.wordsExceeded').remove();
  3563. resolve(true);
  3564. });
  3565. $("#cancelButton").click(function () {
  3566. $(styleElement).remove();
  3567. $('.wordsExceeded').remove();
  3568. resolve(false);
  3569. });
  3570. });
  3571. }
  3572.  
  3573. //跳过折叠块确认
  3574. function skiFoldingBlocks() {
  3575. return new Promise(resolve => {
  3576. const styleElement = GM_addStyle(darkenPageStyle);
  3577. let htmlString = `
  3578. <div class="wordsExceeded">
  3579. <h2>是否跳过折叠块?</h2>
  3580. <p></p>
  3581. <div style="display:grid; padding:5px 0px; align-items: center;">
  3582. <p>
  3583. 即将翻译的区域中包含折叠块,折叠块可能是代码,通常不需要翻译,现在您需要选择是否跳过这些折叠块,
  3584. </p>
  3585. <p>
  3586. 如果其中有您需要翻译的折叠块,可以稍后再单独点击这些折叠块内的翻译按钮进行翻译
  3587. </p>
  3588. </div>
  3589. <p>要跳过折叠块吗?(建议选择跳过)</p>
  3590. <div style="display:flex; padding-top:10px">
  3591. <button id="cancelButton">否</button><button id="skipButton">跳过</button>
  3592. </div>
  3593. </div>
  3594. `;
  3595. $('body').before(htmlString);
  3596. $("#skipButton").click(function () {
  3597. $(styleElement).remove();
  3598. $('.wordsExceeded').remove();
  3599. resolve(true);
  3600. });
  3601. $("#cancelButton").click(function () {
  3602. $(styleElement).remove();
  3603. $('.wordsExceeded').remove();
  3604. resolve(false);
  3605. });
  3606. });
  3607. }
  3608.  
  3609. // 翻译框/翻译处理器
  3610. var translatedText = "";
  3611. async function translateProblemStatement(text, element_node, button) {
  3612. let status = 0;
  3613. let id = getRandomNumber(8);
  3614. let matches = [];
  3615. let replacements = {};
  3616. // 创建元素并放在element_node的后面
  3617. const translateDiv = document.createElement('div');
  3618. translateDiv.setAttribute('id', id);
  3619. translateDiv.classList.add('translate-problem-statement');
  3620. const spanElement = document.createElement('span');
  3621. translateDiv.appendChild(spanElement);
  3622. element_node.insertAdjacentElement('afterend', translateDiv);
  3623. // 替换latex公式
  3624. if (is_oldLatex) {
  3625. //去除开头结尾的<p>标签
  3626. text = text.replace(/^<p>/i, "");
  3627. text = text.replace(/<\/p>$/i, "");
  3628. //
  3629. let i = 0;
  3630. let regex = /<span\s+class="tex-span">.*?<\/span>/gi;
  3631. matches = text.match(regex);
  3632. try {
  3633. for (i; i < matches.length; i++) {
  3634. let match = matches[i];
  3635. text = text.replace(match, `【${i + 1}】`);
  3636. replacements[`【${i + 1}】`] = match;
  3637. }
  3638. } catch (e) { }
  3639. } else if (translation != "openai") {
  3640. // 使用GPT翻译时不必替换latex公式
  3641. let i = 0;
  3642. // 块公式
  3643. matches = matches.concat(text.match(/\$\$([\s\S]*?)\$\$/g));
  3644. try {
  3645. for (i; i < matches.length; i++) {
  3646. let match = matches[i];
  3647. text = text.replace(match, `【${i + 1}】`);
  3648. replacements[`【${i + 1}】`] = match;
  3649. }
  3650. } catch (e) { }
  3651. // 行内公式
  3652. matches = matches.concat(text.match(/\$(.*?)\$/g));
  3653. try {
  3654. for (i; i < matches.length; i++) {
  3655. let match = matches[i];
  3656. text = text.replace(match, `【${i + 1}】`);
  3657. replacements[`【${i + 1}】`] = match;
  3658. }
  3659. } catch (e) { }
  3660. }
  3661.  
  3662. if (text.length > 4950) {
  3663. const shouldContinue = await showWordsExceededDialog(button);
  3664. if (!shouldContinue) {
  3665. status = 1;
  3666. return {
  3667. translateDiv: translateDiv,
  3668. status: status
  3669. };
  3670. }
  3671. }
  3672. // 翻译
  3673. if (translation == "deepl") {
  3674. translateDiv.innerHTML = "正在使用 deepl 翻译中……请稍等";
  3675. translatedText = await translate_deepl(text);
  3676. } else if (translation == "youdao") {
  3677. translateDiv.innerHTML = "正在使用 有道 翻译中……请稍等";
  3678. translatedText = await translate_youdao_mobile(text);
  3679. } else if (translation == "google") {
  3680. translateDiv.innerHTML = "正在使用 google 翻译中……请稍等";
  3681. translatedText = await translate_gg(text);
  3682. } else if (translation == "openai") {
  3683. try {
  3684. translateDiv.innerHTML = "正在使用 ChatGPT 翻译中……" +
  3685. "<br><br>应用的配置:" + opneaiConfig.configurations[opneaiConfig.choice].note +
  3686. "<br><br>使用 ChatGPT 翻译需要很长的时间,请耐心等待";
  3687. translatedText = await translate_openai(text);
  3688. } catch (error) {
  3689. status = 2;
  3690. translatedText = error;
  3691. }
  3692. }
  3693. if (/^翻译出错/.test(translatedText)) status = 2;
  3694. // 还原latex公式
  3695. translatedText = translatedText.replace(/】【/g, '】 【');
  3696. if (is_oldLatex) {
  3697. translatedText = "<p>" + translatedText;
  3698. translatedText += "</p>";
  3699. try {
  3700. for (let i = 0; i < matches.length; i++) {
  3701. let match = matches[i];
  3702. let replacement = replacements[`【${i + 1}】`];
  3703. let regex;
  3704. regex = new RegExp(`【\\s*${i + 1}\\s*】`, 'g');
  3705. translatedText = translatedText.replace(regex, replacement);
  3706. regex = new RegExp(`\\[\\s*${i + 1}\\s*\\]`, 'g');
  3707. translatedText = translatedText.replace(regex, replacement);
  3708. regex = new RegExp(`【\\s*${i + 1}(?![】\\d])`, 'g');
  3709. translatedText = translatedText.replace(regex, replacement);
  3710. regex = new RegExp(`(?<![【\\d])${i + 1}\\s*】`, 'g');
  3711. translatedText = translatedText.replace(regex, " " + replacement);
  3712. }
  3713. } catch (e) { }
  3714. }
  3715. else if (translation != "openai") {
  3716. try {
  3717. for (let i = 0; i < matches.length; i++) {
  3718. let match = matches[i];
  3719. let replacement = replacements[`【${i + 1}】`];
  3720. let regex;
  3721. regex = new RegExp(`【\\s*${i + 1}\\s*】`, 'g');
  3722. translatedText = translatedText.replace(regex, replacement);
  3723. regex = new RegExp(`\\[\\s*${i + 1}\\s*\\]`, 'g');
  3724. translatedText = translatedText.replace(regex, replacement);
  3725. regex = new RegExp(`【\\s*${i + 1}(?![】\\d])`, 'g');
  3726. translatedText = translatedText.replace(regex, replacement);
  3727. regex = new RegExp(`(?<![【\\d])${i + 1}\\s*】`, 'g');
  3728. translatedText = translatedText.replace(regex, " " + replacement);
  3729. }
  3730. } catch (e) { }
  3731. }
  3732.  
  3733. // 结果复制按钮
  3734. if (!is_oldLatex) {
  3735. // 创建一个隐藏的元素来保存 translatedText 的值
  3736. var textElement = document.createElement("div");
  3737. textElement.style.display = "none";
  3738. textElement.textContent = translatedText;
  3739. translateDiv.parentNode.insertBefore(textElement, translateDiv);
  3740.  
  3741. // 按钮
  3742. var copyButton = document.createElement("button");
  3743. copyButton.textContent = "Copy";
  3744. var wrapperDiv = document.createElement("div");
  3745. $(wrapperDiv).css({
  3746. display: "flex",
  3747. justifyContent: "flex-end"
  3748. });
  3749. $(wrapperDiv).append(copyButton);
  3750. $(copyButton).addClass("html2mdButton html2md-cb");
  3751.  
  3752. copyButton.addEventListener("click", function () {
  3753. var translatedText = textElement.textContent;
  3754. GM_setClipboard(translatedText);
  3755. $(this).addClass("copied").text("Copied");
  3756. // 更新复制按钮文本
  3757. setTimeout(() => {
  3758. $(this).removeClass("copied");
  3759. $(this).text("Copy");
  3760. }, 2000);
  3761. });
  3762. translateDiv.parentNode.insertBefore(wrapperDiv, translateDiv);
  3763. }
  3764.  
  3765. // 转义LaTex中的特殊符号
  3766. if (!is_oldLatex) {
  3767. const escapeRules = [
  3768. { pattern: /(?<!\\)>(?!\s)/g, replacement: " &gt; " }, // >符号
  3769. { pattern: /(?<!\\)</g, replacement: " &lt; " }, // <符号
  3770. { pattern: /(?<!\\)\*/g, replacement: " &#42; " }, // *符号
  3771. { pattern: /(?<!\\)&(?=\s)/g, replacement: "\\&" }, // &符号
  3772. { pattern: /(?<!\\)\\(?![\\a-zA-Z0-9])/g, replacement: "\\\\" }, // \符号
  3773. { pattern: /(?<!\\)\\\\(?=\s)/g, replacement: "\\\\\\\\" }, // \\符号
  3774. ];
  3775.  
  3776. let latexMatches = [...translatedText.matchAll(/\$\$([\s\S]*?)\$\$|\$(.*?)\$|\$([\s\S]*?)\$/g)];
  3777.  
  3778. for (const match of latexMatches) {
  3779. const matchedText = match[0];
  3780. var escapedText = matchedText;
  3781. for (const rule of escapeRules) {
  3782. escapedText = escapedText.replaceAll(rule.pattern, rule.replacement);
  3783. }
  3784. translatedText = translatedText.replace(matchedText, escapedText);
  3785. }
  3786. }
  3787.  
  3788. // 使符合mathjx的转换语法
  3789. const ruleMap = [
  3790. { pattern: /(\s_[\u4e00-\u9fa5]+_)([\u4e00-\u9fa5]+)/g, replacement: "$1 $2" }, // 斜体
  3791. { pattern: /(_[\u4e00-\u9fa5]+_\s)([\u4e00-\u9fa5]+)/g, replacement: " $1$2" },
  3792. { pattern: /(_[\u4e00-\u9fa5]+_)([\u4e00-\u9fa5]+)/g, replacement: " $1 $2" },
  3793. { pattern: /(\$\$[\r\n])/g, replacement: "$$$$$$$$$$$$" }, // $$ 行间
  3794. { pattern: /(?<!\$)\$(?!\$)/g, replacement: "$$$$$" }, // $ 内联
  3795. ];
  3796. ruleMap.forEach(({ pattern, replacement }) => {
  3797. translatedText = translatedText.replace(pattern, replacement);
  3798. });
  3799.  
  3800. // 更新
  3801. if (is_oldLatex) {
  3802. // oldlatex
  3803. translatedText = $.parseHTML(translatedText);
  3804. $(translateDiv).empty().append($(translatedText));
  3805. return {
  3806. translateDiv: translateDiv,
  3807. status: status
  3808. };
  3809. } else {
  3810. // 渲染MarkDown
  3811. var md = window.markdownit();
  3812. var html = md.render(translatedText);
  3813. translateDiv.innerHTML = html;
  3814. // 渲染Latex
  3815. MathJax.Hub.Queue(["Typeset", MathJax.Hub, translateDiv]);
  3816.  
  3817. return {
  3818. translateDiv: translateDiv,
  3819. status: status,
  3820. copyDiv: textElement,
  3821. copyButton: copyButton
  3822. };
  3823. }
  3824.  
  3825. }
  3826.  
  3827. // ChatGPT
  3828. async function translate_openai(raw) {
  3829. var openai_retext = "";
  3830. var data;
  3831. if (is_oldLatex) {
  3832. data = {
  3833. model: (openai_model !== null && openai_model !== "") ? openai_model : 'gpt-3.5-turbo',
  3834. messages: [{
  3835. role: "user",
  3836. content: "请将下面的文本翻译为中文,这是一道编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的【】、HTML标签本身以及其中的内容不翻译不变动,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw
  3837. }],
  3838. temperature: 0.7,
  3839. ...Object.assign({}, ...openai_data)
  3840. };
  3841. } else {
  3842. data = {
  3843. model: (openai_model !== null && openai_model !== "") ? openai_model : 'gpt-3.5-turbo',
  3844. messages: [{
  3845. role: "user",
  3846. content: "请将下面的文本翻译为中文,这是一道编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw
  3847. }],
  3848. temperature: 0.7
  3849. };
  3850. };
  3851. return new Promise(function (resolve, reject) {
  3852. GM_xmlhttpRequest({
  3853. method: 'POST',
  3854. url: (openai_proxy !== null && openai_proxy !== "") ? openai_proxy : 'https://api.openai.com/v1/chat/completions',
  3855.  
  3856. data: JSON.stringify(data),
  3857. headers: {
  3858. 'Content-Type': 'application/json',
  3859. 'Authorization': 'Bearer ' + openai_key,
  3860. ...Object.assign({}, ...openai_header)
  3861. },
  3862. responseType: 'json',
  3863. onload: function (response) {
  3864. if (!response.response) {
  3865. reject("发生了未知的错误,如果你启用了代理API,请确认是否填写正确,并确保代理能够正常工作。\n\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈 请注意打码响应报文的敏感部分\n\n响应报文:" + JSON.stringify(response));
  3866. }
  3867. else if (!response.response.choices || response.response.choices.length < 1 || !response.response.choices[0].message) {
  3868. resolve("翻译出错,请重试\n\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈 \n\n报错信息:" + JSON.stringify(response.response, null, '\n'));
  3869. } else {
  3870. openai_retext = response.response.choices[0].message.content;
  3871. resolve(openai_retext);
  3872. }
  3873. },
  3874. onerror: function (response) {
  3875. reject("发生了未知的错误,请确认你是否能正常访问OpenAi的接口,如果使用代理API,请检查是否正常工作\n\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈 请注意打码响应报文的敏感部分\n\n响应报文:" + JSON.stringify(response));
  3876. },
  3877. });
  3878. });
  3879. }
  3880.  
  3881. //--谷歌翻译--start
  3882. async function translate_gg(raw) {
  3883. return new Promise((resolve, reject) => {
  3884. const url = 'https://translate.google.com/m';
  3885. const params = `tl=zh-CN&q=${encodeURIComponent(raw)}`;
  3886.  
  3887. GM_xmlhttpRequest({
  3888. method: 'GET',
  3889. url: `${url}?${params}`,
  3890. onload: function (response) {
  3891. const html = response.responseText;
  3892. const translatedText = $(html).find('.result-container').text();
  3893. resolve(translatedText);
  3894. },
  3895. onerror: function (error) {
  3896. console.error('Error:', error);
  3897. reject(error);
  3898. }
  3899. });
  3900. });
  3901. }
  3902. //--谷歌翻译--end
  3903.  
  3904. //--有道翻译m--start
  3905. async function translate_youdao_mobile(raw) {
  3906. const options = {
  3907. method: "POST",
  3908. url: 'http://m.youdao.com/translate',
  3909. data: "inputtext=" + encodeURIComponent(raw) + "&type=AUTO",
  3910. anonymous: true,
  3911. headers: {
  3912. "Content-Type": "application/x-www-form-urlencoded",
  3913. 'Host': 'm.youdao.com',
  3914. 'Origin': 'http://m.youdao.com',
  3915. 'Referer': 'http://m.youdao.com/translate',
  3916. }
  3917. }
  3918. return await BaseTranslate('有道翻译mobile', raw, options, res => /id="translateResult">\s*?<li>([\s\S]*?)<\/li>\s*?<\/ul/.exec(res)[1])
  3919. }
  3920. //--有道翻译m--end
  3921.  
  3922. //--Deepl翻译--start
  3923. function getTimeStamp(iCount) {
  3924. const ts = Date.now();
  3925. if (iCount !== 0) {
  3926. iCount = iCount + 1;
  3927. return ts - (ts % iCount) + iCount;
  3928. } else {
  3929. return ts;
  3930. }
  3931. }
  3932.  
  3933. async function translate_deepl(raw) {
  3934. const id = (Math.floor(Math.random() * 99999) + 100000) * 1000;
  3935. const data = {
  3936. jsonrpc: '2.0',
  3937. method: 'LMT_handle_texts',
  3938. id,
  3939. params: {
  3940. splitting: 'newlines',
  3941. lang: {
  3942. source_lang_user_selected: 'auto',
  3943. target_lang: 'ZH',
  3944. },
  3945. texts: [{
  3946. text: raw,
  3947. requestAlternatives: 3
  3948. }],
  3949. timestamp: getTimeStamp(raw.split('i').length - 1)
  3950. }
  3951. }
  3952. let postData = JSON.stringify(data);
  3953. if ((id + 5) % 29 === 0 || (id + 3) % 13 === 0) {
  3954. postData = postData.replace('"method":"', '"method" : "');
  3955. } else {
  3956. postData = postData.replace('"method":"', '"method": "');
  3957. }
  3958. const options = {
  3959. method: 'POST',
  3960. url: 'https://www2.deepl.com/jsonrpc',
  3961. data: postData,
  3962. headers: {
  3963. 'Content-Type': 'application/json',
  3964. 'Host': 'www2.deepl.com',
  3965. 'Origin': 'https://www.deepl.com',
  3966. 'Referer': 'https://www.deepl.com/',
  3967. },
  3968. anonymous: true,
  3969. nocache: true,
  3970. }
  3971. return await BaseTranslate('Deepl翻译', raw, options, res => JSON.parse(res).result.texts[0].text)
  3972. }
  3973.  
  3974. //--Deepl翻译--end
  3975.  
  3976. //--异步请求包装工具--start
  3977. async function PromiseRetryWrap(task, options, ...values) {
  3978. const { RetryTimes, ErrProcesser } = options || {};
  3979. let retryTimes = RetryTimes || 5;
  3980. const usedErrProcesser = ErrProcesser || (err => { throw err });
  3981. if (!task) return;
  3982. while (true) {
  3983. try {
  3984. return await task(...values);
  3985. } catch (err) {
  3986. if (!--retryTimes) {
  3987. console.log(err);
  3988. return usedErrProcesser(err);
  3989. }
  3990. }
  3991. }
  3992. }
  3993.  
  3994. async function BaseTranslate(name, raw, options, processer) {
  3995. let errtext;
  3996. const toDo = async () => {
  3997. var tmp;
  3998. try {
  3999. const data = await Request(options);
  4000. tmp = data.responseText;
  4001. const result = await processer(tmp);
  4002. if (result) sessionStorage.setItem(name + '-' + raw, result);
  4003. return result
  4004. } catch (err) {
  4005. errtext = tmp;
  4006. throw {
  4007. responseText: tmp,
  4008. err: err
  4009. }
  4010. }
  4011. }
  4012. return await PromiseRetryWrap(toDo, { RetryTimes: 3, ErrProcesser: () => "翻译出错,请重试或更换翻译接口\n\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈 请注意打码报错信息的敏感部分\n\n报错信息:" + errtext })
  4013. }
  4014.  
  4015. function Request(options) {
  4016. return new Promise((reslove, reject) => GM_xmlhttpRequest({ ...options, onload: reslove, onerror: reject }))
  4017. }
  4018.  
  4019. //--异步请求包装工具--end
  4020.  
  4021. // 开始
  4022. document.addEventListener("DOMContentLoaded", function () {
  4023. function checkJQuery(retryDelay) {
  4024. if (typeof jQuery === 'undefined') {
  4025. console.warn("JQuery未加载," + retryDelay + "毫秒后重试");
  4026. setTimeout(function () {
  4027. var newRetryDelay = Math.min(retryDelay * 2, 2000);
  4028. checkJQuery(newRetryDelay);
  4029. }, retryDelay);
  4030. } else {
  4031. init();
  4032. settingPanel();
  4033. checkScriptVersion();
  4034. toZH_CN();
  4035. var newElement = $("<div></div>").addClass("alert alert-info CFBetter_alert")
  4036. .html(`Codeforces Better! —— 正在等待页面资源加载……`)
  4037. .css({
  4038. "margin": "1em",
  4039. "text-align": "center",
  4040. "font-weight": "600",
  4041. "position": "relative"
  4042. });
  4043. var tip_SegmentedTranslation = $("<div></div>").addClass("alert alert-error CFBetter_alert")
  4044. .html(`Codeforces Better! —— 注意!分段翻译已开启,这会造成负面效果,
  4045. <p>除非你现在需要翻译超长篇的博客或者题目,否则请前往设置关闭分段翻译</p>`)
  4046. .css({
  4047. "margin": "1em",
  4048. "text-align": "center",
  4049. "font-weight": "600",
  4050. "position": "relative"
  4051. });
  4052.  
  4053. async function processPage() {
  4054. if (showLoading) newElement.html('Codeforces Better! —— 正在等待Latex渲染队列全部完成……');
  4055. await waitUntilIdleThenDo(async function () {
  4056. if (enableSegmentedTranslation) $(".menu-box:first").next().after(tip_SegmentedTranslation); //显示分段翻译警告
  4057. if (showJumpToLuogu) CF2luogu();
  4058. Promise.resolve()
  4059. .then(() => {
  4060. if (showLoading && expandFoldingblocks) newElement.html('Codeforces Better! —— 正在展开折叠块……');
  4061. return delay(100).then(() => { if (expandFoldingblocks) ExpandFoldingblocks() });
  4062. })
  4063. .then(() => {
  4064. if (showLoading && commentPaging) newElement.html('Codeforces Better! —— 正在对评论区分页……');
  4065. return delay(100).then(() => { if (commentPaging) CommentPagination() });
  4066. })
  4067. .then(() => {
  4068. if (showLoading) newElement.html('Codeforces Better! —— 正在加载按钮……');
  4069. return delay(100).then(() => addConversionButton());
  4070. })
  4071. .then(async () => {
  4072. if (showLoading && renderPerfOpt) newElement.html('Codeforces Better! —— 正在优化折叠块渲染……');
  4073. await delay(100);
  4074. if (renderPerfOpt) await RenderPerfOpt();
  4075. })
  4076. .then(() => {
  4077. alertZh();
  4078. if (showLoading) {
  4079. newElement.html('Codeforces Better! —— 加载已完成');
  4080. newElement.removeClass('alert-info').addClass('alert-success');
  4081. setTimeout(function () {
  4082. newElement.remove();
  4083. }, 3000);
  4084. }
  4085. })
  4086. .catch((error) => {
  4087. console.log(error);
  4088. });
  4089. });
  4090. }
  4091.  
  4092. function delay(ms) {
  4093. return new Promise((resolve) => setTimeout(resolve, ms));
  4094. }
  4095.  
  4096. if (showLoading) {
  4097. if (is_mSite) $("header").after(newElement);
  4098. else $(".menu-box:first").next().after(newElement);
  4099. }
  4100.  
  4101. if (loaded) {
  4102. processPage();
  4103. } else {
  4104. // 页面完全加载完成后执行
  4105. window.onload = function () {
  4106. processPage();
  4107. };
  4108. }
  4109. }
  4110. }
  4111. checkJQuery(50);
  4112. });
  4113.  
  4114. // 配置自动迁移代码(将在10个小版本后移除-1.66)
  4115. if (GM_getValue("openai_key") || GM_getValue("api2d_key")) {
  4116. const newConfig = { "choice": -1, "configurations": [] };
  4117. if (GM_getValue("openai_key")) {
  4118. let config1 = {
  4119. "note": "我的配置1",
  4120. "model": GM_getValue("openai_model") || "",
  4121. "key": GM_getValue("openai_key"),
  4122. "proxy": GM_getValue("openai_proxy") || "",
  4123. "_header": "",
  4124. "_data": ""
  4125. }
  4126. if (GM_getValue("translation") === "openai") newConfig.choice = 0;
  4127. newConfig.configurations.push(config1);
  4128. }
  4129. if (GM_getValue("api2d_key")) {
  4130. let config2 = {
  4131. "note": "api2d",
  4132. "model": GM_getValue("api2d_model"),
  4133. "key": GM_getValue("api2d_key"),
  4134. "proxy": GM_getValue("api2d_request_entry") + '/v1/chat/completions',
  4135. "_header": GM_getValue("x_api2d_no_cache") ? "" : " x-api2d-no-cache : 1",
  4136. "_data": ""
  4137. }
  4138. if (GM_getValue("translation") === "api2d") {
  4139. if (GM_getValue("openai_key")) newConfig.choice = 1;
  4140. else newConfig.choice = 0;
  4141. }
  4142. newConfig.configurations.push(config2);
  4143. }
  4144. GM_setValue("chatgpt-config", newConfig);
  4145. const keysToDelete = ["openai_key", "openai_model", "openai_proxy", "api2d_key", "api2d_model", "api2d_request_entry", "x_api2d_no_cache", "showOpneAiAdvanced"];
  4146. keysToDelete.forEach(key => {
  4147. if (GM_getValue(key) != undefined) GM_deleteValue(key);
  4148. });
  4149. if (GM_getValue("translation") === "api2d") GM_setValue("translation", "openai");
  4150. location.reload();
  4151. }
  4152. // 配置自动迁移代码(将在10个小版本后移除-1.71)
  4153. if (GM_getValue("darkMode") === true || GM_getValue("darkMode") === false) {
  4154. GM_setValue("darkMode", "follow");
  4155. location.reload();
  4156. }
  4157.