Codeforces Better!

Codeforces界面汉化、黑暗模式支持、题目翻译、markdown视图、一键复制题目、跳转到洛谷、评论区分页、ClistRating分显示、榜单重新着色

当前为 2023-10-01 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Codeforces Better!
  3. // @namespace https://greasyfork.org/users/747162
  4. // @version 1.66
  5. // @description Codeforces界面汉化、黑暗模式支持、题目翻译、markdown视图、一键复制题目、跳转到洛谷、评论区分页、ClistRating分显示、榜单重新着色
  6. // @author 北极小狐
  7. // @match *://*.codeforces.com/*
  8. // @run-at document-start
  9. // @connect www2.deepl.com
  10. // @connect www.iflyrec.com
  11. // @connect m.youdao.com
  12. // @connect api.interpreter.caiyunai.com
  13. // @connect translate.google.com
  14. // @connect openai.api2d.net
  15. // @connect api.openai.com
  16. // @connect www.luogu.com.cn
  17. // @connect clist.by
  18. // @connect greasyfork.org
  19. // @connect *
  20. // @grant GM_xmlhttpRequest
  21. // @grant GM_info
  22. // @grant GM_setValue
  23. // @grant GM_getValue
  24. // @grant GM_deleteValue
  25. // @grant GM_addStyle
  26. // @grant GM_setClipboard
  27. // @icon https://aowuucdn.oss-cn-beijing.aliyuncs.com/codeforces.png
  28. // @require https://cdn.staticfile.org/turndown/7.1.2/turndown.min.js
  29. // @require https://cdn.staticfile.org/markdown-it/13.0.1/markdown-it.min.js
  30. // @require https://cdn.bootcdn.net/ajax/libs/crypto-js/4.1.1/crypto-js.min.js
  31. // @require https://cdn.staticfile.org/chroma-js/2.4.2/chroma.min.js
  32. // @license MIT
  33. // @compatible Chrome
  34. // @compatible Firefox
  35. // @compatible Edge
  36. // ==/UserScript==
  37.  
  38. // 状态与初始化
  39. const getGMValue = (key, defaultValue) => {
  40. const value = GM_getValue(key);
  41. if (value === undefined || value === "") {
  42. GM_setValue(key, defaultValue);
  43. return defaultValue;
  44. }
  45. return value;
  46. };
  47. var darkMode = getGMValue("darkMode", "follow");
  48. var is_mSite, is_acmsguru, is_oldLatex, is_contest, is_problem, is_problemset, is_standings;
  49. var bottomZh_CN, showLoading, hoverTargetAreaDisplay, expandFoldingblocks, renderPerfOpt, enableSegmentedTranslation, translation, commentTranslationChoice;
  50. var openai_model, openai_key, openai_proxy, openai_header, openai_data, opneaiConfig;
  51. var replaceSymbol, commentPaging, showJumpToLuogu, loaded;
  52. var showClistRating_contest, showClistRating_problem, showClistRating_problemset, RatingHidden, clist_Authorization;
  53. var standingsRecolor;
  54. function init() {
  55. const { hostname, href } = window.location;
  56. is_mSite = hostname.startsWith('m');
  57. is_acmsguru = href.includes("acmsguru");
  58. is_oldLatex = $('.tex-span').length;
  59. is_contest = /\/contest\/[\d\/\s]+$/.test(href) && !href.includes('/problem/');
  60. is_problem = href.includes('/problem/');
  61. is_problemset = href.includes('/problemset') && !href.includes('/problem/');
  62. is_standings = href.includes('/standings');
  63. // 说明为旧的latex渲染
  64. if (is_oldLatex) {
  65. var newElement = $("<div></div>").addClass("alert alert-warning ojbetter-alert").html(`
  66. 注意:当前页面存在使用非 MathJax 库渲染为 HTML Latex 公式(这通常是一道古老的题目),这导致 CodeforcesBetter! 无法将其还原回 Latex,因此当前页面部分功能不适用。
  67. <br>此外当前页面的翻译功能采用了特别的实现方式,因此可能会出现排版错位的情况。
  68. `).css({ "margin": "1em", "text-align": "center", "position": "relative" });
  69. $(".menu-box:first").next().after(newElement);
  70. }
  71. bottomZh_CN = getGMValue("bottomZh_CN", true);
  72. showLoading = getGMValue("showLoading", true);
  73. hoverTargetAreaDisplay = getGMValue("hoverTargetAreaDisplay", false);
  74. expandFoldingblocks = getGMValue("expandFoldingblocks", true);
  75. renderPerfOpt = getGMValue("renderPerfOpt", false);
  76. commentPaging = getGMValue("commentPaging", true);
  77. enableSegmentedTranslation = getGMValue("enableSegmentedTranslation", false);
  78. showJumpToLuogu = getGMValue("showJumpToLuogu", true);
  79. standingsRecolor = getGMValue("standingsRecolor", true);
  80. loaded = getGMValue("loaded", false);
  81. translation = getGMValue("translation", "deepl");
  82. commentTranslationChoice = getGMValue("commentTranslationChoice", "0");
  83. replaceSymbol = getGMValue("replaceSymbol", "2");
  84. showClistRating_contest = getGMValue("showClistRating_contest", false);
  85. showClistRating_problem = getGMValue("showClistRating_problem", false);
  86. showClistRating_problemset = getGMValue("showClistRating_problemset", false);
  87. RatingHidden = getGMValue("RatingHidden", false);
  88. clist_Authorization = getGMValue("clist_Authorization", "");
  89. //openai
  90. opneaiConfig = getGMValue("chatgpt-config", {
  91. "choice": -1,
  92. "configurations": []
  93. });
  94. if (opneaiConfig.choice !== -1 && opneaiConfig.configurations.length !== 0) {
  95. const configAtIndex = opneaiConfig.configurations[opneaiConfig.choice];
  96.  
  97. if (configAtIndex == undefined) {
  98. let existingConfig = GM_getValue('chatgpt-config');
  99. existingConfig.choice = 0;
  100. GM_setValue('chatgpt-config', existingConfig);
  101. location.reload();
  102. }
  103.  
  104. openai_model = configAtIndex.model;
  105. openai_key = configAtIndex.key;
  106. openai_proxy = configAtIndex.proxy;
  107. openai_header = configAtIndex._header ?
  108. configAtIndex._header.split("\n").map(header => {
  109. const [key, value] = header.split(":");
  110. return { [key.trim()]: value.trim() };
  111. }) : [];
  112. openai_data = configAtIndex._data ?
  113. configAtIndex._data.split("\n").map(header => {
  114. const [key, value] = header.split(":");
  115. return { [key.trim()]: value.trim() };
  116. }) : [];
  117. }
  118. }
  119.  
  120. // 常量
  121. 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>';
  122. const unfoldIcon = `<svg t="1695971616104" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2517" width="16" height="16"><path d="M747.451 527.394L512.376 707.028l-235.071-185.71a37.975 37.975 0 0 0-23.927-8.737 38 38 0 0 0-29.248 13.674 37.984 37.984 0 0 0 4.938 53.552l259.003 205.456c14.013 11.523 34.219 11.523 48.231 0l259.003-199.002a37.974 37.974 0 0 0 5.698-53.552 37.982 37.982 0 0 0-53.552-5.315z m0 0" p-id="2518"></path><path d="M488.071 503.845c14.013 11.522 34.219 11.522 48.231 0l259.003-199.003a37.97 37.97 0 0 0 13.983-25.591 37.985 37.985 0 0 0-8.285-27.959 37.97 37.97 0 0 0-25.591-13.979 37.985 37.985 0 0 0-27.96 8.284L512.376 425.61 277.305 239.899a37.974 37.974 0 0 0-23.927-8.736 37.993 37.993 0 0 0-29.248 13.674 37.984 37.984 0 0 0 4.938 53.552l259.003 205.456z m0 0" p-id="2519"></path></svg>`;
  123. const putawayIcon = `<svg t="1695971573189" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2266" width="16" height="16"><path d="M276.549 496.606l235.075-179.634 235.071 185.711a37.975 37.975 0 0 0 23.927 8.737 38 38 0 0 0 29.248-13.674 37.986 37.986 0 0 0-4.938-53.552L535.929 238.737c-14.013-11.523-34.219-11.523-48.231 0L228.695 437.739a37.974 37.974 0 0 0-5.698 53.552 37.982 37.982 0 0 0 53.552 5.315z m0 0" p-id="2267"></path><path d="M535.929 520.155c-14.013-11.522-34.219-11.522-48.231 0L228.695 719.158a37.97 37.97 0 0 0-13.983 25.591 37.985 37.985 0 0 0 8.285 27.959 37.97 37.97 0 0 0 25.591 13.979 37.985 37.985 0 0 0 27.96-8.284L511.624 598.39l235.071 185.711a37.974 37.974 0 0 0 23.927 8.736 37.993 37.993 0 0 0 29.248-13.674 37.984 37.984 0 0 0-4.938-53.552L535.929 520.155z m0 0" p-id="2268"></path></svg>`;
  124. const copyIcon = `<svg t="1695970366492" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2499" width="16" height="16"><path d="M720 192h-544A80.096 80.096 0 0 0 96 272v608C96 924.128 131.904 960 176 960h544c44.128 0 80-35.872 80-80v-608C800 227.904 764.128 192 720 192z m16 688c0 8.8-7.2 16-16 16h-544a16 16 0 0 1-16-16v-608a16 16 0 0 1 16-16h544a16 16 0 0 1 16 16v608z" p-id="2500"></path><path d="M848 64h-544a32 32 0 0 0 0 64h544a16 16 0 0 1 16 16v608a32 32 0 1 0 64 0v-608C928 99.904 892.128 64 848 64z" p-id="2501"></path><path d="M608 360H288a32 32 0 0 0 0 64h320a32 32 0 1 0 0-64zM608 520H288a32 32 0 1 0 0 64h320a32 32 0 1 0 0-64zM480 678.656H288a32 32 0 1 0 0 64h192a32 32 0 1 0 0-64z" p-id="2502"></path></svg>`;
  125. const clistIcon = `<svg width="37.7pt" height="10pt" viewBox="0 0 181 48" version="1.1" xmlns="http://www.w3.org/2000/svg"><g id="#0057b8ff"><path fill="#0057b8" opacity="1.00" d=" M 17.36 0.00 L 18.59 0.00 C 23.84 6.49 30.28 11.92 36.01 17.98 C 34.01 19.99 32.01 21.99 30.00 23.99 C 26.02 19.97 22.02 15.98 18.02 11.99 C 14.01 15.98 10.01 19.99 6.00 23.99 C 4.16 22.04 2.30 20.05 0.00 18.61 L 0.00 17.37 C 3.44 15.11 6.00 11.84 8.96 9.03 C 11.79 6.05 15.09 3.47 17.36 0.00 Z" /></g><g id="#a0a0a0ff"><path fill="#a0a0a0" opacity="1.00" d=" M 56.76 13.74 C 61.48 4.80 76.07 3.90 81.77 12.27 C 83.09 13.94 83.44 16.10 83.91 18.12 C 81.53 18.23 79.16 18.24 76.78 18.23 C 75.81 15.72 73.99 13.31 71.14 12.95 C 67.14 12.02 63.45 15.29 62.48 18.99 C 61.30 23.27 61.71 28.68 65.34 31.70 C 67.82 34.05 72.19 33.93 74.61 31.55 C 75.97 30.18 76.35 28.23 76.96 26.48 C 79.36 26.43 81.77 26.44 84.17 26.56 C 83.79 30.09 82.43 33.49 79.89 36.02 C 74.14 41.35 64.17 40.80 58.77 35.25 C 53.52 29.56 53.18 20.38 56.76 13.74 Z" />
  126. <path fill="#a0a0a0" opacity="1.00" d=" M 89.01 7.20 C 91.37 7.21 93.74 7.21 96.11 7.22 C 96.22 15.71 96.10 24.20 96.18 32.69 C 101.25 32.76 106.32 32.63 111.39 32.79 C 111.40 34.86 111.41 36.93 111.41 39.00 C 103.94 39.00 96.47 39.00 89.00 39.00 C 89.00 28.40 88.99 17.80 89.01 7.20 Z" /><path fill="#a0a0a0" opacity="1.00" d=" M 115.00 7.21 C 117.33 7.21 119.66 7.21 121.99 7.21 C 122.01 17.81 122.00 28.40 122.00 39.00 C 119.67 39.00 117.33 39.00 115.00 39.00 C 115.00 28.40 114.99 17.80 115.00 7.21 Z" /><path fill="#a0a0a0" opacity="1.00" d=" M 133.35 7.47 C 139.11 5.56 146.93 6.28 150.42 11.87 C 151.42 13.39 151.35 15.31 151.72 17.04 C 149.33 17.05 146.95 17.05 144.56 17.03 C 144.13 12.66 138.66 11.12 135.34 13.30 C 133.90 14.24 133.54 16.87 135.35 17.61 C 139.99 20.02 145.90 19.54 149.92 23.19 C 154.43 26.97 153.16 35.36 147.78 37.72 C 143.39 40.03 137.99 40.11 133.30 38.69 C 128.80 37.34 125.34 32.90 125.91 28.10 C 128.22 28.10 130.53 28.11 132.84 28.16 C 132.98 34.19 142.68 36.07 145.18 30.97 C 146.11 27.99 142.17 27.05 140.05 26.35 C 135.54 25.04 129.83 24.33 127.50 19.63 C 125.30 14.78 128.42 9.00 133.35 7.47 Z" />
  127. <path fill="#a0a0a0" opacity="1.00" d=" M 153.31 7.21 C 161.99 7.21 170.67 7.21 179.34 7.21 C 179.41 9.30 179.45 11.40 179.48 13.50 C 176.35 13.50 173.22 13.50 170.09 13.50 C 170.05 21.99 170.12 30.48 170.05 38.98 C 167.61 39.00 165.18 39.00 162.74 39.00 C 162.64 30.52 162.73 22.04 162.69 13.55 C 159.57 13.49 156.44 13.49 153.32 13.50 C 153.32 11.40 153.31 9.31 153.31 7.21 Z" /></g><g id="#ffd700ff"><path fill="#ffd700" opacity="1.00" d=" M 12.02 29.98 C 14.02 27.98 16.02 25.98 18.02 23.98 C 22.01 27.99 26.03 31.97 30.00 35.99 C 34.01 31.99 38.01 27.98 42.02 23.99 C 44.02 25.98 46.02 27.98 48.01 29.98 C 42.29 36.06 35.80 41.46 30.59 48.00 L 29.39 48.00 C 24.26 41.42 17.71 36.08 12.02 29.98 Z" /></g></svg>`;
  128. 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: 100; }`;
  129. 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: 300; }`;
  130.  
  131. // 报错信息捕获
  132. /*let errorMessages = "";
  133. const defaultError = console.error.bind(console);
  134. console.error = (message) => {
  135. const error = new Error();
  136. const stack = error.stack.split("\n").slice(2).join("\n");
  137. const now = new Date().toLocaleString();
  138. errorMessages += "\n## " + message + "\n### time: " + now +"\n" + stack + "\n";
  139. defaultError(message);
  140. };
  141. window.onerror = (message, source, lineno, colno, error) => {
  142. const now = new Date().toLocaleString();
  143. errorMessages += "\n## " + message + "\n### time: " + now +"\n" + error.stack + "\n";
  144. defaultError(message);
  145. return true;
  146. };*/
  147.  
  148. // 切换系统黑暗监听
  149. const mediaQueryList = window.matchMedia('(prefers-color-scheme: dark)');
  150. const changeEventListeners = [];
  151. function handleColorSchemeChange(event) {
  152. const newColorScheme = event.matches ? $('html').attr('data-theme', 'dark') : $('html').attr('data-theme', 'light');
  153. if (!event.matches) {
  154. var originalColor = $(this).data("original-color");
  155. $(this).css("background-color", originalColor);
  156. }
  157. }
  158.  
  159. // 黑暗模式
  160. (function setDark() {
  161. // 初始化
  162. function setDarkTheme() {
  163. const htmlElement = document.querySelector('html');
  164. if (htmlElement) {
  165. htmlElement.setAttribute('data-theme', 'dark');
  166. } else {
  167. setTimeout(setDarkTheme, 100);
  168. }
  169. }
  170. if (darkMode == "dark") {
  171. setDarkTheme();
  172. } else if (darkMode == "follow") {
  173. // 添加事件监听器
  174. changeEventListeners.push(handleColorSchemeChange);
  175. mediaQueryList.addEventListener('change', handleColorSchemeChange);
  176.  
  177. if (window.matchMedia('(prefers-color-scheme: dark)').matches) setDarkTheme();
  178. }
  179.  
  180. GM_addStyle(`
  181. /* 黑暗支持 */
  182. html[data-theme=dark]:root {
  183. color-scheme: light dark;
  184. }
  185. /* 文字颜色1 */
  186. html[data-theme=dark] .title,html[data-theme=dark] .problem-statement,
  187. html[data-theme=dark] .ttypography, html[data-theme=dark] .roundbox, html[data-theme=dark] .info,
  188. html[data-theme=dark] .ttypography .bordertable, html[data-theme=dark] .ttypography .bordertable thead th,
  189. html[data-theme=dark] .ttypography h1, html[data-theme=dark] .ttypography h2, html[data-theme=dark] .ttypography h3,
  190. html[data-theme=dark] .ttypography h4, html[data-theme=dark] .ttypography h5, html[data-theme=dark] .ttypography h6
  191. html[data-theme=dark] .datatable table, html[data-theme=dark] .problem-statement .sample-tests pre,
  192. html[data-theme=dark] .alert-success, html[data-theme=dark] .alert-info, html[data-theme=dark] .alert-error,
  193. html[data-theme=dark] .alert-warning, html[data-theme=dark] .markItUpEditor, html[data-theme=dark] #pageContent,
  194. html[data-theme=dark] .ace-chrome .ace_gutter, html[data-theme=dark] .translate-problem-statement,
  195. html[data-theme=dark] .setting-name, html[data-theme=dark] .CFBetter_setting_menu, html[data-theme=dark] .help_tip .tip_text,
  196. html[data-theme=dark] textarea, html[data-theme=dark] .user-black, html[data-theme=dark] .comments label.show-archived,
  197. html[data-theme=dark] .comments label.show-archived *, html[data-theme=dark] table,
  198. html[data-theme=dark] #items-per-page, html[data-theme=dark] #pagBar, html[data-theme=dark] .CFBetter_setting_sidebar li a:link{
  199. color: #a0adb9 !important;
  200. }
  201. html[data-theme=dark] h1 a, html[data-theme=dark] h2 a, html[data-theme=dark] h3 a, html[data-theme=dark] h4 a{
  202. color: #adbac7;
  203. }
  204. /* 文字颜色2 */
  205. html[data-theme=dark] .contest-state-phase, html[data-theme=dark] .legendary-user-first-letter,
  206. html[data-theme=dark] .lang-chooser,
  207. html[data-theme=dark] .second-level-menu-list li a, html[data-theme=dark] #footer,
  208. html[data-theme=dark] .ttypography .tt, html[data-theme=dark] select,
  209. html[data-theme=dark] .roundbox .caption, html[data-theme=dark] .topic .title *,
  210. html[data-theme=dark] .user-admin, html[data-theme=dark] button.html2mdButton:hover,
  211. html[data-theme=dark] .CFBetter_modal button{
  212. color: #9099a3 !important;
  213. }
  214. /* 文字颜色3 */
  215. html[data-theme=dark] button.html2mdButton{
  216. color: #6385a6;
  217. }
  218. html[data-theme=dark] input{
  219. color: #6385a6 !important;
  220. }
  221. /* 文字颜色4 */
  222. html[data-theme=dark] .ttypography .MathJax, html[data-theme=dark] .MathJax span{
  223. color: #cbd6e2 !important;
  224. }
  225. /* 链接颜色 */
  226. html[data-theme=dark] a:link {
  227. color: #3989c9;
  228. }
  229. html[data-theme=dark] a:visited {
  230. color: #8590a6;
  231. }
  232. html[data-theme=dark] .menu-box a, html[data-theme=dark] .sidebox th a{
  233. color: #9099a3 !important;
  234. }
  235. /* 按钮 */
  236. html[data-theme=dark] .second-level-menu-list li.backLava {
  237. border-radius: 6px;
  238. overflow: hidden;
  239. filter: invert(1) hue-rotate(.5turn);
  240. }
  241. html[data-theme=dark] input:hover{
  242. background-color: #22272e !important;
  243. }
  244. /* 背景层次1 */
  245. html[data-theme=dark] body, html[data-theme=dark] .ttypography .bordertable thead th,
  246. html[data-theme=dark] .datatable table, html[data-theme=dark] .datatable .dark, html[data-theme=dark] li#add_button,
  247. html[data-theme=dark] .problem-statement .sample-tests pre, html[data-theme=dark] .markItUpEditor,
  248. html[data-theme=dark] .SumoSelect>.CaptionCont, html[data-theme=dark] .SumoSelect>.optWrapper,
  249. html[data-theme=dark] .SumoSelect>.optWrapper.multiple>.options li.opt span i, html[data-theme=dark] .ace_scroller,
  250. html[data-theme=dark] .CFBetter_setting_menu, html[data-theme=dark] .help_tip .tip_text, html[data-theme=dark] li#add_button:hover,
  251. html[data-theme=dark] textarea, html[data-theme=dark] .state, html[data-theme=dark] .ace-chrome .ace_gutter-active-line,
  252. html[data-theme=dark] .sidebar-menu ul li:hover, html[data-theme=dark] .sidebar-menu ul li.active,
  253. html[data-theme=dark] label.config_bar_ul_li_text:hover, html[data-theme=dark] button.html2mdButton:hover,
  254. html[data-theme=dark] .CFBetter_setting_sidebar li a.active, html[data-theme=dark] .CFBetter_setting_sidebar li,
  255. html[data-theme=dark] .CFBetter_setting_menu::-webkit-scrollbar-track, html[data-theme=dark] .CFBetter_setting_content::-webkit-scrollbar-track,
  256. html[data-theme=dark] .CFBetter_modal, html[data-theme=dark] .CFBetter_modal button:hover{
  257. background-color: #22272e !important;
  258. }
  259. /* 背景层次2 */
  260. html[data-theme=dark] .roundbox, html[data-theme=dark] .roundbox .dark, html[data-theme=dark] .bottom-links,
  261. html[data-theme=dark] button.html2mdButton, html[data-theme=dark] .spoiler-content, html[data-theme=dark] input,
  262. html[data-theme=dark] .problem-statement .test-example-line-even, html[data-theme=dark] .highlight-blue,
  263. html[data-theme=dark] .ttypography .tt, html[data-theme=dark] select,
  264. html[data-theme=dark] .alert-success, html[data-theme=dark] .alert-info, html[data-theme=dark] .alert-error,
  265. html[data-theme=dark] .alert-warning, html[data-theme=dark] .SumoSelect>.optWrapper>.options li.opt:hover,
  266. html[data-theme=dark] .input-output-copier:hover, html[data-theme=dark] .translate-problem-statement-panel,
  267. html[data-theme=dark] .aceEditorTd, html[data-theme=dark] .ace-chrome .ace_gutter,
  268. html[data-theme=dark] .translate-problem-statement, html[data-theme=dark] .datatable,
  269. html[data-theme=dark] .CFBetter_setting_list, html[data-theme=dark] #config_bar_list,
  270. html[data-theme=dark] .CFBetter_setting_menu hr,
  271. html[data-theme=dark] .highlighted-row td, html[data-theme=dark] .highlighted-row th,
  272. html[data-theme=dark] .pagination span.active, html[data-theme=dark] .CFBetter_setting_sidebar li a,
  273. html[data-theme=dark] .CFBetter_setting_menu::-webkit-scrollbar-thumb, html[data-theme=dark] .CFBetter_setting_content::-webkit-scrollbar-thumb,
  274. html[data-theme=dark] .CFBetter_modal button{
  275. background-color: #2d333b !important;
  276. }
  277. /* 实线边框颜色-圆角 */
  278. html[data-theme=dark] .roundbox, html[data-theme=dark] .roundbox .rtable td,
  279. html[data-theme=dark] button.html2mdButton, html[data-theme=dark] .sidebar-menu ul li,
  280. html[data-theme=dark] input, html[data-theme=dark] .ttypography .tt, html[data-theme=dark] #items-per-page,
  281. html[data-theme=dark] .datatable td, html[data-theme=dark] .datatable th,
  282. html[data-theme=dark] .alert-success, html[data-theme=dark] .alert-info, html[data-theme=dark] .alert-error,
  283. html[data-theme=dark] .alert-warning, html[data-theme=dark] .translate-problem-statement,
  284. html[data-theme=dark] textarea, html[data-theme=dark] .input-output-copier{
  285. border: 1px solid #424b56 !important;
  286. border-radius: 2px;
  287. }
  288. /* 实线边框颜色-无圆角 */
  289. html[data-theme=dark] .CFBetter_setting_list, html[data-theme=dark] #config_bar_list,
  290. html[data-theme=dark] label.config_bar_ul_li_text, html[data-theme=dark] .problem-statement .sample-tests .input,
  291. html[data-theme=dark] .problem-statement .sample-tests .output, html[data-theme=dark] .pagination span.active,
  292. html[data-theme=dark] .CFBetter_setting_sidebar li, html[data-theme=dark] .CFBetter_setting_menu select,
  293. html[data-theme=dark] .translate-problem-statement-panel, html[data-theme=dark] .CFBetter_modal button{
  294. border: 1px solid #424b56 !important;
  295. }
  296. html[data-theme=dark] .roundbox .titled, html[data-theme=dark] .roundbox .rtable th {
  297. border-bottom: 1px solid #424b56 !important;
  298. }
  299. html[data-theme=dark] .roundbox .bottom-links, html[data-theme=dark] #footer{
  300. border-top: 1px solid #424b56 !important;
  301. }
  302. html[data-theme=dark] .topic .content {
  303. border-left: 4px solid #424b56 !important;
  304. }
  305. html[data-theme=dark] .CFBetter_setting_sidebar {
  306. border-right: 1px solid #424b56 !important;
  307. }
  308. /* 虚线边框颜色 */
  309. html[data-theme=dark] .comment-table, html[data-theme=dark] li#add_button,
  310. html[data-theme=dark] .CFBetter_setting_menu_label_text{
  311. border: 1px dashed #424b56 !important;
  312. }
  313. html[data-theme=dark] li#add_button:hover{
  314. border: 1px dashed #03A9F4 !important;
  315. background-color: #2d333b !important;
  316. color: #03A9F4 !important;
  317. }
  318. /* focus-visible */
  319. html[data-theme=dark] input:focus-visible, html[data-theme=dark] textarea, html[data-theme=dark] select{
  320. border-width: 1.5px !important;
  321. outline: none;
  322. }
  323. /* 图片-亮度 */
  324. html[data-theme=dark] img{
  325. opacity: .75;
  326. }
  327. /* 图片-反转 */
  328. html[data-theme=dark] .SumoSelect>.CaptionCont>label>i, html[data-theme=dark] .delete-resource-link{
  329. filter: invert(1) hue-rotate(.5turn);
  330. }
  331. /* 区域遮罩 */
  332. html[data-theme=dark] .overlay {
  333. background: repeating-linear-gradient(135deg, #49525f6e, #49525f6e 30px, #49525f29 0px, #49525f29 55px);
  334. color: #9099a3;
  335. text-shadow: 0px 0px 2px #000000;
  336. }
  337. /* 其他样式 */
  338. html[data-theme=dark] .rated-user{
  339. display: initial;
  340. }
  341. html[data-theme=dark] .datatable .ilt, html[data-theme=dark] .datatable .irt,
  342. html[data-theme=dark] .datatable .ilb, html[data-theme=dark] .datatable .irb,
  343. html[data-theme=dark] .datatable .lt, html[data-theme=dark] .datatable .rt,
  344. html[data-theme=dark] .datatable .lb, html[data-theme=dark] .datatable .rb{
  345. background: none;
  346. }
  347. html[data-theme=dark] .problems .accepted-problem td.id{
  348. border-left: 6px solid #47837d !important;
  349. }
  350. html[data-theme=dark] .problems .rejected-problem td.id{
  351. border-left: 6px solid #ef9a9a !important;
  352. }
  353. html[data-theme=dark] .problems .accepted-problem td.act {
  354. background-color: #47837d !important;
  355. border-radius: 0px;
  356. }
  357. html[data-theme=dark] .problems .rejected-problem td.act{
  358. background-color: #ef9a9a !important;
  359. border-radius: 0px;
  360. }
  361. html[data-theme=dark] .CFBetter_setting_menu, html[data-theme=dark] .CFBetter_modal{
  362. box-shadow: 0px 0px 0px 4px #2d333b;
  363. border: 1px solid #2d333b;
  364. }
  365. html[data-theme=dark] .collapsible-topic.collapsed .content .collapsible-topic-options:before{
  366. background-image: linear-gradient(#22272e00, #22272e);
  367. }
  368. html[data-theme=dark] .alert{
  369. text-shadow: none;
  370. }
  371. html[data-theme=dark] input[type="radio"]:checked+.CFBetter_setting_menu_label_text {
  372. color: #a0adb9 !important;
  373. border: 1px solid #326154 !important;
  374. }
  375. /* 评测状态文字颜色 */
  376. html[data-theme=dark] .verdict-accepted, html[data-theme=dark] .verdict-accepted-challenged,
  377. html[data-theme=dark] .verdict-successful-challenge{
  378. color: #0a0 !important;
  379. }
  380. html[data-theme=dark] .verdict-failed, html[data-theme=dark] .verdict-challenged{
  381. color: red !important;
  382. }
  383. html[data-theme=dark] .verdict-rejected, html[data-theme=dark] .verdict-unsuccessful-challenge{
  384. color: #673ab7 !important;
  385. }
  386. html[data-theme=dark] .verdict-waiting {
  387. color: gray !important;
  388. }
  389. `);
  390. })()
  391.  
  392. // 样式
  393. GM_addStyle(`
  394. html {
  395. scroll-behavior: smooth;
  396. }
  397. :root {
  398. --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";
  399. }
  400. span.mdViewContent {
  401. white-space: pre-wrap;
  402. }
  403. /*翻译区域提示*/
  404. .overlay {
  405. pointer-events: none;
  406. position: absolute;
  407. top: 0;
  408. left: 0;
  409. width: 100%;
  410. height: 100%;
  411. background: repeating-linear-gradient(135deg, #97e7cacc, #97e7cacc 30px, #e9fbf1cc 0px, #e9fbf1cc 55px);
  412. border-radius: 5px;
  413. display: flex;
  414. align-items: center;
  415. justify-content: center;
  416. color: #00695C;
  417. font-size: 16px;
  418. font-weight: bold;
  419. text-shadow: 0px 0px 2px #edfcf4;
  420. }
  421. /*翻译div*/
  422. .translate-problem-statement {
  423. justify-items: start;
  424. letter-spacing: 1.8px;
  425. color: #059669;
  426. background-color: #f9f9fa;
  427. border: 1px solid #10b981;
  428. border-radius: 0.3rem;
  429. padding: 5px;
  430. margin: -1px 0px 10px 0px;
  431. width: 100%;
  432. box-sizing: border-box;
  433. font-size: 13px;
  434. }
  435. .translate-problem-statement.error_translate {
  436. color: red;
  437. border-color: red;
  438. }
  439. .translate-problem-statement a, .translate-problem-statement a:link {
  440. color: #10b981;
  441. font-weight: 600;
  442. background: 0 0;
  443. text-decoration: none;
  444. }
  445. .translate-problem-statement ol, .translate-problem-statement ul {
  446. display: grid;
  447. margin-inline-start: 0.8em;
  448. margin-block-start: 0em;
  449. margin: 0.5em 0 0 3em;
  450. }
  451. .translate-problem-statement li {
  452. display: list-item;
  453. height: auto;
  454. word-wrap: break-word;
  455. }
  456. .translate-problem-statement ol li {
  457. list-style-type: auto;
  458. }
  459. .translate-problem-statement ul li {
  460. list-style-type: disc;
  461. }
  462. .translate-problem-statement img {
  463. max-width: 100.0%;
  464. max-height: 100.0%;
  465. }
  466. .ttypography .translate-problem-statement .MathJax {
  467. color: #059669!important;
  468. }
  469. .translate-problem-statement span.math {
  470. margin: 0px 2.5px !important;
  471. }
  472. .translate-problem-statement a:hover {
  473. background-color: #800;
  474. color: #fff;
  475. text-decoration: none;
  476. }
  477. .translate-problem-statement-panel{
  478. display: flex;
  479. justify-content: space-between;
  480. background-color: #f9f9fa;
  481. border: 1px solid #c5ebdf;
  482. border-radius: 0.3rem;
  483. margin-bottom: 4px;
  484. }
  485. .html2md-panel {
  486. display: flex;
  487. justify-content: flex-end;
  488. align-items: center;
  489. }
  490. .html2md-panel a {
  491. text-decoration: none;
  492. }
  493. .html2mdButton {
  494. display: flex;
  495. align-items: center;
  496. cursor: pointer;
  497. background-color: #ffffff;
  498. color: #606266;
  499. height: 22px;
  500. width: auto;
  501. font-size: 13px;
  502. border-radius: 0.3rem;
  503. padding: 1px 5px;
  504. margin: 5px !important;
  505. border: 1px solid #dcdfe6;
  506. }
  507. .html2mdButton:hover {
  508. color: #409eff;
  509. border-color: #409eff;
  510. background-color: #f1f8ff;
  511. }
  512. button.html2mdButton.copied {
  513. background-color: #f0f9eb;
  514. color: #67c23e;
  515. border: 1px solid #b3e19d;
  516. }
  517. button.html2mdButton.mdViewed {
  518. background-color: #fdf6ec;
  519. color: #e6a23c;
  520. border: 1px solid #f3d19e;
  521. }
  522. button.html2mdButton.error {
  523. background-color: #fef0f0;
  524. color: #f56c6c;
  525. border: 1px solid #fab6b6;
  526. }
  527. button.translated {
  528. background-color: #f0f9eb;
  529. color: #67c23e;
  530. border: 1px solid #b3e19d;
  531. }
  532. button.html2mdButton.reTranslation {
  533. background-color: #f4f4f5;
  534. color: #909399;
  535. border: 1px solid #c8c9cc;
  536. }
  537. .borderlessButton{
  538. display: flex;
  539. align-items: center;
  540. margin: 2.5px 7px;
  541. fill: #9E9E9E;
  542. }
  543. .borderlessButton:hover{
  544. cursor: pointer;
  545. fill: #059669;
  546. }
  547. .translate-problem-statement table {
  548. border: 1px #ccc solid !important;
  549. margin: 1.5em 0 !important;
  550. color: #059669 !important;
  551. }
  552. .translate-problem-statement table thead th {
  553. border: 1px #ccc solid !important;
  554. color: #059669 !important;
  555. }
  556. .translate-problem-statement table td {
  557. border-right: 1px solid #ccc;
  558. border-top: 1px solid #ccc;
  559. padding: 0.7143em 0.5em;
  560. }
  561. .translate-problem-statement table th {
  562. padding: 0.7143em 0.5em;
  563. }
  564. .translate-problem-statement p:not(:first-child) {
  565. margin: 1.5em 0 0;
  566. }
  567. .translate-problem-statement p {
  568. line-height: 20px !important;
  569. }
  570. /*设置面板*/
  571. header .enter-or-register-box, header .languages {
  572. position: absolute;
  573. right: 170px;
  574. }
  575. button.html2mdButton.CFBetter_setting {
  576. float: right;
  577. height: 30px;
  578. background: #60a5fa;
  579. color: white;
  580. margin: 10px;
  581. border: 0px;
  582. }
  583.  
  584. button.html2mdButton.CFBetter_setting.open {
  585. background-color: #e6e6e6;
  586. color: #727378;
  587. cursor: not-allowed;
  588. }
  589.  
  590. .CFBetter_setting_menu {
  591. z-index: 200;
  592. box-shadow: 0px 0px 0px 4px #ffffff;
  593. display: grid;
  594. position: fixed;
  595. top: 50%;
  596. left: 50%;
  597. width: 485px;
  598. height: 600px;
  599. transform: translate(-50%, -50%);
  600. border-radius: 6px;
  601. background-color: #f0f4f9;
  602. border-collapse: collapse;
  603. border: 1px solid #ffffff;
  604. color: #697e91;
  605. font-family: var(--vp-font-family-base);
  606. padding: 10px 20px 20px 10px;
  607. box-sizing: content-box;
  608. }
  609. .CFBetter_setting_menu h3 {
  610. margin-top: 10px;
  611. }
  612. .CFBetter_setting_menu h4 {
  613. margin: 15px 0px 10px 0px;
  614. }
  615. .CFBetter_setting_menu h4,.CFBetter_setting_menu h5 {
  616. font-weight: 600;
  617. }
  618. .CFBetter_setting_menu hr {
  619. border: none;
  620. height: 1px;
  621. background-color: #ccc;
  622. margin: 10px 0;
  623. }
  624. .CFBetter_setting_menu .badge {
  625. border-radius: 4px;
  626. border: 1px solid #009688;
  627. color: #009688;
  628. font-size: 12px;
  629. padding: 0.5px 4px;
  630. margin-left: 5px;
  631. margin-right: auto;
  632. }
  633. /* 页面切换 */
  634. .settings-page {
  635. display: none;
  636. }
  637. .settings-page.active {
  638. display: block;
  639. }
  640. .CFBetter_setting_container {
  641. display: flex;
  642. }
  643. .CFBetter_setting_sidebar {
  644. width: 100px;
  645. padding: 6px 10px 6px 6px;
  646. margin: 20px 0px;
  647. border-right: 1px solid #d4d8e9;
  648. }
  649. .CFBetter_setting_content {
  650. flex-grow: 1;
  651. width: 350px;
  652. margin: 20px 0px 0px 20px;
  653. padding-right: 10px;
  654. max-height: 580px;
  655. overflow-y: auto;
  656. box-sizing: border-box;
  657. }
  658. .CFBetter_setting_sidebar h3 {
  659. margin-top: 0;
  660. }
  661. .CFBetter_setting_sidebar hr {
  662. margin-top: 10px;
  663. margin-bottom: 10px;
  664. border: none;
  665. border-top: 1px solid #DADCE0;
  666. }
  667. .CFBetter_setting_sidebar ul {
  668. list-style-type: none;
  669. margin: 0;
  670. padding: 0;
  671. }
  672. .CFBetter_setting_sidebar li {
  673. margin: 5px 0px;
  674. background-color: #ffffff;
  675. border: 1px solid #d4d8e9;
  676. border-radius: 4px;
  677. font-size: 16px;
  678. }
  679. .CFBetter_setting_sidebar li a {
  680. text-decoration: none;
  681. display: flex;
  682. width: 100%;
  683. color: gray;
  684. letter-spacing: 2px;
  685. padding: 7px;
  686. border-radius: 4px;
  687. align-items: center;
  688. -webkit-box-sizing: border-box;
  689. -moz-box-sizing: border-box;
  690. box-sizing: border-box;
  691. }
  692. .CFBetter_setting_sidebar li a.active {
  693. background-color: #eceff1c7;
  694. }
  695. /* 下拉选择框 */
  696. .CFBetter_setting_menu select {
  697. margin-left: 6px;
  698. border-style: solid;
  699. border-color: #26A69A;
  700. color: #009688;
  701. font-size: 15px;
  702. }
  703. .CFBetter_setting_menu select:focus-visible {
  704. outline: none;
  705. }
  706. /*设置面板-滚动条*/
  707. .CFBetter_setting_menu::-webkit-scrollbar, .CFBetter_setting_content::-webkit-scrollbar {
  708. width: 5px;
  709. height: 7px;
  710. background-color: #aaa;
  711. }
  712. .CFBetter_setting_menu::-webkit-scrollbar-thumb, .CFBetter_setting_content::-webkit-scrollbar-thumb {
  713. background-clip: padding-box;
  714. background-color: #d7d9e4;
  715. }
  716. .CFBetter_setting_menu::-webkit-scrollbar-track, .CFBetter_setting_content::-webkit-scrollbar-track {
  717. background-color: #f1f1f1;
  718. }
  719. /*设置面板-关闭按钮*/
  720. .CFBetter_setting_menu .tool-box {
  721. position: absolute;
  722. align-items: center;
  723. justify-content: center;
  724. width: 20px;
  725. height: 20px;
  726. overflow: hidden;
  727. border-radius: 10px;
  728. top: 3px;
  729. right: 3px;
  730. }
  731.  
  732. .CFBetter_setting_menu .btn-close {
  733. display: flex;
  734. text-align: center;
  735. width: 20px;
  736. height: 20px;
  737. color: transparent;
  738. font-size: 0;
  739. cursor: pointer;
  740. background-color: #ff000080;
  741. border: none;
  742. margin: 0px;
  743. padding: 0px;
  744. overflow: hidden;
  745. transition: .15s ease all;
  746. align-items: center;
  747. justify-content: center;
  748. box-sizing: border-box;
  749. }
  750.  
  751. .CFBetter_setting_menu .btn-close:hover {
  752. width: 20px;
  753. height: 20px !important;
  754. font-size: 17px;
  755. color: #ffffff;
  756. background-color: #ff0000cc;
  757. box-shadow: 0 5px 5px 0 #00000026;
  758. }
  759.  
  760. .CFBetter_setting_menu .btn-close:active {
  761. width: 20px;
  762. height: 20px;
  763. font-size: 1px;
  764. color: #ffffffde;
  765. --shadow-btn-close: 0 3px 3px 0 #00000026;
  766. box-shadow: var(--shadow-btn-close);
  767. }
  768.  
  769. /*设置面板-checkbox*/
  770. .CFBetter_setting_menu input[type=checkbox]:focus {
  771. outline: 0px;
  772. }
  773.  
  774. .CFBetter_setting_menu input[type="checkbox"] {
  775. margin: 0px;
  776. appearance: none;
  777. -webkit-appearance: none;
  778. width: 40px;
  779. height: 20px !important;
  780. border: 1.5px solid #D7CCC8;
  781. padding: 0px !important;
  782. border-radius: 20px;
  783. background: #efebe978;
  784. position: relative;
  785. box-sizing: border-box;
  786. }
  787.  
  788. .CFBetter_setting_menu input[type="checkbox"]::before {
  789. content: "";
  790. width: 14px;
  791. height: 14px;
  792. background: #D7CCC8;
  793. border: 1.5px solid #BCAAA4;
  794. border-radius: 50%;
  795. position: absolute;
  796. top: 0;
  797. left: 0;
  798. transform: translate(2%, 2%);
  799. transition: all 0.3s ease-in-out;
  800. }
  801.  
  802. .CFBetter_setting_menu input[type="checkbox"]::after {
  803. 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");
  804. position: absolute;
  805. top: 0;
  806. left: 24px;
  807. }
  808.  
  809. .CFBetter_setting_menu input[type="checkbox"]:checked {
  810. border: 1.5px solid #C5CAE9;
  811. background: #E8EAF6;
  812. }
  813.  
  814. .CFBetter_setting_menu input[type="checkbox"]:checked::before {
  815. background: #C5CAE9;
  816. border: 1.5px solid #7986CB;
  817. transform: translate(122%, 2%);
  818. transition: all 0.3s ease-in-out;
  819. }
  820.  
  821. .CFBetter_setting_menu input[type="checkbox"]:checked::after {
  822. 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");
  823. position: absolute;
  824. top: 1.5px;
  825. left: 4.5px;
  826. }
  827.  
  828. .CFBetter_setting_menu label, #darkMode_span, #loaded_span {
  829. font-size: 16px;
  830. }
  831.  
  832. .CFBetter_setting_list {
  833. display: flex;
  834. align-items: center;
  835. padding: 10px;
  836. margin: 5px 0px;
  837. background-color: #ffffff;
  838. border-bottom: 1px solid #c9c6c696;
  839. border-radius: 8px;
  840. justify-content: space-between;
  841. }
  842.  
  843. /*设置面板-radio*/
  844. .CFBetter_setting_menu #translation-settings label {
  845. display: grid;
  846. list-style-type: none;
  847. padding-inline-start: 0px;
  848. overflow-x: auto;
  849. max-width: 100%;
  850. align-items: center;
  851. margin: 3px 0px;
  852. }
  853.  
  854. .CFBetter_setting_menu_label_text {
  855. display: flex;
  856. border: 1px dashed #00aeeccc;
  857. height: 35px;
  858. width: 100%;
  859. color: gray;
  860. font-weight: 300;
  861. font-size: 14px;
  862. letter-spacing: 2px;
  863. padding: 7px;
  864. align-items: center;
  865. -webkit-box-sizing: border-box;
  866. -moz-box-sizing: border-box;
  867. box-sizing: border-box;
  868. }
  869.  
  870. input[type="radio"]:checked+.CFBetter_setting_menu_label_text {
  871. background: #41e49930;
  872. border: 1px solid green;
  873. color: green;
  874. font-weight: 500;
  875. }
  876.  
  877. .CFBetter_setting_menu label input[type="radio"], .CFBetter_contextmenu label input[type="radio"]{
  878. appearance: none;
  879. list-style: none;
  880. padding: 0px !important;
  881. margin: 0px;
  882. clip: rect(0 0 0 0);
  883. -webkit-clip-path: inset(100%);
  884. clip-path: inset(100%);
  885. height: 1px;
  886. overflow: hidden;
  887. position: absolute;
  888. white-space: nowrap;
  889. width: 1px;
  890. }
  891.  
  892. .CFBetter_setting_menu input[type="text"] {
  893. display: block;
  894. height: 25px !important;
  895. width: 100%;
  896. background-color: #ffffff;
  897. color: #727378;
  898. font-size: 12px;
  899. border-radius: 0.3rem;
  900. padding: 1px 5px !important;
  901. box-sizing: border-box;
  902. margin: 5px 0px 5px 0px;
  903. border: 1px solid #00aeeccc;
  904. box-shadow: 0 0 1px #0000004d;
  905. }
  906.  
  907. .CFBetter_setting_menu .CFBetter_setting_list input[type="text"] {
  908. margin-left: 5px;
  909. }
  910.  
  911. .CFBetter_setting_menu input[type="text"]:focus-visible{
  912. border-style: solid;
  913. border-color: #3f51b5;
  914. outline: none;
  915. }
  916.  
  917. .CFBetter_setting_menu_input {
  918. width: 100%;
  919. display: grid;
  920. margin-top: 5px;
  921. -webkit-box-sizing: border-box;
  922. -moz-box-sizing: border-box;
  923. box-sizing: border-box;
  924. }
  925. .CFBetter_setting_menu input::placeholder {
  926. color: #727378;
  927. }
  928. .CFBetter_setting_menu input.no_default::placeholder{
  929. color: #BDBDBD;
  930. }
  931. .CFBetter_setting_menu input.is_null::placeholder{
  932. color: red;
  933. border-width: 1.5px;
  934. }
  935. .CFBetter_setting_menu input.is_null{
  936. border-color: red;
  937. }
  938. .CFBetter_setting_menu textarea {
  939. display: block;
  940. width: 100%;
  941. height: 60px;
  942. background-color: #ffffff;
  943. color: #727378;
  944. font-size: 12px;
  945. padding: 1px 5px !important;
  946. box-sizing: border-box;
  947. margin: 5px 0px 5px 0px;
  948. border: 1px solid #00aeeccc;
  949. box-shadow: 0 0 1px #0000004d;
  950. }
  951. .CFBetter_setting_menu textarea:focus-visible{
  952. border-style: solid;
  953. border-color: #3f51b5;
  954. outline: none;
  955. }
  956. .CFBetter_setting_menu textarea::placeholder{
  957. color: #BDBDBD;
  958. font-size: 14px;
  959. }
  960.  
  961. .CFBetter_setting_menu #save {
  962. cursor: pointer;
  963. display: inline-flex;
  964. padding: 5px;
  965. background-color: #1aa06d;
  966. color: #ffffff;
  967. font-size: 14px;
  968. line-height: 1.5rem;
  969. font-weight: 500;
  970. justify-content: center;
  971. width: 100%;
  972. border-radius: 0.375rem;
  973. border: none;
  974. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  975. margin-top: 20px
  976. }
  977. .CFBetter_setting_menu button#debug_button.debug_button {
  978. width: 18%;
  979. }
  980.  
  981. .CFBetter_setting_menu span.tip {
  982. color: #999;
  983. font-size: 12px;
  984. font-weight: 500;
  985. padding: 5px 0px;
  986. }
  987. /*设置面板-tip*/
  988. .help_tip {
  989. margin-right: auto;
  990. }
  991. span.input_label {
  992. font-size: 14px;
  993. }
  994. .help_tip .tip_text {
  995. display: none;
  996. position: absolute;
  997. color: #697e91;
  998. font-weight: 400;
  999. font-size: 14px;
  1000. letter-spacing: 0px;
  1001. background-color: #ffffff;
  1002. padding: 10px;
  1003. margin: 5px 0px;
  1004. border-radius: 4px;
  1005. border: 1px solid #e4e7ed;
  1006. box-shadow: 0px 0px 12px rgba(0, 0, 0, .12);
  1007. z-index: 100;
  1008. }
  1009. .help_tip .tip_text p {
  1010. margin-bottom: 5px;
  1011. }
  1012. .help_tip .tip_text:before {
  1013. content: "";
  1014. position: absolute;
  1015. top: -20px;
  1016. right: -10px;
  1017. bottom: -10px;
  1018. left: -10px;
  1019. z-index: -1;
  1020. }
  1021. .help-icon {
  1022. cursor: help;
  1023. width: 15px;
  1024. color: #b4b9d4;
  1025. margin-left: 5px;
  1026. margin-top: 3px;
  1027. }
  1028. .CFBetter_setting_menu .CFBetter_setting_menu_label_text .help_tip .help-icon {
  1029. color: #7fbeb2;
  1030. }
  1031. .help_tip .help-icon:hover + .tip_text, .help_tip .tip_text:hover {
  1032. display: block;
  1033. cursor: help;
  1034. width: 250px;
  1035. }
  1036.  
  1037. /*确认弹窗*/
  1038. .CFBetter_modal {
  1039. z-index: 600;
  1040. display: grid;
  1041. position: fixed;
  1042. top: 50%;
  1043. left: 50%;
  1044. transform: translate(-50%, -50%);
  1045. font-size: 12px;
  1046. font-family: var(--vp-font-family-base);
  1047. padding: 10px 20px;
  1048. box-shadow: 0px 0px 0px 4px #ffffff;
  1049. border-radius: 6px;
  1050. background-color: #f0f4f9;
  1051. border-collapse: collapse;
  1052. border: 1px solid #ffffff;
  1053. color: #697e91;
  1054. }
  1055. .CFBetter_modal .buttons{
  1056. display: flex;
  1057. padding-top: 15px;
  1058. }
  1059. .CFBetter_modal button {
  1060. display: inline-flex;
  1061. justify-content: center;
  1062. align-items: center;
  1063. line-height: 1;
  1064. white-space: nowrap;
  1065. cursor: pointer;
  1066. text-align: center;
  1067. box-sizing: border-box;
  1068. outline: none;
  1069. transition: .1s;
  1070. user-select: none;
  1071. vertical-align: middle;
  1072. -webkit-appearance: none;
  1073. height: 24px;
  1074. padding: 5px 11px;
  1075. margin-right: 15px;
  1076. font-size: 12px;
  1077. border-radius: 4px;
  1078. color: #ffffff;
  1079. background: #009688;
  1080. border-color: #009688;
  1081. border: none;
  1082. }
  1083. .CFBetter_modal button#cancelButton{
  1084. background-color:#4DB6AC;
  1085. }
  1086. .CFBetter_modal button:hover{
  1087. background-color:#4DB6AC;
  1088. }
  1089. .CFBetter_modal button#cancelButton:hover {
  1090. background-color: #80CBC4;
  1091. }
  1092. .CFBetter_modal .help-icon {
  1093. margin: 0px 8px 0px 0px;
  1094. height: 1em;
  1095. width: 1em;
  1096. line-height: 1em;
  1097. display: inline-flex;
  1098. justify-content: center;
  1099. align-items: center;
  1100. position: relative;
  1101. fill: currentColor;
  1102. font-size: inherit;
  1103. }
  1104. .CFBetter_modal p {
  1105. margin: 5px 0px;
  1106. }
  1107. /*更新检查*/
  1108. div#update_panel {
  1109. z-index: 200;
  1110. position: fixed;
  1111. top: 50%;
  1112. left: 50%;
  1113. width: 240px;
  1114. transform: translate(-50%, -50%);
  1115. box-shadow: 0px 0px 4px 0px #0000004d;
  1116. padding: 10px 20px 20px 20px;
  1117. color: #444242;
  1118. background-color: #f5f5f5;
  1119. border: 1px solid #848484;
  1120. border-radius: 8px;
  1121. }
  1122. div#update_panel #updating {
  1123. cursor: pointer;
  1124. display: inline-flex;
  1125. padding: 3px;
  1126. background-color: #1aa06d;
  1127. color: #ffffff;
  1128. font-size: 14px;
  1129. line-height: 1.5rem;
  1130. font-weight: 500;
  1131. justify-content: center;
  1132. width: 100%;
  1133. border-radius: 0.375rem;
  1134. border: none;
  1135. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  1136. }
  1137. div#update_panel #updating a {
  1138. text-decoration: none;
  1139. color: white;
  1140. display: flex;
  1141. position: inherit;
  1142. top: 0;
  1143. left: 0;
  1144. width: 100%;
  1145. height: 22px;
  1146. font-size: 14px;
  1147. justify-content: center;
  1148. align-items: center;
  1149. }
  1150. #skip_menu {
  1151. display: flex;
  1152. margin-top: 10px;
  1153. justify-content: flex-end;
  1154. align-items: center;
  1155. }
  1156. #skip_menu .help_tip {
  1157. margin-right: 5px;
  1158. margin-left: -5px;
  1159. }
  1160. #skip_menu .help-icon {
  1161. color: #f44336;
  1162. }
  1163. /* 配置管理 */
  1164. .embed-responsive {
  1165. height: max-content;
  1166. padding-bottom: 0px;
  1167. }
  1168. .config_bar {
  1169. height: 70px;
  1170. width: 100%;
  1171. display: flex;
  1172. justify-content: space-between;
  1173. }
  1174. li#add_button {
  1175. cursor: pointer;
  1176. height: 40px;
  1177. border: 1px dashed #BDBDBD;
  1178. border-radius: 8px;
  1179. background-color: #fcfbfb36;
  1180. color: #bdbdbd;
  1181. font-size: 14px;
  1182. align-items: center;
  1183. justify-content: center;
  1184. }
  1185. li#add_button:hover {
  1186. border: 1px dashed #03A9F4;
  1187. background-color: #d7f0fb8c;
  1188. color: #03A9F4;
  1189. }
  1190. div#config_bar_list {
  1191. display: flex;
  1192. width: 100%;
  1193. border: 1px solid #c5cae9;
  1194. border-radius: 8px;
  1195. background-color: #f0f8ff;
  1196. box-sizing: border-box;
  1197. }
  1198. div#config_bar_list input[type="radio"] {
  1199. appearance: none;
  1200. width: 0;
  1201. height: 0;
  1202. overflow: hidden;
  1203. }
  1204. div#config_bar_list input[type="radio"] {
  1205. margin: 0px;
  1206. }
  1207. div#config_bar_list input[type=radio]:focus {
  1208. outline: 0px;
  1209. }
  1210. label.config_bar_ul_li_text {
  1211. display: flex;
  1212. align-items: center;
  1213. justify-content: center;
  1214. max-width: 100%;
  1215. height: 40px;
  1216. overflow-x: auto;
  1217. font-size: 14px;
  1218. font-weight: 400;
  1219. margin: 0px 4px;
  1220. padding: 3px;
  1221. border: 1px solid #dedede;
  1222. border-radius: 10px;
  1223. box-shadow: 0px 2px 4px 0px rgba(0,0,0,.05);
  1224. box-sizing: border-box;
  1225. }
  1226. ul#config_bar_ul li button {
  1227. background-color: #e6e6e6;
  1228. color: #727378;
  1229. height: 23px;
  1230. font-size: 14px;
  1231. border-radius: 0.3rem;
  1232. padding: 1px 5px;
  1233. margin: 5px;
  1234. border: none;
  1235. box-shadow: 0 0 1px #0000004d;
  1236. }
  1237. ul#config_bar_ul {
  1238. display: flex;
  1239. align-items: center;
  1240. list-style-type: none;
  1241. padding-inline-start: 0px;
  1242. overflow-x: auto;
  1243. max-width: 100%;
  1244. margin: 0px;
  1245. }
  1246. ul#config_bar_ul li {
  1247. width: 80px;
  1248. display: grid;
  1249. margin: 4px 4px;
  1250. min-width: 100px;
  1251. box-sizing: border-box;
  1252. }
  1253. label.config_bar_ul_li_text:hover {
  1254. background-color: #eae4dc24;
  1255. }
  1256. input[type="radio"]:checked + .config_bar_ul_li_text {
  1257. background: #41b3e430;
  1258. border: 1px solid #5e7ce0;
  1259. color: #5e7ce0;
  1260. }
  1261. ul#config_bar_ul::-webkit-scrollbar {
  1262. width: 5px;
  1263. height: 5px;
  1264. }
  1265. ul#config_bar_ul::-webkit-scrollbar-thumb {
  1266. background-clip: padding-box;
  1267. background-color: #d7d9e4;
  1268. border-radius: 8px;
  1269. }
  1270. ul#config_bar_ul::-webkit-scrollbar-button:start:decrement {
  1271. width: 4px;
  1272. background-color: transparent;
  1273. }
  1274. ul#config_bar_ul::-webkit-scrollbar-button:end:increment {
  1275. width: 4px;
  1276. background-color: transparent;
  1277. }
  1278. ul#config_bar_ul::-webkit-scrollbar-track {
  1279. background-color: #f1f1f1;
  1280. border-radius: 5px;
  1281. }
  1282. label.config_bar_ul_li_text::-webkit-scrollbar {
  1283. width: 5px;
  1284. height: 7px;
  1285. background-color: #aaa;
  1286. }
  1287. label.config_bar_ul_li_text::-webkit-scrollbar-thumb {
  1288. background-clip: padding-box;
  1289. background-color: #d7d9e4;
  1290. }
  1291. label.config_bar_ul_li_text::-webkit-scrollbar-track {
  1292. background-color: #f1f1f1;
  1293. }
  1294. .config_bar_list_add_div {
  1295. display: flex;
  1296. height: 40px;
  1297. margin: 4px 2px;
  1298. }
  1299. /* 修改菜单 */
  1300. div#config_bar_menu {
  1301. z-index: 400;
  1302. position: absolute;
  1303. width: 60px;
  1304. background: #ffffff;
  1305. box-shadow: 1px 1px 4px 0px #0000004d;
  1306. border: 0px solid rgba(0,0,0,0.04);
  1307. border-radius: 4px;
  1308. padding: 8px 0;
  1309. }
  1310. div.config_bar_menu_item {
  1311. cursor: pointer;
  1312. padding: 2px 6px;
  1313. display: flex;
  1314. justify-content: center;
  1315. align-items: center;
  1316. height: 32px;
  1317. color: rgba(0,0,0,0.75);
  1318. font-size: 14px;
  1319. font-weight: 500;
  1320. box-shadow: inset 0px 0px 0px 0px #8bb2d9;
  1321. }
  1322. div#config_bar_menu_edit:hover {
  1323. background-color: #00aeec;
  1324. color: white;
  1325. }
  1326. div#config_bar_menu_delete:hover {
  1327. background-color: #FF5722;
  1328. color: white;
  1329. }
  1330. /* 配置页面 */
  1331. #config_edit_menu {
  1332. z-index: 300;
  1333. width: 450px;
  1334. }
  1335. /* 黑暗模式选项 */
  1336. .dark-mode-selection {
  1337. display: flex;
  1338. justify-content: center;
  1339. align-items: center;
  1340. max-width: 350px;
  1341. -webkit-user-select: none;
  1342. -moz-user-select: none;
  1343. -ms-user-select: none;
  1344. user-select: none;
  1345. }
  1346. .dark-mode-selection > * {
  1347. margin: 6px;
  1348. }
  1349. .dark-mode-selection .CFBetter_setting_menu_label_text {
  1350. border-radius: 8px;
  1351. }
  1352. /* 右键菜单 */
  1353. .CFBetter_contextmenu {
  1354. z-index: 500;
  1355. display: grid;
  1356. position: absolute;
  1357. background-color: #f0f4f9;
  1358. border-collapse: collapse;
  1359. color: #697e91;
  1360. font-family: var(--vp-font-family-base);
  1361. overflow: hidden;
  1362. box-sizing: content-box;
  1363. box-shadow: 0px 0px 0px 2px #eddbdb4d;
  1364. }
  1365. input[type="radio"]:checked+.CFBetter_contextmenu_label_text {
  1366. background: #41e49930;
  1367. border: 1px solid green;
  1368. color: green;
  1369. font-weight: 500;
  1370. }
  1371. .CFBetter_contextmenu_label_text {
  1372. display: flex;
  1373. border: 1px dashed #80cbc4;
  1374. height: 26px;
  1375. width: 100%;
  1376. color: gray;
  1377. font-size: 13px;
  1378. padding: 4px;
  1379. align-items: center;
  1380. -webkit-box-sizing: border-box;
  1381. -moz-box-sizing: border-box;
  1382. box-sizing: border-box;
  1383. }
  1384. .CFBetter_contextmenu_label_text:hover {
  1385. color: #F44336;
  1386. border: 1px dashed #009688;
  1387. background-color: #ffebcd;
  1388. }
  1389. /* RatingByClist */
  1390. .ratingBadges, html[data-theme=dark] button.ratingBadges{
  1391. font-weight: 700;
  1392. margin-top: 5px;
  1393. border-radius: 4px;
  1394. color: #ffffff00;
  1395. border: 1px solid #cccccc66;
  1396. }
  1397. /* 移动设备 */
  1398. @media (max-device-width: 450px) {
  1399. button.html2mdButton{
  1400. height: 2em;
  1401. font-size: 1.2em;
  1402. }
  1403. button.html2mdButton.CFBetter_setting{
  1404. height: 2.5em;
  1405. font-size: 1em;
  1406. }
  1407. .CFBetter_setting_menu{
  1408. width: 90%;
  1409. }
  1410. .CFBetter_setting_menu label, #darkMode_span, #loaded_span, .CFBetter_setting_menu_label_text,
  1411. .CFBetter_setting_sidebar li{
  1412. font-size: 1em;
  1413. }
  1414. .translate-problem-statement{
  1415. font-size: 1.2em;
  1416. }
  1417. .CFBetter_modal{
  1418. font-size: 1.5em;
  1419. }
  1420. .CFBetter_setting_list, .translate-problem-statement{
  1421. padding: 0.5em;
  1422. }
  1423. .CFBetter_setting_menu_label_text{
  1424. height: 2.5em;
  1425. padding: 0.5em;
  1426. }
  1427. #pagBar #jump-input, #pagBar #items-per-page, .CFBetter_modal button{
  1428. height: 2.5em;
  1429. font-size: 1em;
  1430. }
  1431. .translate-problem-statement p, .translate-problem-statement ul li{
  1432. line-height: 1.5em !important;
  1433. }
  1434. .CFBetter_contextmenu_label_text{
  1435. height: 3em;
  1436. font-size: 1em;
  1437. }
  1438. }
  1439. `);
  1440.  
  1441. // 工具
  1442. // 获取cookie
  1443. function getCookie(name) {
  1444. const cookies = document.cookie.split(";");
  1445. for (let i = 0; i < cookies.length; i++) {
  1446. const cookie = cookies[i].trim();
  1447. const [cookieName, cookieValue] = cookie.split("=");
  1448.  
  1449. if (cookieName === name) {
  1450. return decodeURIComponent(cookieValue);
  1451. }
  1452. }
  1453. return "";
  1454. }
  1455.  
  1456. // 防抖函数
  1457. function debounce(callback) {
  1458. let timer;
  1459. let immediateExecuted = false;
  1460. const delay = 500;
  1461. return function () {
  1462. clearTimeout(timer);
  1463. if (!immediateExecuted) { callback.call(this); immediateExecuted = true; }
  1464. timer = setTimeout(() => { immediateExecuted = false; }, delay);
  1465. };
  1466. }
  1467.  
  1468. // 为元素添加鼠标拖动
  1469. function addDraggable(element) {
  1470. let isDragging = false;
  1471. let initialX, initialY; // 元素的初始位置
  1472. let startX, startY, offsetX, offsetY; // 鼠标起始位置,移动偏移量
  1473. let isSpecialMouseDown = false; // 选取某些元素时不拖动
  1474.  
  1475. element.on('mousedown', function (e) {
  1476. var elem = $(this);
  1477. var elemOffset = elem.offset();
  1478. var centerX = elemOffset.left + elem.outerWidth() / 2;
  1479. var centerY = elemOffset.top + elem.outerHeight() / 2;
  1480. initialX = centerX - window.pageXOffset;
  1481. initialY = centerY - window.pageYOffset;
  1482.  
  1483. isDragging = true;
  1484. startX = e.clientX;
  1485. startY = e.clientY;
  1486.  
  1487. isSpecialMouseDown = $(e.target).is('label, p, input, textarea, span, select');
  1488. if (isSpecialMouseDown) return;
  1489. $('body').css('cursor', 'all-scroll');
  1490. });
  1491.  
  1492. $(document).on('mousemove', function (e) {
  1493. if (!isDragging) return;
  1494. // 不执行拖动操作
  1495. if ($(e.target).is('label, p, input, textarea, span') || isSpecialMouseDown && !$(e.target).is('input, textarea')) return;
  1496. e.preventDefault();
  1497. offsetX = e.clientX - startX;
  1498. offsetY = e.clientY - startY;
  1499. element.css({ top: initialY + offsetY + 'px', left: initialX + offsetX + 'px' });
  1500. });
  1501.  
  1502. $(document).on('mouseup', function () {
  1503. isDragging = false;
  1504. isSpecialMouseDown = false;
  1505. $('body').css('cursor', 'default');
  1506. });
  1507. }
  1508.  
  1509. // 更新检查
  1510. function checkScriptVersion() {
  1511. function compareVersions(version1 = "0", version2 = "0") {
  1512. const v1Array = String(version1).split(".");
  1513. const v2Array = String(version2).split(".");
  1514. const minLength = Math.min(v1Array.length, v2Array.length);
  1515. let result = 0;
  1516. for (let i = 0; i < minLength; i++) {
  1517. const curV1 = Number(v1Array[i]);
  1518. const curV2 = Number(v2Array[i]);
  1519. if (curV1 > curV2) {
  1520. result = 1;
  1521. break;
  1522. } else if (curV1 < curV2) {
  1523. result = -1;
  1524. break;
  1525. }
  1526. }
  1527. if (result === 0 && v1Array.length !== v2Array.length) {
  1528. const v1IsBigger = v1Array.length > v2Array.length;
  1529. const maxLenArray = v1IsBigger ? v1Array : v2Array;
  1530. for (let i = minLength; i < maxLenArray.length; i++) {
  1531. const curVersion = Number(maxLenArray[i]);
  1532. if (curVersion > 0) {
  1533. v1IsBigger ? result = 1 : result = -1;
  1534. break;
  1535. }
  1536. }
  1537. }
  1538. return result;
  1539. }
  1540.  
  1541. GM_xmlhttpRequest({
  1542. method: "GET",
  1543. url: "https://greasyfork.org/zh-CN/scripts/465777.json",
  1544. timeout: 10 * 1e3,
  1545. onload: function (response) {
  1546. const scriptData = JSON.parse(response.responseText);
  1547. const skipUpdate = getCookie("skipUpdate");
  1548.  
  1549. if (
  1550. scriptData.name === GM_info.script.name &&
  1551. compareVersions(scriptData.version, GM_info.script.version) === 1 &&
  1552. skipUpdate !== "true"
  1553. ) {
  1554. const styleElement = GM_addStyle(darkenPageStyle);
  1555. $("body").append(`
  1556. <div id='update_panel'>
  1557. <h3>${GM_info.script.name}有新版本!</h3>
  1558. <hr>
  1559. <div class='update_panel_menu'>
  1560. <span class ='tip'>版本信息:${GM_info.script.version} ${scriptData.version}</span>
  1561. </div>
  1562. <br>
  1563. <div id="skip_menu">
  1564. <div class="help_tip">
  1565. `+ helpCircleHTML + `
  1566. <div class="tip_text">
  1567. <p><b>更新遇到了问题?</b></p>
  1568. <p>由于 Greasyfork 平台的原因,当新版本刚发布时,点击 Greasyfork 上的更新按钮<u>可能</u>会出现<u>实际更新/安装的却是上一个版本</u>的情况</p>
  1569. <p>通常你只需要稍等几分钟,然后再次前往更新/安装即可</p>
  1570. <p>你也可以<u>点击下方按钮,在本次浏览器会话期间将不再提示更新</u></p>
  1571. <button id='skip_update' class='html2mdButton'>暂不更新</button>
  1572. </div>
  1573. </div>
  1574. <button id='updating'><a target="_blank" href="${scriptData.url}">更新</a></button>
  1575. </div>
  1576. </div>
  1577. `);
  1578.  
  1579. $("#skip_update").click(function () {
  1580. document.cookie = "skipUpdate=true; expires=session; path=/";
  1581. styleElement.remove();
  1582. $("#update_panel").remove();
  1583. });
  1584. }
  1585. }
  1586. });
  1587.  
  1588. };
  1589.  
  1590. // 汉化替换
  1591. function toZH_CN() {
  1592. if (!bottomZh_CN) return;
  1593. // 设置语言为zh
  1594. var htmlTag = document.getElementsByTagName("html")[0];
  1595. htmlTag.setAttribute("lang", "zh-CN");
  1596.  
  1597. // 文本节点遍历替换
  1598. function traverseTextNodes(node, rules) {
  1599. if (!node) return;
  1600. if (node.nodeType === Node.TEXT_NODE) {
  1601. rules.forEach(rule => {
  1602. const regex = new RegExp(rule.match, 'g');
  1603. node.textContent = node.textContent.replace(regex, rule.replace);
  1604. });
  1605. } else {
  1606. $(node).contents().each((_, child) => traverseTextNodes(child, rules));
  1607. }
  1608. }
  1609.  
  1610. // 严格
  1611. function strictTraverseTextNodes(node, rules) {
  1612. if (!node) return;
  1613. if (node.nodeType === Node.TEXT_NODE) {
  1614. const nodeText = node.textContent.trim();
  1615. rules.forEach(rule => {
  1616. if (nodeText === rule.match) {
  1617. node.textContent = rule.replace;
  1618. }
  1619. });
  1620. } else {
  1621. $(node).contents().each((_, child) => strictTraverseTextNodes(child, rules));
  1622. }
  1623. }
  1624.  
  1625. const rules1 = [
  1626. { match: 'Virtual participation', replace: '参加虚拟重现赛' },
  1627. { match: 'Enter', replace: '进入' },
  1628. { match: 'Current standings', replace: '当前榜单' },
  1629. { match: 'Final standings', replace: '最终榜单' },
  1630. { match: 'Preliminary results', replace: '初步结果' },
  1631. { match: 'open hacking:', replace: '公开黑客攻击中' },
  1632. { match: 'School/University/City/Region Championship', replace: '学校/大学/城市/区域比赛' },
  1633. { match: 'Official School Contest', replace: '学校官方比赛' },
  1634. { match: 'Training Contest', replace: '训练赛' },
  1635. { match: 'Training Camp Contest', replace: '训练营比赛' },
  1636. { match: 'Official ICPC Contest', replace: 'ICPC官方比赛' },
  1637. { match: 'Official International Personal Contest', replace: '官方国际个人赛' },
  1638. { match: 'China', replace: '中国' },
  1639. { match: 'Statements', replace: '题目描述' },
  1640. { match: 'in Chinese', replace: '中文' },
  1641. { match: 'Trainings', replace: '训练' },
  1642. { match: 'Prepared by', replace: '编写人' },
  1643. { match: 'Current or upcoming contests', replace: '当前或即将举行的比赛' },
  1644. { match: 'Past contests', replace: '过去的比赛' },
  1645. { match: 'Exclusions', replace: '排除' },
  1646. { match: 'Before start', replace: '距比赛开始还有' },
  1647. { match: 'Before registration', replace: '距报名开始还有' },
  1648. { match: 'Until closing ', replace: '距报名结束还有' },
  1649. { match: 'Before extra registration', replace: '额外报名还未开始' },
  1650. { match: 'Register »', replace: '报名 »' },
  1651. { match: 'Registration completed', replace: '已报名' },
  1652. { match: 'Registration closed', replace: '报名已结束' },
  1653. { match: 'Problems', replace: '问题集' },
  1654. { match: 'Questions about problems', replace: '关于问题的提问' },
  1655. { match: 'Contest status', replace: '比赛状态' },
  1656. ];
  1657. traverseTextNodes($('.datatable'), rules1);
  1658.  
  1659. const rules2 = [
  1660. { match: 'Home', replace: '主页' },
  1661. { match: 'Top', replace: '热门' },
  1662. { match: 'Catalog', replace: '指南目录' },
  1663. { match: 'Contests', replace: '比赛' },
  1664. { match: 'Gym', replace: '训练营' },
  1665. { match: 'Problemset', replace: '题单' },
  1666. { match: 'Groups', replace: '团体' },
  1667. { match: 'Rating', replace: 'Rating(评级)排行榜' },
  1668. { match: 'Edu', replace: '培训' },
  1669. { match: 'Calendar', replace: '日历' },
  1670. { match: 'Help', replace: '帮助' }
  1671. ];
  1672. traverseTextNodes($('.menu-list.main-menu-list'), rules2);
  1673.  
  1674. const rules3 = [
  1675. { match: 'Settings', replace: '设置' },
  1676. { match: 'Blog', replace: '博客' },
  1677. { match: 'Teams', replace: '队伍' },
  1678. { match: 'Submissions', replace: '提交' },
  1679. { match: 'Favourites', replace: '收藏' },
  1680. { match: 'Talks', replace: '私信' },
  1681. { match: 'Contests', replace: '比赛' },
  1682. ];
  1683. traverseTextNodes($('.nav-links'), rules3);
  1684.  
  1685. const rules4 = [
  1686. { match: 'Before contest', replace: '即将进行的比赛' },
  1687. { match: 'Contest is running', replace: '比赛进行中' },
  1688. ];
  1689. traverseTextNodes($('.contest-state-phase'), rules4);
  1690.  
  1691. const rules5 = [
  1692. { match: 'has extra registration', replace: '有额外的报名时期' },
  1693. { 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分钟。' },
  1694. ];
  1695. traverseTextNodes($('.notice'), rules5);
  1696.  
  1697. const rules6 = [
  1698. { match: 'Contribution', replace: '贡献' },
  1699. ];
  1700. traverseTextNodes($('.propertyLinks'), rules6);
  1701.  
  1702. const rules7 = [
  1703. { match: 'Contest history', replace: '比赛历史' },
  1704. ];
  1705. traverseTextNodes($('.contests-table'), rules7);
  1706.  
  1707. const rules8 = [
  1708. { match: 'Register now', replace: '现在报名' },
  1709. { match: 'No tag edit access', replace: '没有标签编辑权限' },
  1710. { match: 'Language:', replace: '语言:' },
  1711. { match: 'Choose file:', replace: '选择文件:' },
  1712. ];
  1713. traverseTextNodes($('.roundbox.sidebox.borderTopRound '), rules8);
  1714.  
  1715. const rules9 = [
  1716. { match: 'Add to exclusions', replace: '添加到排除列表' },
  1717. ];
  1718. traverseTextNodes($('.icon-eye-close.icon-large'), rules9);
  1719.  
  1720. const rules10 = [
  1721. { match: 'Add to exclusions for gym contests filter', replace: '添加训练营过滤器的排除项' },
  1722. ];
  1723. traverseTextNodes($("._ContestFilterExclusionsManageFrame_addExclusionLink"), rules10);
  1724.  
  1725. const rules11 = [
  1726. { match: 'Announcement', replace: '公告' },
  1727. { match: 'Statements', replace: '统计报表' },
  1728. { match: 'Tutorial', replace: '题解' },
  1729. ];
  1730. traverseTextNodes($('.roundbox.sidebox.sidebar-menu.borderTopRound '), rules11);
  1731.  
  1732. const rules12 = [
  1733. { match: 'Problems', replace: '问题' },
  1734. { match: 'Submit Code', replace: '提交代码' },
  1735. { match: 'My Submissions', replace: '我的提交' },
  1736. { match: 'Status', replace: '状态' },
  1737. { match: 'Standings', replace: '榜单' },
  1738. { match: 'Custom Invocation', replace: '自定义调试' },
  1739. { match: 'Common standings', replace: '全部排行' },
  1740. { match: 'Friends standings', replace: '只看朋友' },
  1741. { match: 'Submit', replace: '提交' },
  1742. { match: 'Hacks', replace: '黑客' },
  1743. { match: 'Room', replace: '房间' },
  1744. { match: 'Custom test', replace: '自定义测试' },
  1745. { match: 'Blog', replace: '博客' },
  1746. { match: 'Teams', replace: '队伍' },
  1747. { match: 'Submissions', replace: '提交记录' },
  1748. { match: 'Groups', replace: '团体' },
  1749. { match: 'Favourites', replace: '收藏' },
  1750. { match: 'Contests', replace: '比赛' },
  1751. { match: 'Members', replace: '成员' },
  1752. { match: '问题etting', replace: '参与编写的问题' },
  1753. { match: 'Streams', replace: '直播' },
  1754. { match: 'Gym', replace: '训练营' },
  1755. { match: 'Mashups', replace: '组合混搭' },
  1756. { match: 'Posts', replace: '帖子' },
  1757. { match: 'Comments', replace: '回复' },
  1758. { match: 'Main', replace: '主要的' },
  1759. { match: 'Settings', replace: '设置' },
  1760. { match: 'Lists', replace: '列表' },
  1761. { match: 'General', replace: '基本' },
  1762. { match: 'Sidebar', replace: '侧边栏' },
  1763. { match: 'Social', replace: '社会信息' },
  1764. { match: 'Address', replace: '地址' },
  1765. { match: 'Wallets', replace: '钱包' },
  1766. ];
  1767. traverseTextNodes($('.second-level-menu'), rules12);
  1768. if (is_mSite) {
  1769. traverseTextNodes($('nav'), rules12);
  1770. }
  1771.  
  1772. const rules13 = [
  1773. { match: 'Expand', replace: '展开' }
  1774. ];
  1775. traverseTextNodes($('.topic-toggle-collapse'), rules13);
  1776.  
  1777. const rules14 = [
  1778. { match: 'Full text and comments', replace: '阅读全文/评论' }
  1779. ];
  1780. traverseTextNodes($('.topic-read-more'), rules14);
  1781.  
  1782. const rules15 = [
  1783. { match: 'Switch off editor', replace: '关闭编辑器语法高亮' }
  1784. ];
  1785. traverseTextNodes($('.toggleEditorCheckboxLabel'), rules15);
  1786.  
  1787. const rules16 = [
  1788. { match: 'Registration for the contest', replace: '比赛报名' }
  1789. ];
  1790. traverseTextNodes($('.submit'), rules16);
  1791.  
  1792. const rules17 = [
  1793. { match: 'Difficulty:', replace: '难度:' },
  1794. ];
  1795. traverseTextNodes($('._FilterByTagsFrame_difficulty'), rules17);
  1796.  
  1797. const rules18 = [
  1798. { match: 'Add tag', replace: '添加标签' }
  1799. ];
  1800. traverseTextNodes($('._FilterByTagsFrame_addTagLink'), rules18);
  1801.  
  1802. const rules19 = [
  1803. { match: 'Rating changes for last rounds are temporarily rolled back. They will be returned soon.', replace: '上一轮的评级变化暂时回滚。它们将很快恢复。' },
  1804. { match: 'Reminder: in case of any technical issues, you can use the lightweight website', replace: '提醒:如果出现任何技术问题,您可以使用轻量网站' },
  1805. { match: 'Please subscribe to the official Codeforces channel in Telegram via the link ', replace: '请通过链接订阅Codeforces的官方Telegram频道' }
  1806. ];
  1807. traverseTextNodes($('.alert'), rules19);
  1808.  
  1809. const rules20 = [
  1810. { match: 'Enter', replace: '登录' },
  1811. { match: 'Register', replace: '注册' },
  1812. { match: 'Contest rating', replace: '测试 rating' },
  1813. { match: 'Logout', replace: '退出登录' }
  1814. ];
  1815. traverseTextNodes($('.lang-chooser'), rules20);
  1816.  
  1817. const rules21 = [
  1818. { match: 'Change photo', replace: '更换图片' },
  1819. { match: 'Contest rating', replace: '比赛Rating' },
  1820. { match: 'Contribution', replace: '贡献' },
  1821. { match: 'My friends', replace: '我的好友' },
  1822. { match: 'Change settings', replace: '改变设置' },
  1823. { match: 'Last visit', replace: '最后访问' },
  1824. { match: 'Registered', replace: '注册于' },
  1825. { match: 'Blog entries', replace: '博客条目' },
  1826. { match: 'comments', replace: '评论' },
  1827. { match: 'Write new entry', replace: '编写新条目' },
  1828. { match: 'View my talks', replace: '查看我的私信' },
  1829. { match: 'Talks', replace: '私信' },
  1830. { match: 'Send message', replace: '发送消息' },
  1831. ];
  1832. traverseTextNodes($('.userbox'), rules21);
  1833.  
  1834. const rules22 = [
  1835. { match: 'Reset', replace: '重置' },
  1836. ];
  1837. traverseTextNodes($('#vote-reset-filterDifficultyLowerBorder'), rules22);
  1838. traverseTextNodes($('#vote-reset-filterDifficultyUpperBorder'), rules22);
  1839.  
  1840. const rules23 = [
  1841. { match: 'The problem statement has recently been changed.', replace: '题目描述最近已被更改。' },
  1842. { match: 'View the changes.', replace: '查看更改' },
  1843. ];
  1844. traverseTextNodes($('.alert.alert-info'), rules23);
  1845.  
  1846. const rules24 = [
  1847. { match: 'Fill in the form to login into Codeforces.', replace: '填写表单以登录到Codeforces。' },
  1848. { match: 'You can use', replace: '你也可以使用' },
  1849. { match: 'as an alternative way to enter.', replace: '登录' },
  1850. ];
  1851. traverseTextNodes($('.enterPage'), rules24);
  1852.  
  1853. const rules25 = [
  1854. { match: '\\* To view the complete list, click ', replace: '* 要查看完整列表,请点击' },
  1855. ];
  1856. traverseTextNodes($('.notice.small'), rules25);
  1857.  
  1858. const rules26 = [
  1859. { match: 'Contest type:', replace: '比赛类型:' },
  1860. { match: 'Rated:', replace: '已评级:' },
  1861. { match: 'Tried:', replace: '已尝试' },
  1862. { match: 'Substring:', replace: '关键字' },
  1863. ];
  1864. traverseTextNodes($('.setting-name'), rules26);
  1865.  
  1866. const rules27 = [
  1867. { match: 'Sort by:', replace: '排序依据:' },
  1868. { match: 'relevance', replace: '相关' },
  1869. { match: 'popularity', replace: '热度' },
  1870. { match: 'time', replace: '时间' },
  1871. ];
  1872. traverseTextNodes($('.by-form'), rules27);
  1873.  
  1874. // 元素选择替换
  1875. // 侧栏titled汉化
  1876. (function () {
  1877. var translations = {
  1878. "Pay attention": "→ 注意",
  1879. "Top rated": "→ 评级排行",
  1880. "Top contributors": "→ 贡献者排行",
  1881. "Find user": "→ 查找用户",
  1882. "Recent actions": "→ 最新动态",
  1883. "Training filter": "→ 过滤筛选",
  1884. "Find training": "→ 搜索比赛/问题",
  1885. "Virtual participation": "→ 什么是虚拟参赛",
  1886. "Contest materials": "→ 比赛相关资料",
  1887. "Settings": "→ 设置",
  1888. "Create Mashup Contest": "→ 克隆比赛到组合混搭",
  1889. "Clone Contest to Mashup": "→ 克隆比赛到组合混搭",
  1890. "Create Mashup Contest": "→ 创建混搭比赛",
  1891. "Submit": "→ 提交",
  1892. "Practice": "→ 练习",
  1893. "Problem tags": "→ 问题标签",
  1894. "Filter Problems": "→ 过滤问题",
  1895. "Attention": "→ 注意",
  1896. "Past contests filter": "→ 过去的比赛筛选",
  1897. "About Contest": "→ 关于比赛",
  1898. "Last submissions": "→ 提交历史",
  1899. "Streams": "→ 直播",
  1900. "Coach rights": "→ 教练权限",
  1901. "Advices to fill address": "→ 填写地址的建议",
  1902. "Hacks filter": "→ 黑客过滤器",
  1903. "Score table": "→ 评分表",
  1904. "Contests": "→ 比赛",
  1905. "History": "→ 编辑历史",
  1906. "Login into Codeforces": "登录 Codeforces",
  1907. };
  1908.  
  1909. $(".caption.titled").each(function () {
  1910. var tag = $(this).text();
  1911. for (var property in translations) {
  1912. if (tag.match(property)) {
  1913. $(this).addClass(property);
  1914. $(this).text(translations[property]);
  1915. break;
  1916. }
  1917. }
  1918. });
  1919. })();
  1920. // 题目Tag汉化
  1921. (function () {
  1922. var parentElement = $('._FilterByTagsFrame_addTagLabel');
  1923. var selectElement = parentElement.find('select');
  1924. var translations = {
  1925. "*combine tags by OR": "*按逻辑或组合我选择的标签",
  1926. "combine-tags-by-or": "*按逻辑或组合我选择的标签(combine-tags-by-or)",
  1927. "2-sat": "二分图可满足性问题(2-sat)",
  1928. "binary search": "二分搜索(binary search)",
  1929. "bitmasks": "位掩码(bitmasks)",
  1930. "brute force": "暴力枚举(brute force)",
  1931. "chinese remainder theorem": "中国剩余定理(chinese remainder theorem)",
  1932. "combinatorics": "组合数学(combinatorics)",
  1933. "constructive algorithms": "构造算法(constructive algorithms)",
  1934. "data structures": "数据结构(data structures)",
  1935. "dfs and similar": "深度优先搜索及其变种(dfs and similar)",
  1936. "divide and conquer": "分治算法(divide and conquer)",
  1937. "dp": "动态规划(dp)",
  1938. "dsu": "并查集(dsu)",
  1939. "expression parsing": "表达式解析(expression parsing)",
  1940. "fft": "快速傅里叶变换(fft)",
  1941. "flows": "流(flows)",
  1942. "games": "博弈论(games)",
  1943. "geometry": "计算几何(geometry)",
  1944. "graph matchings": "图匹配(graph matchings)",
  1945. "graphs": "图论(graphs)",
  1946. "greedy": "贪心策略(greedy)",
  1947. "hashing": "哈希表(hashing)",
  1948. "implementation": "实现问题,编程技巧,模拟(implementation)",
  1949. "interactive": "交互性问题(interactive)",
  1950. "math": "数学(math)",
  1951. "matrices": "矩阵(matrices)",
  1952. "meet-in-the-middle": "meet-in-the-middle算法(meet-in-the-middle)",
  1953. "number theory": "数论(number theory)",
  1954. "probabilities": "概率论(probabilities)",
  1955. "schedules": "调度算法(schedules)",
  1956. "shortest paths": "最短路算法(shortest paths)",
  1957. "sortings": "排序算法(sortings)",
  1958. "string suffix structures": "字符串后缀结构(string suffix structures)",
  1959. "strings": "字符串处理(strings)",
  1960. "ternary search": "三分搜索(ternary search)",
  1961. "trees": "树形结构(trees)",
  1962. "two pointers": "双指针算法(two pointers)"
  1963. };
  1964. selectElement.find("option").each(function () {
  1965. var optionValue = $(this).val();
  1966. if (translations[optionValue]) {
  1967. $(this).text(translations[optionValue]);
  1968. }
  1969. });
  1970. $("._FilterByTagsFrame_tagBoxCaption").each(function () {
  1971. var tag = $(this).text();
  1972. if (tag in translations) {
  1973. $(this).text(translations[tag]);
  1974. }
  1975. });
  1976. $(".notice").each(function () {
  1977. var tag = $(this).text();
  1978. if (tag in translations) {
  1979. $(this).text(translations[tag]);
  1980. }
  1981. });
  1982. $(".tag-box").each(function () {
  1983. var tag = $(this).text();
  1984. for (var property in translations) {
  1985. property = property.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
  1986. if (tag.match(property)) {
  1987. $(this).text(translations[property]);
  1988. break;
  1989. }
  1990. }
  1991. });
  1992. })();
  1993. // 题目过滤器选项汉化
  1994. (function () {
  1995. var parentElement = $('#gym-filter-form');
  1996. var selectElement = parentElement.find('div');
  1997. var translations = {
  1998. "Contest type:": "比赛类型:",
  1999. "ICPC region:": "ICPC地区:",
  2000. "Contest format:": "比赛形式:",
  2001. "Order by:": "排序方式:",
  2002. "Secondary order by:": "次要排序方式:",
  2003. "Hide, if participated:": "隐藏我参加过的:",
  2004. };
  2005. selectElement.find("label").each(function () {
  2006. var optionValue = $(this).text();
  2007. if (translations[optionValue]) {
  2008. $(this).text(translations[optionValue]);
  2009. }
  2010. });
  2011. translations = {
  2012. "Season:": "时间范围(年度)",
  2013. "Duration, hours:": "持续时间(小时):",
  2014. "Difficulty:": "难度:"
  2015. };
  2016. selectElement.each(function () {
  2017. var optionValue = $(this).text();
  2018. if (translations[optionValue]) {
  2019. $(this).text(translations[optionValue]);
  2020. }
  2021. });
  2022. })();
  2023. (function () {
  2024. var parentElement = $('.setting-value');
  2025. var selectElement = parentElement.find('select');
  2026. var translations = {
  2027. "Official ACM-ICPC Contest": "ICPC官方比赛",
  2028. "Official School Contest": "学校官方比赛",
  2029. "Opencup Contest": "Opencup比赛",
  2030. "School/University/City/Region Championship": "学校/大学/城市/地区锦标赛",
  2031. "Training Camp Contest": "训练营比赛",
  2032. "Official International Personal Contest": "官方国际个人赛",
  2033. "Training Contest": "训练比赛",
  2034. "ID_ASC": "创建时间(升序)",
  2035. "ID_DESC": "创建时间(降序)",
  2036. "RATING_ASC": "评分(升序)",
  2037. "RATING_DESC": "评分(降序)",
  2038. "DIFFICULTY_ASC": "难度(升序)",
  2039. "DIFFICULTY_DESC": "难度(降序)",
  2040. "START_TIME_ASC": "开始时间(升序)",
  2041. "START_TIME_DESC": "开始时间(降序)",
  2042. "DURATION_ASC": "持续时间(升序)",
  2043. "DURATION_DESC": "持续时间(降序)",
  2044. "POPULARITY_ASC": "热度(升序)",
  2045. "POPULARITY_DESC": "热度(降序)",
  2046. "UPDATE_TIME_ASC": "更新时间(升序)",
  2047. "UPDATE_TIME_DESC": "更新时间(降序)"
  2048. };
  2049. selectElement.find("option").each(function () {
  2050. var optionValue = $(this).val();
  2051. if (translations[optionValue]) {
  2052. $(this).text(translations[optionValue]);
  2053. }
  2054. });
  2055. parentElement = $('.setting-last-value');
  2056. selectElement = parentElement.find('select');
  2057. selectElement.find("option").each(function () {
  2058. var optionValue = $(this).val();
  2059. if (translations[optionValue]) {
  2060. $(this).text(translations[optionValue]);
  2061. }
  2062. });
  2063. })();
  2064. // 比赛过滤器选项汉化
  2065. (function () {
  2066. var parentElement = $('.options');
  2067. var selectElement = parentElement.find('li');
  2068. var translations = {
  2069. "Educational": "教育性",
  2070. "Global": "全球",
  2071. "VK Cup": "VK杯",
  2072. "Long Rounds": "长期回合",
  2073. "April Fools": "愚人节",
  2074. "Team Contests": "团队比赛",
  2075. "ICPC Scoring": "ICPC计分",
  2076. "Doesn't matter": "----",
  2077. "Any": "所有",
  2078. "Yes": "是",
  2079. "No": "否",
  2080. "No submission(s)": "无提交",
  2081. "Have submission(s)": "有提交",
  2082. "No solved problem(s)": "无解决问题",
  2083. "Have solved problem(s)": "有解决问题"
  2084. };
  2085. selectElement.find('label').each(function () {
  2086. var optionValue = $(this).text();
  2087. if (translations[optionValue]) {
  2088. $(this).text(translations[optionValue]);
  2089. }
  2090. });
  2091. $('.CaptionCont').find('span').each(function () {
  2092. var optionValue = $(this).text();
  2093. if (translations[optionValue]) {
  2094. $(this).text(translations[optionValue]);
  2095. }
  2096. });
  2097. })();
  2098. // 右侧sidebox通用汉化
  2099. (function () {
  2100. var parentElement = $('.sidebox');
  2101. var selectElement = parentElement.find('div');
  2102. var translations = {
  2103. "Show tags for unsolved problems": "显示未解决问题的标签",
  2104. "Hide solved problems": "隐藏已解决的问题",
  2105. };
  2106. selectElement.find("label").each(function () {
  2107. var optionValue = $(this).text();
  2108. if (translations[optionValue]) {
  2109. $(this).text(translations[optionValue]);
  2110. }
  2111. });
  2112. })();
  2113. // 表单字段名汉化
  2114. (function () {
  2115. var translations = {
  2116. "Problem:": "题目:",
  2117. "Language:": "语言:",
  2118. "Source code:": "源代码:",
  2119. "Or choose file:": "或者选择文件:",
  2120. "Choose file:": "选择文件:",
  2121. "Notice:": "注意:",
  2122. "virtual participation:": "虚拟参与:",
  2123. "Registration for the contest:": "比赛报名:",
  2124. "Take part:": "参与:",
  2125. "as individual participant:": "作为个人参与者:",
  2126. "as a team member:": "作为团队成员:",
  2127. "Virtual start time:": "虚拟开始时间:",
  2128. "Complete problemset:": "完整的问题集:",
  2129. "First name (English)": "名字(英文)",
  2130. "Last name (English)": "姓氏(英文)",
  2131. "First name (Native)": "名字(本地语言)",
  2132. "Last name (Native)": "姓氏(本地语言)",
  2133. "Birth date": "出生日期",
  2134. "Country": "国家",
  2135. "City": "城市",
  2136. "Organization": "组织",
  2137. "Handle/Email": "账号/邮箱",
  2138. "Password": "密码",
  2139. };
  2140. $(".field-name").each(function () {
  2141. var optionValue = $(this).text();
  2142. if (translations[optionValue]) {
  2143. $(this).text(translations[optionValue]);
  2144. }
  2145. });
  2146. })();
  2147. (function () {
  2148. var translations = {
  2149. "Terms of agreement:": "协议条款:",
  2150. "Choose team:": "选择团队:"
  2151. };
  2152. $(".field-name label").each(function () {
  2153. var optionValue = $(this).text();
  2154. if (translations[optionValue]) {
  2155. $(this).text(translations[optionValue]);
  2156. }
  2157. });
  2158. })();
  2159. (function () {
  2160. var translations = {
  2161. "Hide sidebar block \"Find user\"": "隐藏侧边栏块“查找用户”",
  2162. "Hide sidebar block \"Current user\"": "隐藏侧边栏块“当前用户”",
  2163. "Hide sidebar block \"Recent аctions\"": "隐藏侧边栏块“最新动态”",
  2164. "Hide sidebar block \"Favourite groups\"": "隐藏侧边栏块“收藏组”",
  2165. "Hide sidebar block \"Top contributors\"": "隐藏侧边栏块“贡献者排行”",
  2166. "Hide sidebar block \"Top rated\"": "隐藏侧边栏块“评级排行”",
  2167. "Hide sidebar block \"Streams\"": "隐藏侧边栏块“直播”",
  2168. "Old password": "旧密码",
  2169. "New password": "新密码",
  2170. "Confirm new password": "确认新密码",
  2171. "Contest email notification": "比赛邮件通知",
  2172. "Send email on new user talk": "在有新用户对话时发送电子邮件",
  2173. "Send email on new comment": "在有新评论时发送电子邮件",
  2174. "Hide contact information": "隐藏联系人信息",
  2175. "Remember me by Gmail, Facebook and etc": "通过 Gmail、Facebook 等记住我",
  2176. "Show tags for unsolved problems": "显示未解决问题的标签",
  2177. "Hide solved problems from problemset": "从问题集中隐藏已解决的问题",
  2178. "Hide low rated blogs": "隐藏评级较低的博客",
  2179. "Offer to publish great rating rises": "提供展示Rating显著提升的机会",
  2180. "Enforce https": "强制 HTTPS",
  2181. "Show private activity in the profile": "在个人资料中显示私人活动",
  2182. "Show diagnostics": "显示诊断信息"
  2183. };
  2184. $(".field-name").each(function () {
  2185. var tag = $(this).text();
  2186. for (var property in translations) {
  2187. property = property.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
  2188. if (tag.match(property)) {
  2189. $(this).text(translations[property]);
  2190. break;
  2191. }
  2192. }
  2193. });
  2194. })();
  2195. (function () {
  2196. var translations = {
  2197. "Postal/zip code": "邮政编码/邮编",
  2198. "Country (English)": "国家(英文)",
  2199. "State (English)": "州/省份(英文)",
  2200. "City (English)": "城市(英文)",
  2201. "Address (English)": "地址(英文)",
  2202. "Recipient (English)": "收件人姓名(英文)",
  2203. "Country (Native)": "国家(本地语言)",
  2204. "State (Native)": "州/省份(本地语言)",
  2205. "City (Native)": "城市(本地语言)",
  2206. "Address (Native)": "地址(本地语言)",
  2207. "Recipient (Native)": "收件人姓名(本地语言)",
  2208. "Phone": "电话",
  2209. "TON Wallet:": "TON 钱包:",
  2210. "Secret Code:": "验证码:"
  2211. };
  2212. $("td.field-name label").each(function () {
  2213. var optionValue = $(this).text();
  2214. if (translations[optionValue]) {
  2215. $(this).text(translations[optionValue]);
  2216. }
  2217. });
  2218. })();
  2219.  
  2220. // 按钮汉化input[type="submit"]
  2221. (function () {
  2222. var translations = {
  2223. "Register for virtual participation": "报名虚拟参赛",
  2224. "Register for practice": "登录以开始练习",
  2225. "Apply": "应用",
  2226. "Register": "报名",
  2227. "Login": "登录",
  2228. "Run": "运行",
  2229. "Start virtual contest": "开始虚拟参赛",
  2230. "Clone Contest": "克隆比赛",
  2231. "Submit": "提交",
  2232. "Save changes": "保存设置",
  2233. "Filter": "过滤",
  2234. "Find": "查找",
  2235. "Create Mashup Contest": "创建混搭比赛"
  2236. };
  2237. $('input[type="submit"]').each(function () {
  2238. var optionValue = $(this).val();
  2239. if (translations[optionValue]) {
  2240. $(this).val(translations[optionValue]);
  2241. }
  2242. });
  2243. })();
  2244. (function () {
  2245. var translations = {
  2246. "Reset": "重置",
  2247. };
  2248. $('input[type="button"]').each(function () {
  2249. var optionValue = $(this).val();
  2250. if (translations[optionValue]) {
  2251. $(this).val(translations[optionValue]);
  2252. }
  2253. });
  2254. })();
  2255.  
  2256. // 选项汉化input[type="radio"]
  2257. (function () {
  2258. var translations = {
  2259. "as individual participant": "个人",
  2260. "as a team member": "作为一个团队成员",
  2261. };
  2262. $('input[type="radio"]').each(function () {
  2263. var tag = $(this).parent().contents().filter(function () {
  2264. return this.nodeType === Node.TEXT_NODE;
  2265. });
  2266. for (var i = 0; i < tag.length; i++) {
  2267. var text = tag[i].textContent.trim();
  2268. if (translations.hasOwnProperty(text)) {
  2269. $(this).addClass(text);
  2270. tag[i].replaceWith(translations[text]);
  2271. break;
  2272. }
  2273. }
  2274. });
  2275. })();
  2276.  
  2277.  
  2278. // 杂项
  2279. (function () {
  2280. var translations = {
  2281. "(standard input\/output)": "标准输入/输出",
  2282. };
  2283. $("div.notice").each(function () {
  2284. var tag = $(this).children().eq(0).text();
  2285. for (var property in translations) {
  2286. if (tag.match(property)) {
  2287. $(this).children().eq(0).text(translations[property]);
  2288. break;
  2289. }
  2290. }
  2291. });
  2292. })();
  2293. (function () {
  2294. var translations = {
  2295. "Ask a question": "提一个问题",
  2296. };
  2297. $(".ask-question-link").each(function () {
  2298. var optionValue = $(this).text();
  2299. if (translations[optionValue]) {
  2300. $(this).text(translations[optionValue]);
  2301. }
  2302. });
  2303. })();
  2304.  
  2305. // 轻量站特殊
  2306. if (is_mSite) {
  2307. (function () {
  2308. var translations = {
  2309. "Announcements": "公告",
  2310. "Submissions": "提交记录",
  2311. "Contests": "比赛",
  2312. };
  2313. $(".caption").each(function () {
  2314. var optionValue = $(this).text();
  2315. if (translations[optionValue]) {
  2316. $(this).text(translations[optionValue]);
  2317. }
  2318. });
  2319. })();
  2320. }
  2321. };
  2322.  
  2323. // 配置管理函数
  2324. function setupConfigManagement(element, tempConfig, structure, configHTML, checkable) {
  2325. let counter = 0;
  2326. createControlBar();
  2327. createContextMenu();
  2328.  
  2329. // 键值对校验
  2330. function valiKeyValue(value) {
  2331. const keyValuePairs = value.split('\n');
  2332. const regex = /^[a-zA-Z0-9_-]+\s*:\s*[a-zA-Z0-9_-]+$/;
  2333. for (let i = 0; i < keyValuePairs.length; i++) {
  2334. if (!regex.test(keyValuePairs[i])) {
  2335. return false;
  2336. }
  2337. }
  2338. return true;
  2339. }
  2340.  
  2341. // 新增数据
  2342. function onAdd() {
  2343. const styleElement = createWindow();
  2344.  
  2345. const settingMenu = $("#config_edit_menu");
  2346. settingMenu.on("click", "#save", () => {
  2347. const config = {};
  2348. let allFieldsValid = true;
  2349. for (const key in structure) {
  2350. let value = $(key).val();
  2351. if (value || $(key).attr('require') === 'false') {
  2352. config[structure[key]] = $(key).val();
  2353. $(key).removeClass('is_null');
  2354. } else {
  2355. $(key).addClass('is_null');
  2356. allFieldsValid = false;
  2357. }
  2358. }
  2359.  
  2360. // 校验提示
  2361. for (let i = 0, len = checkable.length; i < len; i++) {
  2362. let value = $(checkable[i]).val();
  2363. if (value && !valiKeyValue(value)) {
  2364. if (!$(checkable[i]).prev('span.text-error').length) {
  2365. $(checkable[i]).before('<span class="text-error" style="color: red;">格式不符或存在非法字符</span>');
  2366. }
  2367. allFieldsValid = false;
  2368. } else {
  2369. $(checkable[i]).prev('span.text-error').remove();
  2370. }
  2371. }
  2372.  
  2373. if (!allFieldsValid) return;
  2374. tempConfig.configurations.push(config);
  2375.  
  2376. const list = $("#config_bar_ul");
  2377. createListItemElement(config[structure['#note']]).insertBefore($('#add_button'));
  2378.  
  2379. settingMenu.remove();
  2380. $(styleElement).remove();
  2381. });
  2382.  
  2383. settingMenu.on("click", ".btn-close", () => {
  2384. settingMenu.remove();
  2385. $(styleElement).remove();
  2386. });
  2387. }
  2388.  
  2389. // 编辑数据
  2390. function onEdit() {
  2391. const menu = $("#config_bar_menu");
  2392. menu.css({ display: "none" });
  2393.  
  2394. const list = $("#config_bar_ul");
  2395. const index = Array.from(list.children()).indexOf(this);
  2396.  
  2397. const styleElement = createWindow();
  2398.  
  2399. const settingMenu = $("#config_edit_menu");
  2400. const configAtIndex = tempConfig.configurations[index];
  2401.  
  2402. if (configAtIndex) {
  2403. for (const key in structure) {
  2404. $(key).val(configAtIndex[structure[key]]);
  2405. }
  2406. }
  2407.  
  2408. settingMenu.on("click", "#save", () => {
  2409. const config = {};
  2410. let allFieldsValid = true;
  2411. for (const key in structure) {
  2412. let value = $(key).val();
  2413. if (value || $(key).attr('require') === 'false') {
  2414. config[structure[key]] = $(key).val();
  2415. $(key).removeClass('is_null');
  2416. } else {
  2417. $(key).addClass('is_null');
  2418. allFieldsValid = false;
  2419. }
  2420. }
  2421.  
  2422. // 校验提示
  2423. for (let i = 0, len = checkable.length; i < len; i++) {
  2424. let value = $(checkable[i]).val();
  2425. if (value && !valiKeyValue(value)) {
  2426. if (!$(checkable[i]).prev('span.text-error').length) {
  2427. $(checkable[i]).before('<span class="text-error" style="color: red;">格式不符或存在非法字符</span>');
  2428. }
  2429. allFieldsValid = false;
  2430. } else {
  2431. $(checkable[i]).prev('span.text-error').remove();
  2432. }
  2433. }
  2434.  
  2435. if (!allFieldsValid) return;
  2436. tempConfig.configurations[index] = config;
  2437.  
  2438. settingMenu.remove();
  2439. $(styleElement).remove();
  2440. menu.css({ display: "none" });
  2441.  
  2442. list.children().eq(index).find("label").text(config.note);
  2443. });
  2444.  
  2445. // 关闭按钮
  2446. settingMenu.on("click", ".btn-close", () => {
  2447. settingMenu.remove();
  2448. $(styleElement).remove();
  2449. });
  2450. }
  2451.  
  2452. // 删除数据
  2453. function onDelete() {
  2454. const menu = $("#config_bar_menu");
  2455. menu.css({ display: "none" });
  2456.  
  2457. const list = $("#config_bar_ul");
  2458. const index = Array.from(list.children()).indexOf(this);
  2459.  
  2460. tempConfig.configurations.splice(index, 1);
  2461.  
  2462. list.children().eq(index).remove();
  2463. }
  2464.  
  2465. // 创建编辑窗口
  2466. function createWindow() {
  2467. const styleElement = GM_addStyle(darkenPageStyle2);
  2468. $("body").append(configHTML);
  2469. addDraggable($('#config_edit_menu'));
  2470. return styleElement;
  2471. }
  2472.  
  2473. // 创建控制面板
  2474. function createControlBar() {
  2475. $(element).append(`
  2476. <div id='configControlTip' style='color:red;'></div>
  2477. <div class='config_bar'>
  2478. <div class='config_bar_list' id='config_bar_list'>
  2479. <ul class='config_bar_ul' id='config_bar_ul'></ul>
  2480. </div>
  2481. </div>
  2482. `);
  2483. }
  2484.  
  2485. // 创建右键菜单
  2486. function createContextMenu() {
  2487. const menu = $("<div id='config_bar_menu' style='display: none;'></div>");
  2488. menu.html(`
  2489. <div class='config_bar_menu_item' id='config_bar_menu_edit'>修改</div>
  2490. <div class='config_bar_menu_item' id='config_bar_menu_delete'>删除</div>
  2491. `);
  2492. $("body").append(menu);
  2493. }
  2494.  
  2495. // 创建新的li元素
  2496. function createListItemElement(text) {
  2497. const li = $("<li></li>");
  2498. const radio = $("<input type='radio' name='config_item'></input>").appendTo(li);
  2499. radio.attr("value", counter).attr("id", counter++);
  2500. const label = $("<label class='config_bar_ul_li_text'></label>").text(text).attr("for", radio.attr("value")).appendTo(li);
  2501.  
  2502. // 添加右键菜单
  2503. li.on("contextmenu", function (event) {
  2504. event.preventDefault();
  2505. const menu = $("#config_bar_menu");
  2506. menu.css({ display: "block", left: event.pageX, top: event.pageY });
  2507.  
  2508. const deleteItem = $("#config_bar_menu_delete");
  2509. const editItem = $("#config_bar_menu_edit");
  2510.  
  2511. // 移除旧事件
  2512. deleteItem.off("click");
  2513. editItem.off("click");
  2514.  
  2515. deleteItem.on("click", onDelete.bind(this));
  2516. editItem.on("click", onEdit.bind(this));
  2517.  
  2518. $(document).one("click", (event) => {
  2519. if (!menu.get(0).contains(event.target)) {
  2520. menu.css({ display: "none" });
  2521. deleteItem.off("click", onDelete);
  2522. editItem.off("click", onEdit);
  2523. }
  2524. });
  2525. });
  2526.  
  2527.  
  2528. return li;
  2529. }
  2530.  
  2531. // 渲染列表
  2532. function renderList() {
  2533. const listContainer = $("#config_bar_list");
  2534. const list = $("#config_bar_ul");
  2535. list.empty();
  2536. tempConfig.configurations.forEach((item) => {
  2537. list.append(createListItemElement(item[structure['#note']]));
  2538. });
  2539.  
  2540. list.append(`
  2541. <li id='add_button'>
  2542. <span>+ 添加</span>
  2543. </li>
  2544. `);
  2545. const addItem = $('#add_button');
  2546. addItem.on("click", onAdd);
  2547. };
  2548.  
  2549. renderList();
  2550. return tempConfig;
  2551. }
  2552.  
  2553. const CFBetterSettingMenuHTML = `
  2554. <div class='CFBetter_setting_menu' id='CFBetter_setting_menu'>
  2555. <div class="tool-box">
  2556. <button class="btn-close">×</button>
  2557. </div>
  2558. <div class="CFBetter_setting_container">
  2559. <div class="CFBetter_setting_sidebar">
  2560. <ul>
  2561. <li><a href="#basic-settings" id="sidebar-basic-settings" class="active">基本设置</a></li>
  2562. <li><a href="#translation-settings" id="sidebar-translation-settings">翻译设置</a></li>
  2563. <li><a href="#clist_rating-settings" id="sidebar-clist_rating-settings">Clist设置</a></li>
  2564. <li><a href="#compatibility-settings" id="sidebar-compatibility-settings">兼容设置</a></li>
  2565. </ul>
  2566. </div>
  2567. <div class="CFBetter_setting_content">
  2568. <div id="basic-settings" class="settings-page active">
  2569. <h3>基本设置</h3>
  2570. <hr>
  2571. <div class='CFBetter_setting_list' style="padding: 0px 10px;">
  2572. <span id="darkMode_span">黑暗模式</span>
  2573. <div class="dark-mode-selection">
  2574. <label>
  2575. <input class="radio-input" type="radio" name="darkMode" value="dark" />
  2576. <span class="CFBetter_setting_menu_label_text">黑暗</span>
  2577. <span class="radio-icon"> </span>
  2578. </label>
  2579. <label>
  2580. <input checked="" class="radio-input" type="radio" name="darkMode" value="light" />
  2581. <span class="CFBetter_setting_menu_label_text">白天</span>
  2582. <span class="radio-icon"> </span>
  2583. </label>
  2584. <label>
  2585. <input class="radio-input" type="radio" name="darkMode" value="follow" />
  2586. <span class="CFBetter_setting_menu_label_text">跟随系统</span>
  2587. <span class="radio-icon"> </span>
  2588. </label>
  2589. </div>
  2590. </div>
  2591. <div class='CFBetter_setting_list'>
  2592. <label for="bottomZh_CN">界面汉化</label>
  2593. <input type="checkbox" id="bottomZh_CN" name="bottomZh_CN">
  2594. </div>
  2595. <div class='CFBetter_setting_list'>
  2596. <label for="showLoading">显示加载提示信息</label>
  2597. <div class="help_tip">
  2598. ${helpCircleHTML}
  2599. <div class="tip_text">
  2600. <p>当你开启 显示加载信息 时,每次加载页面时会在上方显示加载信息提示:“Codeforces Better! —— xxx”</p>
  2601. <p>这用于了解脚本当前的工作情况,<strong>如果你不想看到,可以选择关闭</strong></p>
  2602. <p><u>需要说明的是,如果你需要反馈脚本的任何加载问题,请开启该选项后再截图,以便于分析问题</u></p>
  2603. </div>
  2604. </div>
  2605. <input type="checkbox" id="showLoading" name="showLoading">
  2606. </div>
  2607. <div class='CFBetter_setting_list'>
  2608. <label for="hoverTargetAreaDisplay">显示目标区域范围</label>
  2609. <div class="help_tip">
  2610. `+ helpCircleHTML + `
  2611. <div class="tip_text">
  2612. <p>开启后当鼠标悬浮在 MD视图/复制/翻译 按钮上时,会显示其目标区域的范围</p>
  2613. </div>
  2614. </div>
  2615. <input type="checkbox" id="hoverTargetAreaDisplay" name="hoverTargetAreaDisplay">
  2616. </div>
  2617. <div class='CFBetter_setting_list'>
  2618. <label for="expandFoldingblocks">自动展开折叠块</label>
  2619. <input type="checkbox" id="expandFoldingblocks" name="expandFoldingblocks">
  2620. </div>
  2621. <div class='CFBetter_setting_list'>
  2622. <label for="renderPerfOpt">折叠块渲染优化</label>
  2623. <div class="help_tip">
  2624. `+ helpCircleHTML + `
  2625. <div class="tip_text">
  2626. <p>为折叠块元素启用可见渲染(content-visibility: auto)</p>
  2627. <p>如果您的浏览器查看大量折叠块时比较卡顿,开启后会有一定程度的改善</p>
  2628. <p>注意:本特性有小概率可能导致页面在某些位置时上下快速跳动闪屏</p>
  2629. </div>
  2630. </div>
  2631. <input type="checkbox" id="renderPerfOpt" name="renderPerfOpt">
  2632. </div>
  2633. <div class='CFBetter_setting_list'>
  2634. <label for="commentPaging">评论区分页</label>
  2635. <div class="help_tip">
  2636. `+ helpCircleHTML + `
  2637. <div class="tip_text">
  2638. <p>对评论区分页显示,每页显示指定数量的<strong>主楼</strong></p>
  2639. </div>
  2640. </div>
  2641. <input type="checkbox" id="commentPaging" name="commentPaging">
  2642. </div>
  2643. <div class='CFBetter_setting_list'>
  2644. <label for="showJumpToLuogu">显示跳转到洛谷</label>
  2645. <div class="help_tip">
  2646. `+ helpCircleHTML + `
  2647. <div class="tip_text">
  2648. <p>洛谷OJ上收录了Codeforces的部分题目,一些题目有翻译和题解</p>
  2649. <p>开启显示后,如果当前题目被收录,则会在题目的右上角显示洛谷标志,</p>
  2650. <p>点击即可一键跳转到该题洛谷的对应页面。</strong></p>
  2651. </div>
  2652. </div>
  2653. <input type="checkbox" id="showJumpToLuogu" name="showJumpToLuogu">
  2654. </div>
  2655. <div class='CFBetter_setting_list'>
  2656. <label for="standingsRecolor">榜单重新着色</label>
  2657. <div class="help_tip">
  2658. `+ helpCircleHTML + `
  2659. <div class="tip_text">
  2660. <p>对于采用 Codeforces 赛制的比赛的榜单</p>
  2661. <p>按照“得分/总分”所在的范围为分数重新渐变着色</p>
  2662. <p>范围:1~0.7~0.45~0 深绿色→浅橙色→深橙色→红色</p>
  2663. </div>
  2664. </div>
  2665. <input type="checkbox" id="standingsRecolor" name="standingsRecolor">
  2666. </div>
  2667. </div>
  2668. <div id="translation-settings" class="settings-page">
  2669. <h3>翻译设置</h3>
  2670. <hr>
  2671. <h4>首选项</h4>
  2672. <label>
  2673. <input type='radio' name='translation' value='deepl'>
  2674. <span class='CFBetter_setting_menu_label_text'>deepl翻译</span>
  2675. </label>
  2676. <label>
  2677. <input type='radio' name='translation' value='iflyrec'>
  2678. <span class='CFBetter_setting_menu_label_text'>讯飞听见翻译</span>
  2679. </label>
  2680. <label>
  2681. <input type='radio' name='translation' value='youdao'>
  2682. <span class='CFBetter_setting_menu_label_text'>有道翻译</span>
  2683. </label>
  2684. <label>
  2685. <input type='radio' name='translation' value='google'>
  2686. <span class='CFBetter_setting_menu_label_text'>Google翻译</span>
  2687. </label>
  2688. <label>
  2689. <input type='radio' name='translation' value='caiyun'>
  2690. <span class='CFBetter_setting_menu_label_text'>彩云小译翻译</span>
  2691. </label>
  2692. <label>
  2693. <input type='radio' name='translation' value='openai'>
  2694. <span class='CFBetter_setting_menu_label_text'>ChatGPT翻译
  2695. <div class="help_tip">
  2696. `+ helpCircleHTML + `
  2697. <div class="tip_text">
  2698. <p><b>请在下方添加并选定你想使用的配置信息</b></p>
  2699. <p>具体请阅读脚本页的介绍</p>
  2700. </div>
  2701. </div>
  2702. </span>
  2703. </label>
  2704. <div class='CFBetter_setting_menu_input' id='openai' style='display: none;'>
  2705. <div id="chatgpt-config"></div>
  2706. </div>
  2707. <h4>偏好</h4>
  2708. <div class='CFBetter_setting_list'>
  2709. <label for="comment_translation_choice" style="display: flex;">评论区翻译</label>
  2710. <select id="comment_translation_choice" name="comment_translation_choice">
  2711. <option value="0">跟随首选项</option>
  2712. <option value="deepl">deepl翻译</option>
  2713. <option value="iflyrec">讯飞听见翻译</option>
  2714. <option value="youdao">有道翻译</option>
  2715. <option value="google">Google翻译</option>
  2716. <option value="caiyun">彩云小译翻译</option>
  2717. <option value="openai">ChatGPT翻译</option>
  2718. </select>
  2719. </div>
  2720. <h4>高级</h4>
  2721. <div class='CFBetter_setting_list'>
  2722. <label for="enableSegmentedTranslation">分段翻译</label>
  2723. <div class="help_tip">
  2724. `+ helpCircleHTML + `
  2725. <div class="tip_text">
  2726. <p>分段翻译会对区域内的每一个&#60;&#112;&#47;&#62;和&#60;&#105;&#47;&#62;标签依次进行翻译,</p>
  2727. <p>这通常在翻译<strong>长篇博客</strong>或者<strong>超长的题目</strong>时很有用。</p>
  2728. <p><u>注意:开启分段翻译会产生如下问题:</u></p>
  2729. <p>- 使得翻译接口无法知晓整个文本的上下文信息,会降低翻译质量。</p>
  2730. <p>- 会有<strong>部分内容不会被翻译</strong>,因为它们不是&#60;&#112;&#47;&#62;或&#60;&#105;&#47;&#62;元素</p>
  2731. </div>
  2732. </div>
  2733. <input type="checkbox" id="enableSegmentedTranslation" name="enableSegmentedTranslation">
  2734. </div>
  2735. <div class='CFBetter_setting_list'>
  2736. <label for="translation_replaceSymbol" style="display: flex;">LaTeX替换符</label>
  2737. <div class="help_tip">
  2738. `+ helpCircleHTML + `
  2739. <div class="tip_text">
  2740. <p>脚本通过先取出所有的LaTeX公式,并使用替换符占位,来保证公式不会被翻译接口所破坏</p>
  2741. <p>对于各个翻译服务,不同的替换符本身遭到破坏的概率有所不同,具体请阅读脚本页的说明</p>
  2742. <p>注意:使用ChatGPT翻译时不需要上述操作, 因此不受此选项影响</p>
  2743. <p>具体您可以前往阅读脚本页的说明</p>
  2744. </div>
  2745. </div>
  2746. <select id="translation_replaceSymbol" name="translation_replaceSymbol">
  2747. <option value=2>使用{}</option>
  2748. <option value=1>使用【】</option>
  2749. <option value=3>使用[]</option>
  2750. </select>
  2751. </div>
  2752. </div>
  2753. <div id="clist_rating-settings" class="settings-page">
  2754. <h3>Clist设置</h3>
  2755. <hr>
  2756. <h4>基本</h4>
  2757. <div class='CFBetter_setting_list' style="background-color: #E0F2F1;border: 1px solid #009688;">
  2758. <div>
  2759. <p>注意:在不同页面工作所需要的凭证有所不同,具体请看对应选项的标注说明</p>
  2760. </div>
  2761. </div>
  2762. <div class='CFBetter_setting_list'>
  2763. <label for='clist_Authorization'>
  2764. <div style="display: flex;align-items: center;">
  2765. <span class="input_label">KEY:</span>
  2766. </div>
  2767. </label>
  2768. <div class="help_tip">
  2769. `+ helpCircleHTML + `
  2770. <div class="tip_text">
  2771. <p>格式样例:</p>
  2772. <div style="border: 1px solid #795548; padding: 10px;">
  2773. <p>ApiKey XXXXXXXXX</p>
  2774. </div>
  2775. </div>
  2776. </div>
  2777. <input type='text' id='clist_Authorization' class='no_default' placeholder='请输入KEY' require = true>
  2778. </div>
  2779. <hr>
  2780. <h4>显示Rating分</h4>
  2781. <div class='CFBetter_setting_list'>
  2782. <label for="showClistRating_contest"><span>比赛问题集页</span></label>
  2783. <div class="help_tip" style="margin-right: initial;">
  2784. `+ helpCircleHTML + `
  2785. <div class="tip_text">
  2786. <p>数据来源clist.by</p>
  2787. <p>您需要提供官方的api key</p>
  2788. <p>或让您的浏览器上的clist.by处于登录状态(即cookie有效)</p>
  2789. </div>
  2790. </div>
  2791. <div class="badge">Cookie/API KEY</div>
  2792. <input type="checkbox" id="showClistRating_contest" name="showClistRating_contest">
  2793. </div>
  2794. <div class='CFBetter_setting_list'>
  2795. <label for="showClistRating_problem"><span>题目页</span></label>
  2796. <div class="help_tip" style="margin-right: initial;">
  2797. `+ helpCircleHTML + `
  2798. <div class="tip_text">
  2799. <p>需要让您的浏览器上的clist.by处于登录状态(即cookie有效)才能正常工作</p>
  2800. </div>
  2801. </div>
  2802. <div class="badge">Cookie</div>
  2803. <input type="checkbox" id="showClistRating_problem" name="showClistRating_problem">
  2804. </div>
  2805. <div class='CFBetter_setting_list'>
  2806. <label for="showClistRating_problemset"><span>题单页</span></label>
  2807. <div class="help_tip" style="margin-right: initial;">
  2808. `+ helpCircleHTML + `
  2809. <div class="tip_text">
  2810. <p>需要让您的浏览器上的clist.by处于登录状态(即cookie有效)才能正常工作</p>
  2811. </div>
  2812. </div>
  2813. <div class="badge">Cookie</div>
  2814. <input type="checkbox" id="showClistRating_problemset" name="showClistRating_problemset">
  2815. </div>
  2816. <hr>
  2817. <div class='CFBetter_setting_list'>
  2818. <label for="RatingHidden"><span>防剧透</span></label>
  2819. <div class="help_tip">
  2820. `+ helpCircleHTML + `
  2821. <div class="tip_text">
  2822. <p>只有当鼠标移动到Rating分展示区域上时才显示</p>
  2823. </div>
  2824. </div>
  2825. <input type="checkbox" id="RatingHidden" name="RatingHidden">
  2826. </div>
  2827. </div>
  2828. <div id="compatibility-settings" class="settings-page">
  2829. <h3>兼容设置</h3>
  2830. <hr>
  2831. <div class='CFBetter_setting_list'>
  2832. <label for="loaded"><span id="loaded_span">不等待页面资源加载</span></label>
  2833. <div class="help_tip">
  2834. `+ helpCircleHTML + `
  2835. <div class="tip_text">
  2836. <p>为了防止在页面资源未加载完成前(主要是各种js)执行脚本产生意外的错误,脚本默认会等待 window.onload 事件</p>
  2837. <p>如果您的页面上方的加载信息始终停留在:“等待页面资源加载”,即使页面已经完成加载</p>
  2838. <p><u>您首先应该确认是否是网络问题,</u></p>
  2839. <p>如果不是,那这可能是由于 window.onload 事件在您的浏览器中触发过早(早于DOMContentLoaded),</p>
  2840. <p>您可以尝试开启该选项来不再等待 window.onload 事件</p>
  2841. <p><u>注意:如果没有上述问题,请不要开启该选项</u></p>
  2842. </div>
  2843. </div>
  2844. <input type="checkbox" id="loaded" name="loaded">
  2845. </div>
  2846. </div>
  2847. </div>
  2848. </div>
  2849. `;
  2850.  
  2851. const chatgptConfigEditHTML = `
  2852. <div class='CFBetter_setting_menu' id='config_edit_menu'>
  2853. <div class="tool-box">
  2854. <button class="btn-close">×</button>
  2855. </div>
  2856. <h4>配置</h4>
  2857. <h5>基本</h5>
  2858. <hr>
  2859. <label for='note'>
  2860. <span class="input_label">备注:</span>
  2861. </label>
  2862. <input type='text' id='note' class='no_default' placeholder='请为该配置取一个备注名' require = true>
  2863. <label for='openai_model'>
  2864. <div style="display: flex;align-items: center;">
  2865. <span class="input_label">模型:</span>
  2866. <div class="help_tip">
  2867. `+ helpCircleHTML + `
  2868. <div class="tip_text">
  2869. <p>留空则默认为:gpt-3.5-turbo</p>
  2870. <p>模型列表请查阅<a target="_blank" href="https://platform.openai.com/docs/models">OpenAI官方文档</a></p>
  2871. <p><strong>此外,如果您使用的是服务商提供的代理API,请确认服务商是否支持对应模型</strong></p>
  2872. </div>
  2873. </div>
  2874. </div>
  2875. </label>
  2876. <input type='text' id='openai_model' placeholder='gpt-3.5-turbo' require = false>
  2877. <label for='openai_key'>
  2878. <div style="display: flex;align-items: center;">
  2879. <span class="input_label">KEY:</span>
  2880. <div class="help_tip">
  2881. `+ helpCircleHTML + `
  2882. <div class="tip_text">
  2883. <p>您需要输入自己的OpenAI key,<a target="_blank" href="https://platform.openai.com/account/usage">官网</a></p>
  2884. <p><b>如果您使用的是服务商提供的代理API,则应该填写服务商提供的 Key</b></p>
  2885. </div>
  2886. </div>
  2887. </div>
  2888. </label>
  2889. <input type='text' id='openai_key' class='no_default' placeholder='请输入KEY' require = true>
  2890. <label for='openai_proxy'>
  2891. <div style="display: flex;align-items: center;">
  2892. <span class="input_label">Proxy API:</span>
  2893. <div class="help_tip">
  2894. `+ helpCircleHTML + `
  2895. <div class="tip_text">
  2896. <p>留空则默认为OpenAI官方API</p>
  2897. <p>您也可以填写指定的API来代理访问OpenAIAPI,</p>
  2898. <p>如果您使用的是服务商提供的代理APIKEY,则这里应该填写其提供的<strong>完整</strong>API地址,详请阅读脚本说明</p>
  2899. <p><strong>由于您指定了自定义的APITampermonkey会对您的跨域请求进行警告,您需要自行授权</strong></p>
  2900. </div>
  2901. </div>
  2902. </div>
  2903. </label>
  2904. <input type='text' id='openai_proxy' placeholder='https://api.openai.com/v1/chat/completions' require = false>
  2905. <h5>高级</h5>
  2906. <hr>
  2907. <label for='_header'>
  2908. <div style="display: flex;align-items: center;">
  2909. <span class="input_label">自定义header</span>
  2910. <div class="help_tip">
  2911. `+ helpCircleHTML + `
  2912. <div class="tip_text">
  2913. <p>格式样例:</p>
  2914. <div style="border: 1px solid #795548; padding: 10px;">
  2915. <p>name1 : 123<br>name2 : cccc</p>
  2916. </div>
  2917. </div>
  2918. </div>
  2919. </div>
  2920. </label>
  2921. <textarea id="_header" placeholder='(选填)您可以在这里填写向请求header中额外添加的键值对' require = false></textarea>
  2922. <label for='_data'>
  2923. <div style="display: flex;align-items: center;">
  2924. <span class="input_label">自定义data</span>
  2925. <div class="help_tip">
  2926. `+ helpCircleHTML + `
  2927. <div class="tip_text">
  2928. <p>格式样例:</p>
  2929. <div style="border: 1px solid #795548; padding: 10px;">
  2930. <p>name1 : 123<br>name2 : cccc</p>
  2931. </div>
  2932. </div>
  2933. </div>
  2934. </div>
  2935. </label>
  2936. <textarea id="_data" placeholder='(选填)您可以在这里填写向请求data中额外添加的键值对' require = false></textarea>
  2937. <button id='save'>保存</button>
  2938. </div>
  2939. `;
  2940.  
  2941. // 配置改变保存确认
  2942. function saveConfirmation() {
  2943. return new Promise(resolve => {
  2944. const styleElement = GM_addStyle(darkenPageStyle2);
  2945. let htmlString = `
  2946. <div class="CFBetter_modal">
  2947. <h2>配置已更改,是否保存?</h2>
  2948. <div class="buttons">
  2949. <button id="cancelButton">不保存</button><button id="saveButton">保存</button>
  2950. </div>
  2951. </div>
  2952. `;
  2953. $('body').before(htmlString);
  2954. addDraggable($('.CFBetter_modal'));
  2955. $("#saveButton").click(function () {
  2956. $(styleElement).remove();
  2957. $('.CFBetter_modal').remove();
  2958. resolve(true);
  2959. });
  2960. $("#cancelButton").click(function () {
  2961. $(styleElement).remove();
  2962. $('.CFBetter_modal').remove();
  2963. resolve(false);
  2964. });
  2965. });
  2966. }
  2967.  
  2968. // 设置按钮面板
  2969. async function settingPanel() {
  2970. // 添加按钮
  2971. $("div[class='lang-chooser']").each(function () {
  2972. $(this).before(
  2973. "<button class='html2mdButton CFBetter_setting'>CodeforcesBetter设置</button>"
  2974. );
  2975. });
  2976. $("div[class='enter-or-register-box']").each(function () {
  2977. $(this).after(
  2978. "<button class='html2mdButton CFBetter_setting'>CodeforcesBetter设置</button>"
  2979. );
  2980. });
  2981.  
  2982. const $settingBtns = $(".CFBetter_setting");
  2983. $settingBtns.click(() => {
  2984. const styleElement = GM_addStyle(darkenPageStyle);
  2985. $settingBtns.prop("disabled", true).addClass("open");
  2986. $("body").append(CFBetterSettingMenuHTML);
  2987.  
  2988. // 窗口初始化
  2989. addDraggable($('#CFBetter_setting_menu'));
  2990.  
  2991. // 选项卡切换
  2992. $('.CFBetter_setting_sidebar a').click(function (event) {
  2993. event.preventDefault();
  2994. $('.CFBetter_setting_sidebar a').removeClass('active');
  2995. $(this).addClass('active');
  2996. $('.settings-page').removeClass('active');
  2997. const targetPageId = $(this).attr('href').substring(1);
  2998. $('#' + targetPageId).addClass('active');
  2999. });
  3000.  
  3001. const chatgptStructure = {
  3002. '#note': 'note',
  3003. '#openai_model': 'model',
  3004. '#openai_key': 'key',
  3005. '#openai_proxy': 'proxy',
  3006. '#_header': '_header',
  3007. '#_data': '_data',
  3008. }
  3009. const checkable = [
  3010. '#_header',
  3011. '#_data',
  3012. ]
  3013. let tempConfig = GM_getValue('chatgpt-config'); // 缓存配置信息
  3014. tempConfig = setupConfigManagement('#chatgpt-config', tempConfig, chatgptStructure, chatgptConfigEditHTML, checkable);
  3015.  
  3016. // 状态更新
  3017. $("#bottomZh_CN").prop("checked", GM_getValue("bottomZh_CN") === true);
  3018. $("input[name='darkMode'][value='" + darkMode + "']").prop("checked", true);
  3019. $("#showLoading").prop("checked", GM_getValue("showLoading") === true);
  3020. $("#expandFoldingblocks").prop("checked", GM_getValue("expandFoldingblocks") === true);
  3021. $("#enableSegmentedTranslation").prop("checked", GM_getValue("enableSegmentedTranslation") === true);
  3022. $("#renderPerfOpt").prop("checked", GM_getValue("renderPerfOpt") === true);
  3023. $("#commentPaging").prop("checked", GM_getValue("commentPaging") === true);
  3024. $("#standingsRecolor").prop("checked", GM_getValue("standingsRecolor") === true);
  3025. $("#showJumpToLuogu").prop("checked", GM_getValue("showJumpToLuogu") === true);
  3026. $("#loaded").prop("checked", GM_getValue("loaded") === true);
  3027. $("#hoverTargetAreaDisplay").prop("checked", GM_getValue("hoverTargetAreaDisplay") === true);
  3028. $("#showClistRating_contest").prop("checked", GM_getValue("showClistRating_contest") === true);
  3029. $("#showClistRating_problemset").prop("checked", GM_getValue("showClistRating_problemset") === true);
  3030. $("#showClistRating_problem").prop("checked", GM_getValue("showClistRating_problem") === true);
  3031. $("#RatingHidden").prop("checked", GM_getValue("RatingHidden") === true);
  3032. $("input[name='translation'][value='" + translation + "']").prop("checked", true);
  3033. $("input[name='translation']").css("color", "gray");
  3034. if (translation == "openai") {
  3035. $("#openai").show();
  3036. if (tempConfig) {
  3037. $("input[name='config_item'][value='" + tempConfig.choice + "']").prop("checked", true);
  3038. }
  3039. }
  3040. $('#comment_translation_choice').val(GM_getValue("commentTranslationChoice"));
  3041. $('#translation_replaceSymbol').val(GM_getValue("replaceSymbol"));
  3042. $("#clist_Authorization").val(GM_getValue("clist_Authorization"));
  3043.  
  3044. // 翻译选择情况监听
  3045. $("input[name='translation']").change(function () {
  3046. var selected = $(this).val(); // 获取当前选中的值
  3047. if (selected === "openai") {
  3048. $("#openai").show();
  3049. if (tempConfig) {
  3050. $("input[name='config_item'][value='" + tempConfig.choice + "']").prop("checked", true);
  3051. }
  3052. } else {
  3053. $("#openai").hide();
  3054. }
  3055. });
  3056.  
  3057. // 配置选择情况监听
  3058. $("input[name='config_item']").change(function () {
  3059. var selected = $(this).val(); // 获取当前选中的值
  3060. tempConfig.choice = selected;
  3061. });
  3062.  
  3063. // 关闭
  3064. const $settingMenu = $(".CFBetter_setting_menu");
  3065. $settingMenu.on("click", ".btn-close", async () => {
  3066. const settings = {
  3067. bottomZh_CN: $("#bottomZh_CN").prop("checked"),
  3068. darkMode: $("input[name='darkMode']:checked").val(),
  3069. showLoading: $("#showLoading").prop("checked"),
  3070. hoverTargetAreaDisplay: $("#hoverTargetAreaDisplay").prop("checked"),
  3071. expandFoldingblocks: $("#expandFoldingblocks").prop("checked"),
  3072. renderPerfOpt: $("#renderPerfOpt").prop("checked"),
  3073. commentPaging: $("#commentPaging").prop("checked"),
  3074. enableSegmentedTranslation: $("#enableSegmentedTranslation").prop("checked"),
  3075. standingsRecolor: $("#standingsRecolor").prop("checked"),
  3076. showJumpToLuogu: $("#showJumpToLuogu").prop("checked"),
  3077. loaded: $("#loaded").prop("checked"),
  3078. translation: $("input[name='translation']:checked").val(),
  3079. commentTranslationChoice: $('#comment_translation_choice').val(),
  3080. replaceSymbol: $('#translation_replaceSymbol').val(),
  3081. showClistRating_contest: $('#showClistRating_contest').prop("checked"),
  3082. showClistRating_problemset: $('#showClistRating_problemset').prop("checked"),
  3083. showClistRating_problem: $('#showClistRating_problem').prop("checked"),
  3084. RatingHidden: $('#RatingHidden').prop("checked"),
  3085. clist_Authorization: $('#clist_Authorization').val()
  3086. };
  3087.  
  3088. // 判断是否改变
  3089. let hasChange = false;
  3090. for (const [key, value] of Object.entries(settings)) {
  3091. if (!hasChange && GM_getValue(key) != value) hasChange = true;
  3092. }
  3093. if (!hasChange && JSON.stringify(GM_getValue('chatgpt-config')) != JSON.stringify(tempConfig)) hasChange = true;
  3094.  
  3095. if (hasChange) {
  3096. const shouldSave = await saveConfirmation();
  3097. if (shouldSave) {
  3098. // 数据校验
  3099. if (settings.translation === "openai") {
  3100. var selectedIndex = $('input[name="config_item"]:checked').closest('li').index();
  3101. if (selectedIndex === -1) {
  3102. $('#configControlTip').text('请选择一项配置!');
  3103. $('.CFBetter_setting_sidebar a').removeClass('active');
  3104. $('#sidebar-translation-settings').addClass('active');
  3105. $('.settings-page').removeClass('active');
  3106. $('#translation-settings').addClass('active');
  3107. return;
  3108. }
  3109. }
  3110.  
  3111. // 保存数据
  3112. let refreshPage = false; // 是否需要刷新页面
  3113. for (const [key, value] of Object.entries(settings)) {
  3114. if (!refreshPage && !(key == 'enableSegmentedTranslation' || key == 'translation' || key == 'darkMode' ||
  3115. key == 'replaceSymbol' || key == 'commentTranslationChoice')) {
  3116. if (GM_getValue(key) != value) refreshPage = true;
  3117. }
  3118. GM_setValue(key, value);
  3119. }
  3120. GM_setValue('chatgpt-config', tempConfig);
  3121.  
  3122. if (refreshPage) location.reload();
  3123. else {
  3124. // 切换黑暗模式
  3125. if (darkMode != settings.darkMode) {
  3126. darkMode = settings.darkMode;
  3127. // 移除旧的事件监听器
  3128. changeEventListeners.forEach(listener => {
  3129. mediaQueryList.removeEventListener('change', listener);
  3130. });
  3131.  
  3132. if (darkMode == "follow") {
  3133. changeEventListeners.push(handleColorSchemeChange);
  3134. mediaQueryList.addEventListener('change', handleColorSchemeChange);
  3135. $('html').removeAttr('data-theme');
  3136. } else if (darkMode == "dark") {
  3137. $('html').attr('data-theme', 'dark');
  3138. } else {
  3139. $('html').attr('data-theme', 'light');
  3140. // 移除旧的事件监听器
  3141. const mediaQueryList = window.matchMedia('(prefers-color-scheme: dark)');
  3142. window.matchMedia('(prefers-color-scheme: dark)');
  3143. }
  3144. }
  3145. // 更新配置信息
  3146. enableSegmentedTranslation = settings.enableSegmentedTranslation;
  3147. translation = settings.translation;
  3148. replaceSymbol = settings.replaceSymbol;
  3149. commentTranslationChoice = settings.commentTranslationChoice;
  3150. if (settings.translation === "openai") {
  3151. var selectedIndex = $('#config_bar_ul li input[type="radio"]:checked').closest('li').index();
  3152. if (selectedIndex !== opneaiConfig.choice) {
  3153. opneaiConfig = GM_getValue("chatgpt-config");
  3154. const configAtIndex = opneaiConfig.configurations[selectedIndex];
  3155. openai_model = configAtIndex.model;
  3156. openai_key = configAtIndex.key;
  3157. openai_proxy = configAtIndex.proxy;
  3158. openai_header = configAtIndex._header ?
  3159. configAtIndex._header.split("\n").map(header => {
  3160. const [key, value] = header.split(":");
  3161. return { [key.trim()]: value.trim() };
  3162. }) : [];
  3163. openai_data = configAtIndex._data ?
  3164. configAtIndex._data.split("\n").map(header => {
  3165. const [key, value] = header.split(":");
  3166. return { [key.trim()]: value.trim() };
  3167. }) : [];
  3168. }
  3169. }
  3170. }
  3171. }
  3172. }
  3173.  
  3174. $settingMenu.remove();
  3175. $settingBtns.prop("disabled", false).removeClass("open");
  3176. $(styleElement).remove();
  3177. });
  3178. });
  3179. };
  3180.  
  3181. // html2md转换/处理规则
  3182. var turndownService = new TurndownService({ bulletListMarker: '-' });
  3183. var turndown = turndownService.turndown;
  3184.  
  3185. // 保留原始
  3186. turndownService.keep(['del']);
  3187.  
  3188. // 丢弃
  3189. turndownService.addRule('remove-by-class', {
  3190. filter: function (node) {
  3191. return node.classList.contains('sample-tests') ||
  3192. node.classList.contains('header') ||
  3193. node.classList.contains('overlay') ||
  3194. node.classList.contains('html2md-panel') ||
  3195. node.classList.contains('likeForm');
  3196. },
  3197. replacement: function (content, node) {
  3198. return "";
  3199. }
  3200. });
  3201. turndownService.addRule('remove-script', {
  3202. filter: function (node, options) {
  3203. return node.tagName.toLowerCase() == "script" && node.type.startsWith("math/tex");
  3204. },
  3205. replacement: function (content, node) {
  3206. return "";
  3207. }
  3208. });
  3209.  
  3210. // inline math
  3211. turndownService.addRule('inline-math', {
  3212. filter: function (node, options) {
  3213. return node.tagName.toLowerCase() == "span" && node.className == "MathJax";
  3214. },
  3215. replacement: function (content, node) {
  3216. var latex = $(node).next().text();
  3217. latex = latex.replace(/</g, "&lt;").replace(/>/g, "&gt;");
  3218. return "$" + latex + "$";
  3219. }
  3220. });
  3221.  
  3222. // block math
  3223. turndownService.addRule('block-math', {
  3224. filter: function (node, options) {
  3225. return node.tagName.toLowerCase() == "div" && node.className == "MathJax_Display";
  3226. },
  3227. replacement: function (content, node) {
  3228. var latex = $(node).next().text();
  3229. latex = latex.replace(/</g, "&lt;").replace(/>/g, "&gt;");
  3230. return "\n$$\n" + latex + "\n$$\n";
  3231. }
  3232. });
  3233.  
  3234. // texFontStyle
  3235. turndownService.addRule('texFontStyle', {
  3236. filter: function (node) {
  3237. return (
  3238. node.nodeName === 'SPAN' &&
  3239. node.classList.contains('tex-font-style-bf')
  3240. )
  3241. },
  3242. replacement: function (content) {
  3243. return '**' + content + '**'
  3244. }
  3245. })
  3246.  
  3247. // sectionTitle
  3248. turndownService.addRule('sectionTitle', {
  3249. filter: function (node) {
  3250. return (
  3251. node.nodeName === 'DIV' &&
  3252. node.classList.contains('section-title')
  3253. )
  3254. },
  3255. replacement: function (content) {
  3256. return '**' + content + '**'
  3257. }
  3258. })
  3259.  
  3260. // bordertable
  3261. turndownService.addRule('bordertable', {
  3262. filter: 'table',
  3263. replacement: function (content, node) {
  3264. if (node.classList.contains('bordertable')) {
  3265. var output = [],
  3266. thead = '',
  3267. trs = node.querySelectorAll('tr');
  3268. if (trs.length > 0) {
  3269. var ths = trs[0].querySelectorAll('td,th');
  3270. if (ths.length > 0) {
  3271. thead = '| ' + Array.from(ths).map(th => turndownService.turndown(th.innerHTML.trim())).join(' | ') + ' |\n'
  3272. + '| ' + Array.from(ths).map(() => ' --- ').join('|') + ' |\n';
  3273. }
  3274. }
  3275. var rows = node.querySelectorAll('tr');
  3276. Array.from(rows).forEach(function (row, i) {
  3277. if (i > 0) {
  3278. var cells = row.querySelectorAll('td,th');
  3279. var trow = '| ' + Array.from(cells).map(cell => turndownService.turndown(cell.innerHTML.trim())).join(' | ') + ' |';
  3280. output.push(trow);
  3281. }
  3282. });
  3283. return thead + output.join('\n');
  3284. } else {
  3285. return content;
  3286. }
  3287. }
  3288. });
  3289.  
  3290. // 随机数生成
  3291. function getRandomNumber(numDigits) {
  3292. let min = Math.pow(10, numDigits - 1);
  3293. let max = Math.pow(10, numDigits) - 1;
  3294. return Math.floor(Math.random() * (max - min + 1)) + min;
  3295. }
  3296.  
  3297. // 题目markdown转换/翻译面板
  3298. function addButtonPanel(parent, suffix, type, is_simple = false) {
  3299. let htmlString = `<div class='html2md-panel'>
  3300. <button class='html2mdButton html2md-view${suffix}'>MarkDown视图</button>
  3301. <button class='html2mdButton html2md-cb${suffix}'>Copy</button>
  3302. <button class='html2mdButton translateButton${suffix}'>翻译</button>
  3303. </div>`;
  3304. if (type === "this_level") {
  3305. $(parent).before(htmlString);
  3306. var block = $(".translateButton" + suffix).parent().next();
  3307. } else if (type === "child_level") {
  3308. $(parent).prepend(htmlString);
  3309. var block = $(".translateButton" + suffix).parent().parent();
  3310. }
  3311. if (is_simple) {
  3312. $('.html2md-panel').find('.html2mdButton.html2md-view' + suffix + ', .html2mdButton.html2md-cb' + suffix).remove();
  3313. }
  3314.  
  3315. if (block.css("display") === "none" || block.hasClass('ojbetter-alert')) $(".translateButton" + suffix).parent().remove();
  3316. }
  3317. function addButtonWithHTML2MD(parent, suffix, type) {
  3318. if (is_oldLatex) {
  3319. $(".html2md-view" + suffix).css({
  3320. "cursor": "not-allowed",
  3321. "background-color": "#ffffff",
  3322. "color": "#a8abb2",
  3323. "border": "1px solid #e4e7ed"
  3324. });
  3325. $(".html2md-view" + suffix).prop("disabled", true);
  3326. }
  3327. $(document).on("click", ".html2md-view" + suffix, debounce(function () {
  3328. var target, removedChildren = $();
  3329. if (type === "this_level") {
  3330. target = $(".html2md-view" + suffix).parent().next().get(0);
  3331. } else if (type === "child_level") {
  3332. target = $(".html2md-view" + suffix).parent().parent().get(0);
  3333. removedChildren = $(".html2md-view" + suffix).parent().parent().children(':first').detach();
  3334. }
  3335. if (target.viewmd) {
  3336. target.viewmd = false;
  3337. $(this).text("MarkDown视图");
  3338. $(this).removeClass("mdViewed");
  3339. $(target).html(target.original_html);
  3340. } else {
  3341. target.viewmd = true;
  3342. if (!target.original_html) {
  3343. target.original_html = $(target).html();
  3344. }
  3345. if (!target.markdown) {
  3346. target.markdown = turndownService.turndown($(target).html());
  3347. }
  3348. $(this).text("原始内容");
  3349. $(this).addClass("mdViewed");
  3350. $(target).html(`<span class="mdViewContent" oninput="$(this).parent().get(0).markdown=this.value;" style="width:auto; height:auto;">${target.markdown}</span>`);
  3351. }
  3352. // 恢复删除的元素
  3353. if (removedChildren) $(target).prepend(removedChildren);
  3354. }));
  3355.  
  3356. if (hoverTargetAreaDisplay && !is_oldLatex) {
  3357. var previousCSS;
  3358. $(document).on("mouseover", ".html2md-view" + suffix, function () {
  3359. var target;
  3360.  
  3361. if (type === "this_level") {
  3362. target = $(".html2md-view" + suffix).parent().next().get(0);
  3363. } else if (type === "child_level") {
  3364. target = $(".html2md-view" + suffix).parent().parent().get(0);
  3365. }
  3366.  
  3367. $(target).append('<div class="overlay">目标转换区域</div>');
  3368.  
  3369. previousCSS = {
  3370. "position": $(target).css("position"),
  3371. "display": $(target).css("display")
  3372. };
  3373. $(target).css({
  3374. "position": "relative",
  3375. "display": "block"
  3376. });
  3377.  
  3378. $(".html2md-view" + suffix).parent().css({
  3379. "position": "relative",
  3380. "z-index": "400"
  3381. });
  3382. });
  3383.  
  3384. $(document).on("mouseout", ".html2md-view" + suffix, function () {
  3385. var target;
  3386.  
  3387. if (type === "this_level") {
  3388. target = $(".html2md-view" + suffix).parent().next().get(0);
  3389. } else if (type === "child_level") {
  3390. target = $(".html2md-view" + suffix).parent().parent().get(0);
  3391. }
  3392.  
  3393. $(target).find('.overlay').remove();
  3394. if (previousCSS) {
  3395. $(target).css(previousCSS);
  3396. }
  3397. $(".html2md-view" + suffix).parent().css({
  3398. "position": "static"
  3399. });
  3400. });
  3401. }
  3402. }
  3403.  
  3404. function addButtonWithCopy(parent, suffix, type) {
  3405. if (is_oldLatex) {
  3406. $(".html2md-cb" + suffix).css({
  3407. "cursor": "not-allowed",
  3408. "background-color": "#ffffff",
  3409. "color": "#a8abb2",
  3410. "border": "1px solid #e4e7ed"
  3411. });
  3412. $(".html2md-cb" + suffix).prop("disabled", true);
  3413. }
  3414. $(document).on("click", ".html2md-cb" + suffix, debounce(function () {
  3415. var target, removedChildren;
  3416. if (type === "this_level") {
  3417. target = $(".translateButton" + suffix).parent().next().eq(0).clone();
  3418. } else if (type === "child_level") {
  3419. target = $(".translateButton" + suffix).parent().parent().eq(0).clone();
  3420. $(target).children(':first').remove();
  3421. }
  3422. if ($(target).find('.mdViewContent').length <= 0) {
  3423. text = turndownService.turndown($(target).html());
  3424. } else {
  3425. text = $(target).find('.mdViewContent').text();
  3426. }
  3427. GM_setClipboard(text);
  3428. $(this).addClass("copied");
  3429. $(this).text("Copied");
  3430. // 更新复制按钮文本
  3431. setTimeout(() => {
  3432. $(this).removeClass("copied");
  3433. $(this).text("Copy");
  3434. }, 2000);
  3435. $(target).remove();
  3436. }));
  3437.  
  3438. if (hoverTargetAreaDisplay && !is_oldLatex) {
  3439. var previousCSS;
  3440. $(document).on("mouseover", ".html2md-cb" + suffix, function () {
  3441. var target;
  3442.  
  3443. if (type === "this_level") {
  3444. target = $(".html2md-cb" + suffix).parent().next().get(0);
  3445. } else if (type === "child_level") {
  3446. target = $(".html2md-cb" + suffix).parent().parent().get(0);
  3447. }
  3448.  
  3449. $(target).append('<div class="overlay">目标复制区域</div>');
  3450. previousCSS = {
  3451. "position": $(target).css("position"),
  3452. "display": $(target).css("display")
  3453. };
  3454. $(target).css({
  3455. "position": "relative",
  3456. "display": "block"
  3457. });
  3458. $(".html2md-cb" + suffix).parent().css({
  3459. "position": "relative",
  3460. "z-index": "400"
  3461. })
  3462. });
  3463.  
  3464. $(document).on("mouseout", ".html2md-cb" + suffix, function () {
  3465. var target;
  3466.  
  3467. if (type === "this_level") {
  3468. target = $(".html2md-cb" + suffix).parent().next().get(0);
  3469. } else if (type === "child_level") {
  3470. target = $(".html2md-cb" + suffix).parent().parent().get(0);
  3471. }
  3472.  
  3473. $(target).find('.overlay').remove();
  3474. if (previousCSS) {
  3475. $(target).css(previousCSS);
  3476. }
  3477. $(".html2md-cb" + suffix).parent().css({
  3478. "position": "static"
  3479. })
  3480. });
  3481. }
  3482. }
  3483.  
  3484. async function addButtonWithTranslation(parent, suffix, type, is_comment = false) {
  3485. var result;
  3486. $(document).on('click', '.translateButton' + suffix, debounce(async function () {
  3487. $(this).trigger('mouseout')
  3488. .removeClass("translated")
  3489. .text("翻译中")
  3490. .css("cursor", "not-allowed")
  3491. .prop("disabled", true);
  3492. var target, element_node, block, errerNum = 0;
  3493. if (type === "this_level") block = $(".translateButton" + suffix).parent().next();
  3494. else if (type === "child_level") block = $(".translateButton" + suffix).parent().parent();
  3495.  
  3496. // 重新翻译
  3497. if (result) {
  3498. $(block).find(".translate-problem-statement, .translate-problem-statement-panel").remove();
  3499. // 移除旧的事件
  3500. $(document).off("mouseover", ".translateButton" + suffix);
  3501. $(document).off("mouseout", ".translateButton" + suffix);
  3502. // 重新绑定悬停事件
  3503. if (hoverTargetAreaDisplay) bindHoverEvents(suffix, type);
  3504. }
  3505.  
  3506. // 分段翻译
  3507. if (enableSegmentedTranslation) {
  3508. var pElements = block.find("p:not(li p), li");
  3509. for (let i = 0; i < pElements.length; i++) {
  3510. target = $(pElements[i]).eq(0).clone();
  3511. element_node = pElements[i];
  3512. if (type === "child_level") {
  3513. $(pElements[i]).append("<div></div>");
  3514. element_node = $(pElements[i]).find("div:last-child").get(0);
  3515. }
  3516. result = await blockProcessing(target, element_node, $(".translateButton" + suffix), is_comment);
  3517. if (result.status) errerNum += 1;
  3518. $(target).remove();
  3519. if (translation == "deepl") await new Promise(resolve => setTimeout(resolve, 2000));
  3520. }
  3521. } else {
  3522. target = block.eq(0).clone();
  3523. if (type === "child_level") $(target).children(':first').remove();
  3524. element_node = $(block).get(0);
  3525. if (type === "child_level") {
  3526. $(parent).append("<div></div>");
  3527. element_node = $(parent).find("div:last-child").get(0);
  3528. }
  3529. //是否跳过折叠块
  3530. if ($(target).find('.spoiler').length > 0) {
  3531. const shouldSkip = await skiFoldingBlocks();
  3532. if (shouldSkip) {
  3533. $(target).find('.spoiler').remove();
  3534. } else {
  3535. $(target).find('.html2md-panel').remove();
  3536. }
  3537. }
  3538. result = await blockProcessing(target, element_node, $(".translateButton" + suffix), is_comment);
  3539. if (result.status) errerNum += 1;
  3540. $(target).remove();
  3541. }
  3542.  
  3543. if (!errerNum) {
  3544. $(this).addClass("translated")
  3545. .text("已翻译")
  3546. .css("cursor", "pointer")
  3547. .removeClass("error")
  3548. .prop("disabled", false);
  3549. } else {
  3550. $(this).prop("disabled", false);
  3551. }
  3552.  
  3553. // 重新翻译
  3554. let currentText, is_error;
  3555. $(document).on("mouseover", ".translateButton" + suffix, function () {
  3556. currentText = $(this).text();
  3557. $(this).text("重新翻译");
  3558. if ($(this).hasClass("error")) {
  3559. is_error = true;
  3560. $(this).removeClass("error");
  3561. }
  3562. });
  3563.  
  3564. $(document).on("mouseout", ".translateButton" + suffix, function () {
  3565. $(this).text(currentText);
  3566. if (is_error) $(this).addClass("error");
  3567. });
  3568. }));
  3569.  
  3570. // 目标区域指示
  3571. function bindHoverEvents(suffix, type) {
  3572. var previousCSS;
  3573.  
  3574. $(document).on("mouseover", ".translateButton" + suffix, function () {
  3575. var target;
  3576.  
  3577. if (type === "this_level") {
  3578. target = $(".translateButton" + suffix).parent().next().get(0);
  3579. } else if (type === "child_level") {
  3580. target = $(".translateButton" + suffix).parent().parent().get(0);
  3581. }
  3582.  
  3583. $(target).append('<div class="overlay">目标翻译区域</div>');
  3584.  
  3585. previousCSS = {
  3586. "position": $(target).css("position"),
  3587. "display": $(target).css("display")
  3588. };
  3589. $(target).css({
  3590. "position": "relative",
  3591. "display": ($(target).hasClass('question-response')) ? "block" : $(target).css("display")
  3592. });
  3593.  
  3594. $(".translateButton" + suffix).parent().css({
  3595. "position": "relative",
  3596. "z-index": "400"
  3597. });
  3598. });
  3599.  
  3600. $(document).on("mouseout", ".translateButton" + suffix, function () {
  3601. var target;
  3602.  
  3603. if (type === "this_level") {
  3604. target = $(".translateButton" + suffix).parent().next().get(0);
  3605. } else if (type === "child_level") {
  3606. target = $(".translateButton" + suffix).parent().parent().get(0);
  3607. }
  3608.  
  3609. $(target).find('.overlay').remove();
  3610.  
  3611. if (previousCSS) {
  3612. $(target).css(previousCSS);
  3613. }
  3614.  
  3615. $(".translateButton" + suffix).parent().css({
  3616. "position": "static"
  3617. });
  3618. });
  3619. }
  3620.  
  3621. if (hoverTargetAreaDisplay) bindHoverEvents(suffix, type);
  3622.  
  3623. // 右键菜单
  3624. $(document).on('contextmenu', '.translateButton' + suffix, function (e) {
  3625. e.preventDefault();
  3626.  
  3627. // 是否为评论的翻译
  3628. let is_comment = false;
  3629. if ($(".translateButton" + suffix).parents('.comments').length > 0) is_comment = true;
  3630.  
  3631. // 移除旧的
  3632. if (!$(event.target).closest('.CFBetter_contextmenu').length) {
  3633. $('.CFBetter_contextmenu').remove();
  3634. }
  3635.  
  3636. var menu = $('<div class="CFBetter_contextmenu"></div>');
  3637. var translations = [
  3638. { value: 'deepl', name: 'deepl翻译' },
  3639. { value: 'iflyrec', name: '讯飞听见翻译' },
  3640. { value: 'youdao', name: '有道翻译' },
  3641. { value: 'google', name: 'Google翻译' },
  3642. { value: 'caiyun', name: '彩云小译翻译' },
  3643. { value: 'openai', name: 'ChatGPT翻译' }
  3644. ];
  3645. if (is_comment) {
  3646. var label = $('<label><input type="radio" name="translation" value="0"><span class="CFBetter_contextmenu_label_text">跟随首选项</span></label>');
  3647. menu.append(label);
  3648. }
  3649. translations.forEach(function (translation) {
  3650. var label = $(`<label><input type="radio" name="translation" value="${translation.value}">
  3651. <span class="CFBetter_contextmenu_label_text">${translation.name}</span></label>`);
  3652. menu.append(label);
  3653. });
  3654.  
  3655. // 初始化
  3656. if (is_comment) {
  3657. menu.find(`input[name="translation"][value="${commentTranslationChoice}"]`).prop('checked', true);
  3658. } else {
  3659. menu.find(`input[name="translation"][value="${translation}"]`).prop('checked', true);
  3660. }
  3661. menu.css({
  3662. top: e.pageY + 'px',
  3663. left: e.pageX + 'px'
  3664. }).appendTo('body');
  3665.  
  3666. $(document).one('change', 'input[name="translation"]', function () {
  3667. if (is_comment) {
  3668. commentTranslationChoice = $('input[name="translation"]:checked').val();
  3669. GM_setValue("commentTranslationChoice", commentTranslationChoice);
  3670. } else {
  3671. translation = $('input[name="translation"]:checked').val();
  3672. GM_setValue("translation", translation);
  3673. }
  3674. $('.CFBetter_contextmenu').remove();
  3675. });
  3676.  
  3677. // 点击区域外关闭菜单
  3678. function handleClick(event) {
  3679. if (!$(event.target).closest('.CFBetter_contextmenu').length) {
  3680. $('.CFBetter_contextmenu').remove();
  3681. $(document).off('change', 'input[name="translation"]');
  3682. } else {
  3683. $(document).one('click', handleClick);
  3684. }
  3685. }
  3686. $(document).one('click', handleClick);
  3687. });
  3688. }
  3689.  
  3690. // 块处理
  3691. async function blockProcessing(target, element_node, button, is_comment) {
  3692. if (is_oldLatex) {
  3693. $(target).find('.overlay').remove();
  3694. target.markdown = $(target).html();
  3695. } else if (!target.markdown) {
  3696. target.markdown = turndownService.turndown($(target).html());
  3697. }
  3698. const textarea = document.createElement('textarea');
  3699. textarea.value = target.markdown;
  3700. var result = await translateProblemStatement(textarea.value, element_node, $(button), is_comment);
  3701. //
  3702. if (result.status == 1) {
  3703. $(button).addClass("error")
  3704. .text("翻译中止")
  3705. .css("cursor", "pointer")
  3706. .prop("disabled", false);
  3707. $(result.translateDiv).remove();
  3708. $(target).remove();
  3709. } else if (result.status == 2) {
  3710. result.translateDiv.classList.add("error_translate");
  3711. $(button).addClass("error")
  3712. .text("翻译出错")
  3713. .css("cursor", "pointer")
  3714. .prop("disabled", false);
  3715. $(target).remove();
  3716. }
  3717. return result;
  3718. }
  3719.  
  3720. function addConversionButton() {
  3721. // 题目页添加按钮
  3722. if (window.location.href.includes("problem")) {
  3723. var exContentsPageClasses = ["sample-tests",];
  3724. $('.problem-statement').children('div').each(function () {
  3725. var className = $(this).attr('class');
  3726. if (!exContentsPageClasses.includes(className)) {
  3727. var id = "_problem_" + getRandomNumber(8);
  3728. addButtonPanel(this, id, "this_level");
  3729. addButtonWithHTML2MD(this, id, "this_level");
  3730. addButtonWithCopy(this, id, "this_level");
  3731. addButtonWithTranslation(this, id, "this_level");
  3732. }
  3733. });
  3734. }
  3735. // 添加按钮到ttypography部分
  3736. $(".ttypography").each(function () {
  3737. // 是否为评论
  3738. let is_comment = false;
  3739. if ($(this).parents('.comments').length > 0) is_comment = true;
  3740. // 题目页特判
  3741. if (!$(this).parent().hasClass('problemindexholder')) {
  3742. let id = "_comment_" + getRandomNumber(8);
  3743. addButtonPanel(this, id, "this_level");
  3744. addButtonWithHTML2MD(this, id, "this_level");
  3745. addButtonWithCopy(this, id, "this_level");
  3746. addButtonWithTranslation(this, id, "this_level", is_comment);
  3747. }
  3748. });
  3749.  
  3750. // 添加按钮到spoiler部分
  3751. $('.spoiler-content').each(function () {
  3752. if ($(this).find('.html2md-panel').length === 0) {
  3753. let id = "_spoiler_" + getRandomNumber(8);
  3754. addButtonPanel(this, id, "child_level");
  3755. addButtonWithHTML2MD(this, id, "child_level");
  3756. addButtonWithCopy(this, id, "child_level");
  3757. addButtonWithTranslation(this, id, "child_level");
  3758. }
  3759. });
  3760.  
  3761. // 添加按钮到titled部分
  3762. (function () {
  3763. var elements = [".Virtual.participation", ".Attention", ".Practice"];//只为部分titled添加
  3764. $.each(elements, function (index, value) {
  3765. $(value).each(function () {
  3766. let id = "_titled_" + getRandomNumber(8);
  3767. var $nextDiv = $(this).next().children().get(0);
  3768. addButtonPanel($nextDiv, id, "child_level", true);
  3769. addButtonWithTranslation($nextDiv, id, "child_level");
  3770. });
  3771. });
  3772. })();
  3773. if (is_mSite) {
  3774. $("div[class='_IndexPage_notice']").each(function () {
  3775. let id = "_titled_" + getRandomNumber(8);
  3776. addButtonPanel(this, id, "this_level", true);
  3777. addButtonWithTranslation(this, id, "this_level");
  3778. });
  3779. }
  3780.  
  3781. // 添加按钮到比赛QA部分
  3782. $(".question-response").each(function () {
  3783. let id = "_question_" + getRandomNumber(8);
  3784. addButtonPanel(this, id, "this_level", true);
  3785. addButtonWithTranslation(this, id, "this_level");
  3786. });
  3787. if (is_mSite) {
  3788. $("div._ProblemsPage_announcements table tbody tr:gt(0)").each(function () {
  3789. var $nextDiv = $(this).find("td:first");
  3790. let id = "_question_" + getRandomNumber(8);
  3791. addButtonPanel($nextDiv, id, "this_level", true);
  3792. addButtonWithTranslation($nextDiv, id, "this_level");
  3793. });
  3794. }
  3795.  
  3796. // 添加按钮到弹窗confirm-proto部分
  3797. $(".confirm-proto").each(function () {
  3798. let id = "_titled_" + getRandomNumber(8);
  3799. var $nextDiv = $(this).children().get(0);
  3800. addButtonPanel($nextDiv, id, "this_level", true);
  3801. addButtonWithTranslation($nextDiv, id, "this_level");
  3802. });
  3803.  
  3804. // 添加按钮到_CatalogHistorySidebarFrame_item部分
  3805. $("._CatalogHistorySidebarFrame_item").each(function () {
  3806. let id = "_history_sidebar_" + getRandomNumber(8);
  3807. addButtonPanel(this, id, "this_level", true);
  3808. addButtonWithTranslation(this, id, "this_level");
  3809. });
  3810.  
  3811. $(".problem-lock-link").on("click", function () {
  3812. $(".popup .content div").each(function () {
  3813. let id = "_popup_" + getRandomNumber(8);
  3814. addButtonPanel(this, id, "this_level", true);
  3815. addButtonWithTranslation(this, id, "this_level");
  3816. });
  3817. });
  3818.  
  3819. // 添加按钮到弹窗alert部分
  3820. $(".alert:not(.CFBetter_alert)").each(function () {
  3821. let id = "_alert_" + getRandomNumber(8);
  3822. addButtonPanel(this, id, "this_level", true);
  3823. addButtonWithTranslation(this, id, "this_level");
  3824. });
  3825.  
  3826. // 添加按钮到talk-text部分
  3827. $(".talk-text").each(function () {
  3828. let id = "_talk-text_" + getRandomNumber(8);
  3829. addButtonPanel(this, id, "child_level", true);
  3830. addButtonWithTranslation(this, id, "child_level");
  3831. });
  3832. };
  3833.  
  3834. //弹窗翻译
  3835. function alertZh() {
  3836. var _alert = window.alert;
  3837. window.alert = async function (msg) {
  3838. _alert(msg + "\n=========翻译=========\n" + await translate_deepl(msg));
  3839. return true;
  3840. }
  3841. };
  3842.  
  3843. // 折叠块
  3844. function ExpandFoldingblocks() {
  3845. $('.spoiler').addClass('spoiler-open');
  3846. $('.spoiler-content').attr('style', '');
  3847. };
  3848.  
  3849. // 折叠块渲染优化
  3850. function RenderPerfOpt() {
  3851. return new Promise(function (resolve) {
  3852. var currentIndex = 0;
  3853. var delay = 50;
  3854. var maxDelay = 1000;
  3855.  
  3856. var elements = $('.spoiler-content');
  3857. var batchSize = 10;
  3858. var initialDelay = 50;
  3859.  
  3860. function processBatch(callback) {
  3861. var endIndex = currentIndex + batchSize;
  3862. for (var i = currentIndex; i < endIndex; i++) {
  3863. if (i >= elements.length) {
  3864. callback();
  3865. resolve();
  3866. return;
  3867. }
  3868. var element = elements.eq(i);
  3869. var height = element.outerHeight();
  3870. element.css('contain-intrinsic-size', height + 'px');
  3871. }
  3872.  
  3873. currentIndex += batchSize;
  3874.  
  3875. // 延时
  3876. delay *= 2;
  3877. if (delay >= maxDelay) delay = initialDelay;
  3878.  
  3879. setTimeout(function () {
  3880. processBatch(callback); // 递归
  3881. }, delay);
  3882. }
  3883.  
  3884. processBatch(function () {
  3885. GM_addStyle(`
  3886. .spoiler-content {
  3887. content-visibility: auto;
  3888. }
  3889. `);
  3890. });
  3891. });
  3892. }
  3893.  
  3894. // 分页
  3895. function CommentPagination() {
  3896. GM_addStyle(`
  3897. .comments > .comment {
  3898. display: none;
  3899. }
  3900. #next-page-btn, #prev-page-btn {
  3901. display: none;
  3902. }
  3903. #jump-input, #items-per-page{
  3904. height: 22px;
  3905. border: 1px solid #dcdfe6;
  3906. border-radius: 0.3rem;
  3907. }
  3908. #jump-input:focus-visible{
  3909. border-style: solid;
  3910. border-color: #3f51b5;
  3911. outline: none;
  3912. }
  3913. `);
  3914. $('.comments').after(`
  3915. <div id="pagBar" style="display: flex; align-items: center; justify-content: center; color: #606266;">
  3916. <label for="items-per-page">每页展示主楼数:</label>
  3917. <select id="items-per-page" style="margin-right: 15px;">
  3918. <option value="5">5</option>
  3919. <option value="10">10</option>
  3920. <option value="20">20</option>
  3921. </select>
  3922. <div class="paging" style="margin-right: 15px;">
  3923. <span id="current-page">1</span> / <span id="total-pages"></span>
  3924. </div>
  3925. <input type="text" id="jump-input" placeholder="跳转到页码">
  3926. <button type="button" id="jump-btn" class="html2mdButton">跳转</button>
  3927. <button id="prev-page-btn" class="html2mdButton">上一页</button>
  3928. <button id="next-page-btn" class="html2mdButton">下一页</button>
  3929. </div>
  3930. `);
  3931.  
  3932. let batchSize = 5;
  3933. let elements = $(".comments > .comment").slice(0, -1);
  3934. let start = 0;
  3935. let end = batchSize;
  3936. let currentPage = 1;
  3937. let displayedIndexes = []; // 存储已显示元素的索引
  3938.  
  3939. function showBatch(start, end) {
  3940. // 隐藏上一页
  3941. for (var i = 0; i < displayedIndexes.length; i++) {
  3942. elements.eq(displayedIndexes[i]).hide();
  3943. }
  3944.  
  3945. displayedIndexes = [];
  3946.  
  3947. // 显示当前页
  3948. elements.slice(start, end).each(function (index) {
  3949. $(this).show();
  3950. displayedIndexes.push(start + index);
  3951. });
  3952.  
  3953. // 更新页码和翻页按钮
  3954. $("#current-page").text(currentPage);
  3955. $("#total-pages").text(Math.ceil(elements.length / batchSize));
  3956.  
  3957. if (currentPage === 1) $("#prev-page-btn").hide();
  3958. else $("#prev-page-btn").show();
  3959.  
  3960. if (end >= elements.length) $("#next-page-btn").hide();
  3961. else $("#next-page-btn").show();
  3962. }
  3963.  
  3964. // 初始化
  3965. var commentID = null;
  3966. var pageURL = window.location.href;
  3967. if (pageURL.includes("#comment-")) {
  3968. // 带评论区锚点的链接
  3969. var startIndex = pageURL.lastIndexOf("#comment-") + 9;
  3970. commentID = pageURL.substring(startIndex);
  3971. var indexInComments = null;
  3972. $(".comments > .comment").each(function (index) {
  3973. $(this).find(".comment-table").each(function () {
  3974. var tableCommentID = $(this).attr("commentid");
  3975. if (tableCommentID === commentID) {
  3976. indexInComments = index;
  3977. return false;
  3978. }
  3979. });
  3980. });
  3981. let page = Math.ceil((indexInComments + 1) / batchSize);
  3982. currentPage = !page ? 1 : page;
  3983. showBatch((currentPage - 1) * batchSize, currentPage * batchSize);
  3984. setTimeout(function () {
  3985. window.location.href = pageURL;
  3986. }, 1000);
  3987. } else {
  3988. showBatch(0, batchSize);
  3989. }
  3990.  
  3991. $("#prev-page-btn").on("click", function () {
  3992. var itemsPerPage = parseInt($("#items-per-page").val());
  3993. start = (currentPage - 2) * itemsPerPage;
  3994. end = (currentPage - 1) * itemsPerPage;
  3995. currentPage--;
  3996. showBatch(start, end);
  3997. });
  3998.  
  3999. $("#next-page-btn").on("click", function () {
  4000. var itemsPerPage = parseInt($("#items-per-page").val());
  4001. start = currentPage * itemsPerPage;
  4002. end = (currentPage + 1) * itemsPerPage;
  4003. currentPage++;
  4004. showBatch(start, end);
  4005. });
  4006.  
  4007. $("#jump-btn").on("click", function () {
  4008. var inputPage = parseInt($("#jump-input").val());
  4009.  
  4010. if (inputPage >= 1 && inputPage <= Math.ceil(elements.length / parseInt($("#items-per-page").val()))) {
  4011. var itemsPerPage = parseInt($("#items-per-page").val());
  4012. start = (inputPage - 1) * itemsPerPage;
  4013. end = inputPage * itemsPerPage;
  4014. currentPage = inputPage; // 更新当前页码
  4015. showBatch(start, end);
  4016. }
  4017. });
  4018.  
  4019. $("#items-per-page").on("change", function () {
  4020. batchSize = parseInt($(this).val());
  4021. let page = Math.ceil(end / batchSize);
  4022. currentPage = !page ? 1 : page;
  4023. let maxPage = Math.ceil(elements.length / batchSize);
  4024. if (currentPage > maxPage) currentPage = maxPage;
  4025. showBatch((currentPage - 1) * batchSize, currentPage * batchSize);
  4026. });
  4027. }
  4028.  
  4029. // 跳转洛谷
  4030. function getProblemId(url) {
  4031. const regex = url.includes('/contest/')
  4032. ? /\/contest\/(\d+)\/problem\/([A-Za-z\d]+)/
  4033. : /\/problemset\/problem\/(\d+)\/([A-Za-z\d]+)/;
  4034. const matchResult = url.match(regex);
  4035. return matchResult && matchResult.length >= 3 ? `${matchResult[1]}${matchResult[2]}` : '';
  4036. };
  4037.  
  4038. async function CF2luogu() {
  4039. const url = window.location.href;
  4040. const problemId = getProblemId(url);
  4041. const checkLinkExistence = (url) => {
  4042. return new Promise((resolve, reject) => {
  4043. GM.xmlHttpRequest({
  4044. method: "GET",
  4045. url,
  4046. headers: { "Range": "bytes=0-9999" }, // 获取前10KB数据
  4047. onload(response) {
  4048. if (response.responseText.match(/题目未找到/g)) {
  4049. resolve(false);
  4050. } else {
  4051. resolve(true);
  4052. }
  4053. },
  4054. onerror(error) {
  4055. reject(error);
  4056. }
  4057. });
  4058. });
  4059. };
  4060.  
  4061. let panelElement;
  4062. if ($('#CF2luoguPanel').length > 0) {
  4063. panelElement = $('#CF2luoguPanel');
  4064. } else {
  4065. panelElement = $("<div>")
  4066. .addClass("html2md-panel")
  4067. .attr("id", "CF2luoguPanel")
  4068. .insertBefore('.problemindexholder');
  4069. }
  4070.  
  4071. const LuoguUrl = `https://www.luogu.com.cn/problem/CF${problemId}`;
  4072. const result = await checkLinkExistence(LuoguUrl);
  4073. if (problemId && result) {
  4074. const problemLink = $("<a>")
  4075. .attr("id", "problemLink")
  4076. .attr("href", LuoguUrl)
  4077. .attr("target", "_blank")
  4078. .html(`<button style="height: 25px;" class="html2mdButton"><img style="width:45px; margin-right:2px;" src="https://cdn.luogu.com.cn/fe/logo.png"></button>`);
  4079. panelElement.append(problemLink);
  4080. }
  4081. }
  4082.  
  4083. // RatingClass
  4084. const ratingClassMap = {
  4085. 0: "rating_by_clist_color0",
  4086. 1200: "rating_by_clist_color1",
  4087. 1400: "rating_by_clist_color2",
  4088. 1600: "rating_by_clist_color3",
  4089. 1900: "rating_by_clist_color4",
  4090. 2100: "rating_by_clist_color5",
  4091. 2300: "rating_by_clist_color6",
  4092. 2400: "rating_by_clist_color7",
  4093. 2600: "rating_by_clist_color8",
  4094. 3000: "rating_by_clist_color9"
  4095. };
  4096. const cssMap = {
  4097. "rating_by_clist_color0": "#cccccc",
  4098. "rating_by_clist_color1": "#73e473",
  4099. "rating_by_clist_color2": "#77ddbb",
  4100. "rating_by_clist_color3": "#aaaaff",
  4101. "rating_by_clist_color4": "#ff88ff",
  4102. "rating_by_clist_color5": "#ffcc88",
  4103. "rating_by_clist_color6": "#ffbb55",
  4104. "rating_by_clist_color7": "#ff7777",
  4105. "rating_by_clist_color8": "#ff3333",
  4106. "rating_by_clist_color9": "#aa0000"
  4107. };
  4108. // cookie有效性检查
  4109. async function checkCookie(isContest = false) {
  4110. let ok = false, congested = false;
  4111. await new Promise((resolve, reject) => {
  4112. GM_xmlhttpRequest({
  4113. method: "GET",
  4114. url: "https://clist.by:443/api/v3/contest/?limit=1&resource_id=1",
  4115. onload: function (response) {
  4116. if (response.status === 200) ok = true;
  4117. resolve();
  4118. },
  4119. onerror: function (response) {
  4120. console.warn("访问clist.by出现错误,请稍后再试");
  4121. congested = true;
  4122. resolve();
  4123. }
  4124. });
  4125. });
  4126. if (isContest && !ok && !congested) {
  4127. await new Promise((resolve, reject) => {
  4128. GM_xmlhttpRequest({
  4129. method: "GET",
  4130. url: "https://clist.by:443/api/v3/contest/?limit=1&resource_id=1",
  4131. headers: {
  4132. "Authorization": clist_Authorization
  4133. },
  4134. onload: function (response) {
  4135. if (response.status === 200) ok = true;
  4136. resolve();
  4137. },
  4138. onerror: function (response) {
  4139. console.warn("访问clist.by出现错误,请稍后再试");
  4140. resolve();
  4141. }
  4142. });
  4143. });
  4144. }
  4145. if (!ok) {
  4146. var state = congested ? `当前访问Clist.by网络拥堵,请求已中断,请稍后再重试` :
  4147. `当前浏览器的Clist.by登录Cookie可能已失效,请打开<a target="_blank" href="https://clist.by/">Clist.by</a>重新登录
  4148. <br>说明:脚本的Clist Rating分显示实现依赖于Clist.by的登录用户Cookie信息,
  4149. <br>脚本不会也无法获取您在Clist.by站点上的具体Cookie,发送请求时会由浏览器自动携带,具体请阅读脚本页的说明`;
  4150. var newElement = $("<div></div>")
  4151. .addClass("alert alert-error ojbetter-alert").html(`CodeforcesBetter! —— ${state}`)
  4152. .css({ "margin": "1em", "text-align": "center", "position": "relative" });
  4153. $(".menu-box:first").next().after(newElement);
  4154. }
  4155. return ok;
  4156. }
  4157. // 创建css
  4158. function creatRatingCss(hasborder = true) {
  4159. let dynamicCss = "";
  4160. let hiddenCss = RatingHidden ? ":hover" : "";
  4161. for (let cssClass in cssMap) {
  4162. dynamicCss += "." + cssClass + hiddenCss + " {\n";
  4163. let border = hasborder ? ` border: 1px solid ${cssMap[cssClass]};\n` : ` border: 1px solid #dcdfe6;\n`;
  4164. dynamicCss += ` color: ${cssMap[cssClass]};\n${border}}\n`;
  4165. }
  4166. GM_addStyle(dynamicCss);
  4167. }
  4168. // 模拟请求获取
  4169. async function getRating(problem, problem_url, contest = null) {
  4170. problem = problem.replace(/\([\s\S]*?\)/g, '').replace(/^\s+|\s+$/g, '');
  4171. return new Promise((resolve, reject) => {
  4172. const queryString = `search=${problem}&resource=1`;
  4173. GM_xmlhttpRequest({
  4174. method: 'GET',
  4175. url: `https://clist.by/problems/?${queryString}`,
  4176. responseType: 'html',
  4177. onload: function (response) {
  4178. const html = response.responseText;
  4179. var cleanedHtml = html.replace(/src=(.|\s)*?"/g, '');
  4180. const trs = $(cleanedHtml).find('table').find('tbody tr');
  4181. let records = [];
  4182. trs.each(function (index) {
  4183. const rating = $(this).find('.problem-rating-column').text().trim();
  4184. const link = $(this).find('.problem-name-column').find('a').eq(1).attr('href');
  4185. var contests = [];
  4186. $(this).find('.problem-name-column').find('.pull-right a[title], .pull-right span[title]').each(function () {
  4187. var value = $(this).attr('title');
  4188. if (value) {
  4189. value = value.replace(/<br\/?><\/a>/g, '');
  4190. contests.push(value);
  4191. }
  4192. });
  4193. records.push({ rating: rating, link: link, contests: contests });
  4194. });
  4195. for (let record of records) {
  4196. let link = record.link.replace(/http:/g, 'https:');
  4197. if (link == problem_url || link == problem_url + '/') {
  4198. resolve({
  4199. rating: parseInt(record.rating),
  4200. problem: problem
  4201. });
  4202. return;
  4203. } else if (contest != null) {
  4204. for (let item of record.contests) {
  4205. if (contest == item) {
  4206. resolve({
  4207. rating: parseInt(record.rating),
  4208. problem: problem
  4209. });
  4210. return;
  4211. }
  4212. }
  4213. }
  4214. }
  4215. reject('\n' + problem + '未找到该题目的数据\n');
  4216. },
  4217. onerror: function (response) {
  4218. reject(problem + '发生了错误!');
  4219. }
  4220. });
  4221. });
  4222. }
  4223. // contest页显示Rating
  4224. async function showRatingByClist_contest() {
  4225. if (!await checkCookie(true)) return;
  4226. creatRatingCss();
  4227.  
  4228. var clist_event = $('#sidebar').children().first().find('.rtable th').first().text();
  4229. var problemsMap = new Map();
  4230. await new Promise((resolve, reject) => {
  4231. GM_xmlhttpRequest({
  4232. method: "GET",
  4233. url: "https://clist.by/api/v3/contest/?limit=1&resource_id=1&with_problems=true&event=" + encodeURIComponent(clist_event),
  4234. headers: {
  4235. "Authorization": clist_Authorization
  4236. },
  4237. onload: function (response) {
  4238. var data = JSON.parse(response.responseText);
  4239. var objects = data.objects;
  4240. if (objects.length > 0) {
  4241. var problems = objects[0].problems;
  4242. for (var i = 0; i < problems.length; i++) {
  4243. var problem = problems[i];
  4244. problemsMap.set(problem.url, problem.rating);
  4245. }
  4246. resolve();
  4247. }
  4248. }
  4249. });
  4250. });
  4251.  
  4252. $('.datatable .id.left').each(function () {
  4253. let href = 'https://codeforces.com' + $(this).find('a').attr('href');
  4254. if (problemsMap.has(href)) {
  4255. var rating = problemsMap.get(href);
  4256. let className = "rating_by_clist_color9";
  4257. let keys = Object.keys(ratingClassMap);
  4258. for (let i = 0; i < keys.length; i++) {
  4259. if (rating < keys[i]) {
  4260. className = ratingClassMap[keys[i - 1]];
  4261. break;
  4262. }
  4263. }
  4264. $(this).find('a').after(`<div class="ratingBadges ${className}"><span class="rating">${rating}</span></div>`);
  4265. }
  4266. });
  4267. }
  4268. // problemset页显示Rating
  4269. async function showRatingByClist_problemset() {
  4270. if (!await checkCookie()) return;
  4271. creatRatingCss();
  4272.  
  4273. const $problems = $('.problems');
  4274. const $trs = $problems.find('tbody tr:gt(0)');
  4275.  
  4276. for (let i = 0; i < $trs.length; i += 3) {
  4277. const promises = [];
  4278. const endIndex = Math.min(i + 3, $trs.length);
  4279.  
  4280. for (let j = i; j < endIndex; j++) {
  4281. const $tds = $($trs[j]).find('td');
  4282. let problem = $($tds[1]).find('a:first').text();
  4283. let problem_url = $($tds[1]).find('a').attr('href');
  4284. problem_url = problem_url.replace(/^\/problemset\/problem\/(\d+)\/(\w+)/, 'https://codeforces.com/contest/$1/problem/$2');
  4285.  
  4286. promises.push(getRating(problem, problem_url).catch(error => console.warn(error)));
  4287. }
  4288.  
  4289. const results = await Promise.all(promises);
  4290.  
  4291. for (let j = i; j < endIndex; j++) {
  4292. const result = results[j - i];
  4293. let className = "rating_by_clist_color9";
  4294. let keys = Object.keys(ratingClassMap);
  4295. for (let k = 0; k < keys.length; k++) {
  4296. if (result.rating < keys[k]) {
  4297. className = ratingClassMap[keys[k - 1]];
  4298. break;
  4299. }
  4300. }
  4301.  
  4302. const $tds = $($trs[j]).find('td');
  4303. $($tds[0]).find('a').after(`<div class="ratingBadges ${className}"><span class="rating">${result.rating}</span></div>`);
  4304. }
  4305.  
  4306. // 延时100毫秒
  4307. // await new Promise(resolve => setTimeout(resolve, 100));
  4308. }
  4309. }
  4310. // problem页显示Rating
  4311. async function showRatingByClist_problem() {
  4312. if (!await checkCookie()) return;
  4313. creatRatingCss(false);
  4314.  
  4315. let problem = $('.header .title').eq(0).text().replace(/[\s\S]*?. /, '');
  4316. let problem_url = window.location.href;
  4317. if (problem_url.includes('/contest/')) {
  4318. problem_url = problem_url.replace(/\/contest\/(\d+)\/problem\/(\w+)[^\w]*/, '/contest/$1/problem/$2');
  4319. } else {
  4320. problem_url = problem_url.replace(/\/problemset\/problem\/(\d+)\/(\w+)/, '/contest/$1/problem/$2');
  4321. }
  4322. if (is_mSite) problem_url = problem_url.replace(/\/\/(\w+).codeforces.com/, '//codeforces.com'); // 轻量站
  4323. let contest = $('#sidebar').children().first().find('.rtable th').first().text();
  4324. let result;
  4325. try {
  4326. result = await getRating(problem, problem_url, contest);
  4327. } catch (error) {
  4328. console.warn(error);
  4329. return;
  4330. }
  4331.  
  4332. let className = "rating_by_clist_color9";
  4333. let keys = Object.keys(ratingClassMap);
  4334. for (let i = 0; i < keys.length; i++) {
  4335. if (result.rating < keys[i]) {
  4336. className = ratingClassMap[keys[i - 1]];
  4337. break;
  4338. }
  4339. }
  4340. const RatingHtml = $(`<a id="problemLink" href="https://clist.by/problems/?search=${result.problem}&resource=1" target="_blank">
  4341. <button style="height: 25px;" class="html2mdButton ratingBadges ${className}">
  4342. ${clistIcon}<span style="padding: 1px 0px 0px 5px;">${result.rating}</span></button>
  4343. </a>`);
  4344. if ($('#CF2luoguPanel').length > 0) {
  4345. $('#CF2luoguPanel').append(RatingHtml);
  4346. } else {
  4347. const panelElement = $("<div>")
  4348. .addClass("html2md-panel")
  4349. .attr("id", "CF2luoguPanel");
  4350. if (is_mSite) {
  4351. panelElement.insertBefore('.problem-statement');
  4352. } else {
  4353. panelElement.insertBefore('.problemindexholder');
  4354. }
  4355. panelElement.append(RatingHtml);
  4356. }
  4357. }
  4358.  
  4359. // cf赛制榜单重新着色
  4360. function recolorStandings() {
  4361. function getColorValue(value) {
  4362. value = Math.max(0, Math.min(1, value));
  4363.  
  4364. const scale = chroma.scale(['#b71c1c', '#ff9800', '#ffc107', '#00aa00']).mode('lch').domain([0, 0.45, 0.7, 1]);
  4365. return scale(value).hex();
  4366. }
  4367. var maxScores = $('.standings tr:first th:nth-child(n+5)')
  4368. .map(function () {
  4369. return $(this).find('span').text();
  4370. })
  4371. .get();
  4372. if (maxScores.every(score => score === '')) return;
  4373. $('.standings tr:not(:first):not(:last)').each(function () {
  4374. var thElements = $(this).find('td:nth-child(n+5)');
  4375. thElements.each(function (index) {
  4376. var spanElement = $(this).find('span:first');
  4377. var value = parseInt(spanElement.text());
  4378. if (value <= 0) return;
  4379. var colorValue = getColorValue(value / maxScores[index]);
  4380. spanElement.css('color', colorValue);
  4381. });
  4382. });
  4383. }
  4384.  
  4385. // 等待Latex渲染队列全部完成
  4386. function waitUntilIdleThenDo(callback) {
  4387. var intervalId = setInterval(function () {
  4388. var queue = MathJax.Hub.queue;
  4389. if (queue.pending === 0 && queue.running === 0) {
  4390. clearInterval(intervalId);
  4391. callback();
  4392. }
  4393. }, 100);
  4394. }
  4395.  
  4396. // 字数超限确认
  4397. function showWordsExceededDialog(button, textLength, realTextLength) {
  4398. return new Promise(resolve => {
  4399. const styleElement = GM_addStyle(darkenPageStyle);
  4400. $(button).removeClass("translated");
  4401. $(button).text("字数超限");
  4402. $(button).css("cursor", "not-allowed");
  4403. $(button).prop("disabled", true);
  4404. let htmlString = `
  4405. <div class="CFBetter_modal">
  4406. <h2>字符数超限! </h2>
  4407. <p>即将翻译的内容共 <strong>${realTextLength}</strong> 字符</p>
  4408. <p>这超出了当前翻译服务的 <strong>${textLength}</strong> 字符上限,请更换翻译服务,或在设置面板中开启“分段翻译”</p>
  4409. <div style="display:flex; padding:5px 0px; align-items: center;">
  4410. `+ helpCircleHTML + `
  4411. <p>
  4412. 注意,可能您选择了错误的翻译按钮<br>
  4413. 由于实现方式,区域中会出现多个翻译按钮,请点击更小的子区域中的翻译按钮
  4414. </p>
  4415. </div>
  4416. <p>您确定要继续翻译吗?</p>
  4417. <div class="buttons">
  4418. <button id="continueButton">继续</button><button id="cancelButton">取消</button>
  4419. </div>
  4420. </div>
  4421. `;
  4422. $('body').before(htmlString);
  4423. $("#continueButton").click(function () {
  4424. $(styleElement).remove();
  4425. $('.CFBetter_modal').remove();
  4426. resolve(true);
  4427. });
  4428. $("#cancelButton").click(function () {
  4429. $(styleElement).remove();
  4430. $('.CFBetter_modal').remove();
  4431. resolve(false);
  4432. });
  4433. });
  4434. }
  4435.  
  4436. //跳过折叠块确认
  4437. function skiFoldingBlocks() {
  4438. return new Promise(resolve => {
  4439. const styleElement = GM_addStyle(darkenPageStyle);
  4440. let htmlString = `
  4441. <div class="CFBetter_modal">
  4442. <h2>是否跳过折叠块?</h2>
  4443. <p></p>
  4444. <div style="display:grid; padding:5px 0px; align-items: center;">
  4445. <p>
  4446. 即将翻译的区域中包含折叠块,折叠块可能是代码,通常不需要翻译,现在您需要选择是否跳过这些折叠块,
  4447. </p>
  4448. <p>
  4449. 如果其中有您需要翻译的折叠块,可以稍后再单独点击这些折叠块内的翻译按钮进行翻译
  4450. </p>
  4451. </div>
  4452. <p>要跳过折叠块吗?(建议选择跳过)</p>
  4453. <div class="buttons">
  4454. <button id="cancelButton">否</button><button id="skipButton">跳过</button>
  4455. </div>
  4456. </div>
  4457. `;
  4458. $('body').before(htmlString);
  4459. $("#skipButton").click(function () {
  4460. $(styleElement).remove();
  4461. $('.CFBetter_modal').remove();
  4462. resolve(true);
  4463. });
  4464. $("#cancelButton").click(function () {
  4465. $(styleElement).remove();
  4466. $('.CFBetter_modal').remove();
  4467. resolve(false);
  4468. });
  4469. });
  4470. }
  4471.  
  4472. // latex替换
  4473. function replaceBlock(text, matches, replacements) {
  4474. try {
  4475. for (let i = 0; i < matches.length; i++) {
  4476. let match = matches[i];
  4477. let replacement = '';
  4478. if (replaceSymbol === "1") {
  4479. replacement = `【${i + 1}】`;
  4480. } else if (replaceSymbol === "2") {
  4481. replacement = `{${i + 1}}`;
  4482. } else if (replaceSymbol === "3") {
  4483. replacement = `[${i + 1}]`;
  4484. }
  4485. text = text.replace(match, replacement);
  4486. replacements[replacement] = match;
  4487. }
  4488. } catch (e) { }
  4489. return text;
  4490. }
  4491.  
  4492. // latex还原
  4493. function recoverBlock(translatedText, matches, replacements) {
  4494. for (let i = 0; i < matches.length; i++) {
  4495. let match = matches[i];
  4496. let replacement = replacements[`【${i + 1}】`] || replacements[`[${i + 1}]`] || replacements[`{${i + 1}}`];
  4497.  
  4498. let latexMatch = '\\$\\$([\\s\\S]*?)\\$\\$|\\$(.*?)\\$|\\$([\\s\\S]*?)\\$|';
  4499.  
  4500. let regex = new RegExp(latexMatch + `【\\s*${i + 1}\\s*】|\\[\\s*${i + 1}\\s*\\]|{\\s*${i + 1}\\s*}`, 'g');
  4501. translatedText = translatedText.replace(regex, function (match, p1, p2, p3) {
  4502. // LaTeX中的不替换
  4503. if (p1 || p2 || p3) {
  4504. return match;
  4505. }
  4506. return replacement;
  4507. });
  4508.  
  4509.  
  4510. regex = new RegExp(latexMatch + `【\\s*${i + 1}(?![】\\d])|(?<![【\\d])${i + 1}\\s*】|\\[\\s*${i + 1}(?![\\]\\d])|(?<![\\[\\d])${i + 1}\\s*\\]|{\\s*${i + 1}(?![}\\d])|(?<![{\\d])${i + 1}\\s*}`, 'g');
  4511. translatedText = translatedText.replace(regex, function (match, p1, p2, p3) {
  4512. // LaTeX中的不替换
  4513. if (p1 || p2 || p3) {
  4514. return match;
  4515. }
  4516. return " " + replacement;
  4517. });
  4518. }
  4519. return translatedText;
  4520. }
  4521.  
  4522.  
  4523. // 翻译框/翻译处理器
  4524. var translatedText = "";
  4525. async function translateProblemStatement(text, element_node, button, is_comment) {
  4526. let status = 0;
  4527. let id = getRandomNumber(8);
  4528. let matches = [];
  4529. let replacements = {};
  4530. // 创建元素并放在element_node的后面
  4531. const translateDiv = document.createElement('div');
  4532. translateDiv.setAttribute('id', id);
  4533. translateDiv.classList.add('translate-problem-statement');
  4534. const spanElement = document.createElement('span');
  4535. translateDiv.appendChild(spanElement);
  4536. element_node.insertAdjacentElement('afterend', translateDiv);
  4537.  
  4538. // 替换latex公式
  4539. if (is_oldLatex) {
  4540. //去除开头结尾的<p>标签
  4541. text = text.replace(/^<p>/i, "");
  4542. text = text.replace(/<\/p>$/i, "");
  4543. let regex = /<span\s+class="tex-span">.*?<\/span>/gi;
  4544. matches = matches.concat(text.match(regex));
  4545. text = replaceBlock(text, matches, replacements);
  4546. } else if (translation != "openai") {
  4547. // 使用GPT翻译时不必替换latex公式
  4548. let regex = /\$\$([\s\S]*?)\$\$|\$(.*?)\$|\$([\s\S]*?)\$/g;
  4549. matches = matches.concat(text.match(regex));
  4550. text = replaceBlock(text, matches, replacements);
  4551. }
  4552.  
  4553. // 字符数上限
  4554. const translationLimits = {
  4555. deepl: 5000,
  4556. iflyrec: 2000,
  4557. youdao: 600,
  4558. google: 5000,
  4559. caiyun: 5000
  4560. };
  4561. if (translationLimits.hasOwnProperty(translation) && text.length > translationLimits[translation]) {
  4562. const shouldContinue = await showWordsExceededDialog(button, translationLimits[translation], text.length);
  4563. if (!shouldContinue) {
  4564. status = 1;
  4565. return {
  4566. translateDiv: translateDiv,
  4567. status: status
  4568. };
  4569. }
  4570. }
  4571.  
  4572. // 翻译
  4573. async function translate(translation) {
  4574. try {
  4575. if (translation == "deepl") {
  4576. translateDiv.innerHTML = "正在使用 deepl 翻译中……请稍等";
  4577. translatedText = await translate_deepl(text);
  4578. } else if (translation == "iflyrec") {
  4579. translateDiv.innerHTML = "正在使用 讯飞听见 翻译中……请稍等";
  4580. translatedText = await translate_iflyrec(text);
  4581. } else if (translation == "youdao") {
  4582. translateDiv.innerHTML = "正在使用 有道 翻译中……请稍等";
  4583. translatedText = await translate_youdao_mobile(text);
  4584. } else if (translation == "google") {
  4585. translateDiv.innerHTML = "正在使用 google 翻译中……请稍等";
  4586. translatedText = await translate_gg(text);
  4587. } else if (translation == "caiyun") {
  4588. translateDiv.innerHTML = "正在使用 彩云小译 翻译中……请稍等";
  4589. await translate_caiyun_startup();
  4590. translatedText = await translate_caiyun(text);
  4591. } else if (translation == "openai") {
  4592. translateDiv.innerHTML = "正在使用 ChatGPT 翻译中……" +
  4593. "<br><br>应用的配置:" + opneaiConfig.configurations[opneaiConfig.choice].note +
  4594. "<br><br>使用 ChatGPT 翻译需要很长的时间,请耐心等待";
  4595. translatedText = await translate_openai(text);
  4596.  
  4597. }
  4598. if (/^翻译出错/.test(translatedText)) status = 2;
  4599. } catch (error) {
  4600. status = 2;
  4601. translatedText = error;
  4602. }
  4603. }
  4604.  
  4605. if (is_comment && commentTranslationChoice != "0") await translate(commentTranslationChoice);
  4606. else await translate(translation);
  4607.  
  4608. // 还原latex公式
  4609. translatedText = translatedText.replace(/】\s*【/g, '】 【');
  4610. translatedText = translatedText.replace(/\]\s*\[/g, '] [');
  4611. translatedText = translatedText.replace(/\}\s*\{/g, '} {');
  4612. if (is_oldLatex) {
  4613. translatedText = "<p>" + translatedText + "</p>";
  4614. translatedText = recoverBlock(translatedText, matches, replacements);
  4615. } else if (translation != "openai") {
  4616. translatedText = recoverBlock(translatedText, matches, replacements);
  4617. }
  4618.  
  4619. // 结果复制按钮
  4620. if (!is_oldLatex) {
  4621. // 创建一个隐藏的元素来保存 translatedText 的值
  4622. var textElement = document.createElement("div");
  4623. textElement.style.display = "none";
  4624. textElement.textContent = translatedText;
  4625. translateDiv.parentNode.insertBefore(textElement, translateDiv);
  4626.  
  4627. // panel
  4628. var panelDiv = document.createElement("div");
  4629. $(panelDiv).addClass("translate-problem-statement-panel");
  4630. // 收起按钮
  4631. var closeButton = document.createElement("div");
  4632. closeButton.innerHTML = putawayIcon;
  4633. $(closeButton).addClass("borderlessButton");
  4634. $(panelDiv).append(closeButton);
  4635. // 复制按钮
  4636. var copyButton = document.createElement("div");
  4637. copyButton.innerHTML = copyIcon;
  4638. $(copyButton).addClass("borderlessButton");
  4639. $(panelDiv).append(copyButton);
  4640.  
  4641. var buttonState = "expand";
  4642. closeButton.addEventListener("click", function () {
  4643. if (buttonState === "expand") {
  4644. this.innerHTML = unfoldIcon;
  4645. $(translateDiv).css({
  4646. display: "none",
  4647. transition: "height 2s"
  4648. });
  4649. buttonState = "collapse";
  4650. } else if (buttonState === "collapse") {
  4651. // 执行收起操作
  4652. this.innerHTML = putawayIcon;
  4653. $(translateDiv).css({
  4654. display: "",
  4655. transition: "height 2s"
  4656. });
  4657. buttonState = "expand";
  4658. }
  4659. });
  4660.  
  4661. copyButton.addEventListener("click", function () {
  4662. var translatedText = textElement.textContent;
  4663. GM_setClipboard(translatedText);
  4664. // $(this).addClass("copied").text("Copied");
  4665. // // 更新复制按钮文本
  4666. // setTimeout(() => {
  4667. // $(this).removeClass("copied");
  4668. // $(this).text("Copy");
  4669. // }, 2000);
  4670. });
  4671. translateDiv.parentNode.insertBefore(panelDiv, translateDiv);
  4672. }
  4673.  
  4674. // 转义LaTex中的特殊符号
  4675. if (!is_oldLatex) {
  4676. const escapeRules = [
  4677. { pattern: /(?<!\\)>(?!\s)/g, replacement: " &gt; " }, // >符号
  4678. { pattern: /(?<!\\)</g, replacement: " &lt; " }, // <符号
  4679. { pattern: /(?<!\\)\*/g, replacement: " &#42; " }, // *符号
  4680. { pattern: /(?<!\\)_/g, replacement: " &#95; " }, // _符号
  4681. { pattern: /(?<!\\)\\\\(?=\s)/g, replacement: "\\\\\\\\" }, // \\符号
  4682. { pattern: /(?<!\\)\\(?![\\a-zA-Z0-9])/g, replacement: "\\\\" }, // \符号
  4683. ];
  4684.  
  4685. let latexMatches = [...translatedText.matchAll(/\$\$([\s\S]*?)\$\$|\$(.*?)\$|\$([\s\S]*?)\$/g)];
  4686.  
  4687. for (const match of latexMatches) {
  4688. const matchedText = match[0];
  4689. var escapedText = matchedText;
  4690.  
  4691. for (const rule of escapeRules) {
  4692. escapedText = escapedText.replaceAll(rule.pattern, rule.replacement);
  4693. }
  4694. escapedText = escapedText.replace(/\$\$/g, "$$$$$$$$");// $$符号(因为后面需要作为replacement)
  4695. translatedText = translatedText.replace(matchedText, escapedText);
  4696. }
  4697. }
  4698.  
  4699. // 使符合mathjx的转换语法
  4700. const mathjaxRuleMap = [
  4701. { pattern: /\$/g, replacement: "$$$$$$" }, // $$ 行间
  4702. ];
  4703. mathjaxRuleMap.forEach(({ pattern, replacement }) => {
  4704. translatedText = translatedText.replace(pattern, replacement);
  4705. });
  4706.  
  4707. // markdown修正
  4708. const mdRuleMap = [
  4709. { pattern: /(\s_[\u4e00-\u9fa5]+_)([\u4e00-\u9fa5]+)/g, replacement: "$1 $2" }, // 斜体
  4710. { pattern: /(_[\u4e00-\u9fa5]+_\s)([\u4e00-\u9fa5]+)/g, replacement: " $1$2" },
  4711. { pattern: /(_[\u4e00-\u9fa5]+_)([\u4e00-\u9fa5]+)/g, replacement: " $1 $2" },
  4712. { pattern: /(([\s\S]*?))/g, replacement: "($1)" }, // 中文()
  4713. // { pattern: /:/g, replacement: ":" }, // 中文:
  4714. { pattern: /\*\* (.*?) \*\*/g, replacement: "\*\*$1\*\*" } // 加粗
  4715. ];
  4716. mdRuleMap.forEach(({ pattern, replacement }) => {
  4717. translatedText = translatedText.replace(pattern, replacement);
  4718. });
  4719.  
  4720. // 更新
  4721. if (is_oldLatex) {
  4722. // oldlatex
  4723. translatedText = $.parseHTML(translatedText);
  4724. $(translateDiv).empty().append($(translatedText));
  4725. return {
  4726. translateDiv: translateDiv,
  4727. status: status
  4728. };
  4729. } else {
  4730. // 渲染MarkDown
  4731. var md = window.markdownit();
  4732. var html = md.render(translatedText);
  4733. translateDiv.innerHTML = html;
  4734. // 渲染Latex
  4735. MathJax.Hub.Queue(["Typeset", MathJax.Hub, translateDiv]);
  4736.  
  4737. return {
  4738. translateDiv: translateDiv,
  4739. status: status,
  4740. copyDiv: textElement,
  4741. panelDiv: panelDiv
  4742. };
  4743. }
  4744.  
  4745. }
  4746.  
  4747. // ChatGPT
  4748. async function translate_openai(raw) {
  4749. var openai_retext = "";
  4750. var data;
  4751. if (is_oldLatex) {
  4752. data = {
  4753. model: (openai_model !== null && openai_model !== "") ? openai_model : 'gpt-3.5-turbo',
  4754. messages: [{
  4755. role: "user",
  4756. content: "请将下面的文本翻译为中文,这是一道编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的【】、HTML标签本身以及其中的内容不翻译不变动,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw
  4757. }],
  4758. temperature: 0.7,
  4759. ...Object.assign({}, ...openai_data)
  4760. };
  4761. } else {
  4762. data = {
  4763. model: (openai_model !== null && openai_model !== "") ? openai_model : 'gpt-3.5-turbo',
  4764. messages: [{
  4765. role: "user",
  4766. content: "请将下面的文本翻译为中文,这是一道编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw
  4767. }],
  4768. temperature: 0.7
  4769. };
  4770. };
  4771. return new Promise(function (resolve, reject) {
  4772. GM_xmlhttpRequest({
  4773. method: 'POST',
  4774. url: (openai_proxy !== null && openai_proxy !== "") ? openai_proxy : 'https://api.openai.com/v1/chat/completions',
  4775.  
  4776. data: JSON.stringify(data),
  4777. headers: {
  4778. 'Content-Type': 'application/json',
  4779. 'Authorization': 'Bearer ' + openai_key,
  4780. ...Object.assign({}, ...openai_header)
  4781. },
  4782. responseType: 'json',
  4783. onload: function (response) {
  4784. if (!response.response) {
  4785. reject("发生了未知的错误,如果你启用了代理API,请确认是否填写正确,并确保代理能够正常工作。\n\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈 请注意打码响应报文的敏感部分\n\n响应报文:" + JSON.stringify(response));
  4786. }
  4787. else if (!response.response.choices || response.response.choices.length < 1 || !response.response.choices[0].message) {
  4788. resolve("翻译出错,请重试\n\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈 \n\n报错信息:" + JSON.stringify(response.response, null, '\n'));
  4789. } else {
  4790. openai_retext = response.response.choices[0].message.content;
  4791. resolve(openai_retext);
  4792. }
  4793. },
  4794. onerror: function (response) {
  4795. reject("发生了未知的错误,请确认你是否能正常访问OpenAi的接口,如果使用代理API,请检查是否正常工作\n\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈 请注意打码响应报文的敏感部分\n\n响应报文:" + JSON.stringify(response));
  4796. },
  4797. });
  4798. });
  4799. }
  4800.  
  4801. //--谷歌翻译--start
  4802. async function translate_gg(raw) {
  4803. return new Promise((resolve, reject) => {
  4804. const url = 'https://translate.google.com/m';
  4805. const params = `tl=zh-CN&q=${encodeURIComponent(raw)}`;
  4806.  
  4807. GM_xmlhttpRequest({
  4808. method: 'GET',
  4809. url: `${url}?${params}`,
  4810. onload: function (response) {
  4811. const html = response.responseText;
  4812. const translatedText = $(html).find('.result-container').text();
  4813. resolve(translatedText);
  4814. },
  4815. onerror: function (response) {
  4816. reject("发生了未知的错误,请确认你是否能正常访问Google翻译,\n\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈 请注意打码报错信息的敏感部分\n\n响应报文:" + JSON.stringify(response))
  4817. }
  4818. });
  4819. });
  4820. }
  4821. //--谷歌翻译--end
  4822.  
  4823. //--有道翻译m--start
  4824. async function translate_youdao_mobile(raw) {
  4825. const options = {
  4826. method: "POST",
  4827. url: 'http://m.youdao.com/translate',
  4828. data: "inputtext=" + encodeURIComponent(raw) + "&type=AUTO",
  4829. anonymous: true,
  4830. headers: {
  4831. "Content-Type": "application/x-www-form-urlencoded",
  4832. 'Host': 'm.youdao.com',
  4833. 'Origin': 'http://m.youdao.com',
  4834. 'Referer': 'http://m.youdao.com/translate',
  4835. }
  4836. }
  4837. return await BaseTranslate('有道翻译mobile', raw, options, res => /id="translateResult">\s*?<li>([\s\S]*?)<\/li>\s*?<\/ul/.exec(res)[1])
  4838. }
  4839. //--有道翻译m--end
  4840.  
  4841. //--彩云翻译--start
  4842. async function translate_caiyun_startup() {
  4843. const browser_id = CryptoJS.MD5(Math.random().toString()).toString();
  4844. sessionStorage.setItem('caiyun_id', browser_id);
  4845. const options = {
  4846. method: "POST",
  4847. url: 'https://api.interpreter.caiyunai.com/v1/user/jwt/generate',
  4848. headers: {
  4849. "Content-Type": "application/json",
  4850. "X-Authorization": "token:qgemv4jr1y38jyq6vhvi",
  4851. "Origin": "https://fanyi.caiyunapp.com",
  4852. },
  4853. data: JSON.stringify({ browser_id }),
  4854. }
  4855. const res = await Request(options);
  4856. sessionStorage.setItem('caiyun_jwt', JSON.parse(res.responseText).jwt);
  4857. }
  4858.  
  4859. async function translate_caiyun(raw) {
  4860. const source = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm";
  4861. const dic = [..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"].reduce((dic, current, index) => { dic[current] = source[index]; return dic }, {});
  4862. // 解码
  4863. const decodeUnicode = str => {
  4864. const decoder = new TextDecoder();
  4865. const data = Uint8Array.from(atob(str), c => c.charCodeAt(0));
  4866. return decoder.decode(data);
  4867. };
  4868. const decoder = line => decodeUnicode([...line].map(i => dic[i] || i).join(""));
  4869. const options = {
  4870. method: "POST",
  4871. url: 'https://api.interpreter.caiyunai.com/v1/translator',
  4872. data: JSON.stringify({
  4873. "source": raw.split('\n'),
  4874. "trans_type": "auto2zh",
  4875. "detect": true,
  4876. "browser_id": sessionStorage.getItem('caiyun_id')
  4877. }),
  4878. headers: {
  4879. "X-Authorization": "token:qgemv4jr1y38jyq6vhvi",
  4880. "T-Authorization": sessionStorage.getItem('caiyun_jwt')
  4881. }
  4882. }
  4883. return await BaseTranslate('彩云小译', raw, options, res => JSON.parse(res).target.map(decoder).join('\n'))
  4884. }
  4885. //--彩云翻译--end
  4886.  
  4887. //--Deepl翻译--start
  4888. function getTimeStamp(iCount) {
  4889. const ts = Date.now();
  4890. if (iCount !== 0) {
  4891. iCount = iCount + 1;
  4892. return ts - (ts % iCount) + iCount;
  4893. } else {
  4894. return ts;
  4895. }
  4896. }
  4897.  
  4898. async function translate_deepl(raw) {
  4899. const id = (Math.floor(Math.random() * 99999) + 100000) * 1000;
  4900. const data = {
  4901. jsonrpc: '2.0',
  4902. method: 'LMT_handle_texts',
  4903. id,
  4904. params: {
  4905. splitting: 'newlines',
  4906. lang: {
  4907. source_lang_user_selected: 'auto',
  4908. target_lang: 'ZH',
  4909. },
  4910. texts: [{
  4911. text: raw,
  4912. requestAlternatives: 3
  4913. }],
  4914. timestamp: getTimeStamp(raw.split('i').length - 1)
  4915. }
  4916. }
  4917. let postData = JSON.stringify(data);
  4918. if ((id + 5) % 29 === 0 || (id + 3) % 13 === 0) {
  4919. postData = postData.replace('"method":"', '"method" : "');
  4920. } else {
  4921. postData = postData.replace('"method":"', '"method": "');
  4922. }
  4923. const options = {
  4924. method: 'POST',
  4925. url: 'https://www2.deepl.com/jsonrpc',
  4926. data: postData,
  4927. headers: {
  4928. 'Content-Type': 'application/json',
  4929. 'Host': 'www2.deepl.com',
  4930. 'Origin': 'https://www.deepl.com',
  4931. 'Referer': 'https://www.deepl.com/',
  4932. },
  4933. anonymous: true,
  4934. nocache: true,
  4935. }
  4936. return await BaseTranslate('Deepl翻译', raw, options, res => JSON.parse(res).result.texts[0].text)
  4937. }
  4938.  
  4939. //--Deepl翻译--end
  4940.  
  4941. //--讯飞听见翻译--end
  4942. async function translate_iflyrec(text) {
  4943. const options = {
  4944. method: "POST",
  4945. url: 'https://www.iflyrec.com/TranslationService/v1/textTranslation',
  4946. data: JSON.stringify({
  4947. "from": "2",
  4948. "to": "1",
  4949. "contents": [{
  4950. "text": text,
  4951. "frontBlankLine": 0
  4952. }]
  4953. }),
  4954. anonymous: true,
  4955. headers: {
  4956. 'Content-Type': 'application/json',
  4957. 'Origin': 'https://www.iflyrec.com',
  4958. },
  4959. responseType: "json",
  4960. };
  4961. return await BaseTranslate('讯飞翻译', text, options, res => JSON.parse(res).biz[0].translateResult.replace(/\\n/g, "\n\n"));
  4962. }
  4963. //--讯飞听见翻译--end
  4964.  
  4965. //--异步请求包装工具--start
  4966. async function PromiseRetryWrap(task, options, ...values) {
  4967. const { RetryTimes, ErrProcesser } = options || {};
  4968. let retryTimes = RetryTimes || 5;
  4969. const usedErrProcesser = ErrProcesser || (err => { throw err });
  4970. if (!task) return;
  4971. while (true) {
  4972. try {
  4973. return await task(...values);
  4974. } catch (err) {
  4975. if (!--retryTimes) {
  4976. console.warn(err);
  4977. return usedErrProcesser(err);
  4978. }
  4979. }
  4980. }
  4981. }
  4982.  
  4983. async function BaseTranslate(name, raw, options, processer) {
  4984. let errtext;
  4985. const toDo = async () => {
  4986. var tmp;
  4987. try {
  4988. const data = await Request(options);
  4989. tmp = data.responseText;
  4990. let result = await processer(tmp);
  4991. return result;
  4992. } catch (err) {
  4993. errtext = tmp;
  4994. throw {
  4995. responseText: tmp,
  4996. err: err
  4997. }
  4998. }
  4999. }
  5000. return await PromiseRetryWrap(toDo, { RetryTimes: 3, ErrProcesser: () => "翻译出错,请查看报错信息,并重试或更换翻译接口\n\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈 请注意打码报错信息的敏感部分\n\n报错信息:" + errtext })
  5001. }
  5002.  
  5003. function Request(options) {
  5004. return new Promise((reslove, reject) => GM_xmlhttpRequest({ ...options, onload: reslove, onerror: reject }))
  5005. }
  5006.  
  5007. //--异步请求包装工具--end
  5008.  
  5009. // 开始
  5010. document.addEventListener("DOMContentLoaded", function () {
  5011. function checkJQuery(retryDelay) {
  5012. if (typeof jQuery === 'undefined') {
  5013. console.warn("JQuery未加载," + retryDelay + "毫秒后重试");
  5014. setTimeout(function () {
  5015. var newRetryDelay = Math.min(retryDelay * 2, 2000);
  5016. checkJQuery(newRetryDelay);
  5017. }, retryDelay);
  5018. } else {
  5019. init();
  5020. settingPanel();
  5021. checkScriptVersion();
  5022. toZH_CN();
  5023. var newElement = $("<div></div>").addClass("alert alert-info CFBetter_alert")
  5024. .html(`Codeforces Better! —— 正在等待页面资源加载……`)
  5025. .css({
  5026. "margin": "1em",
  5027. "text-align": "center",
  5028. "font-weight": "600",
  5029. "position": "relative"
  5030. });
  5031. var tip_SegmentedTranslation = $("<div></div>").addClass("alert alert-error CFBetter_alert")
  5032. .html(`Codeforces Better! —— 注意!分段翻译已开启,这会造成负面效果,
  5033. <p>除非你现在需要翻译超长篇的博客或者题目,否则请前往设置关闭分段翻译</p>`)
  5034. .css({
  5035. "margin": "1em",
  5036. "text-align": "center",
  5037. "font-weight": "600",
  5038. "position": "relative"
  5039. });
  5040.  
  5041. async function processPage() {
  5042. if (showLoading) newElement.html('Codeforces Better! —— 正在等待Latex渲染队列全部完成……');
  5043. await waitUntilIdleThenDo(async function () {
  5044. if (enableSegmentedTranslation) $(".menu-box:first").next().after(tip_SegmentedTranslation); //显示分段翻译警告
  5045. if (showJumpToLuogu && is_problem) CF2luogu();
  5046.  
  5047. Promise.resolve()
  5048. .then(() => {
  5049. if (showLoading && expandFoldingblocks) newElement.html('Codeforces Better! —— 正在展开折叠块……');
  5050. return delay(100).then(() => { if (expandFoldingblocks) ExpandFoldingblocks() });
  5051. })
  5052. .then(() => {
  5053. if (showLoading && commentPaging) newElement.html('Codeforces Better! —— 正在对评论区分页……');
  5054. return delay(100).then(() => { if (commentPaging) CommentPagination() });
  5055. })
  5056. .then(() => {
  5057. if (showLoading) newElement.html('Codeforces Better! —— 正在加载按钮……');
  5058. return delay(100).then(() => addConversionButton());
  5059. })
  5060. .then(async () => {
  5061. if (showLoading && renderPerfOpt) newElement.html('Codeforces Better! —— 正在优化折叠块渲染……');
  5062. await delay(100);
  5063. if (renderPerfOpt) await RenderPerfOpt();
  5064. })
  5065. .then(async () => {
  5066. if (standingsRecolor && is_standings) newElement.html('Codeforces Better! —— 正在为榜单重新着色……');
  5067. await delay(100);
  5068. if (standingsRecolor && is_standings) await recolorStandings();
  5069. })
  5070. .then(async () => {
  5071. await delay(100);
  5072. if (showClistRating_contest && is_contest) {
  5073. newElement.html('Codeforces Better! —— 正在加载Clist数据……');
  5074. await showRatingByClist_contest();
  5075. }
  5076. if (showClistRating_problemset && is_problemset) {
  5077. newElement.html('Codeforces Better! —— 正在加载Clist数据……');
  5078. await showRatingByClist_problemset();
  5079. }
  5080. if (showClistRating_problem && is_problem) {
  5081. newElement.html('Codeforces Better! —— 正在加载Clist数据……');
  5082. await showRatingByClist_problem();
  5083. }
  5084. })
  5085. .then(() => {
  5086. alertZh();
  5087. if (showLoading) {
  5088. newElement.html('Codeforces Better! —— 加载已完成');
  5089. newElement.removeClass('alert-info').addClass('alert-success');
  5090. setTimeout(function () {
  5091. newElement.remove();
  5092. }, 3000);
  5093. }
  5094. })
  5095. .catch((error) => {
  5096. console.warn(error);
  5097. });
  5098. });
  5099. }
  5100.  
  5101. function delay(ms) {
  5102. return new Promise((resolve) => setTimeout(resolve, ms));
  5103. }
  5104.  
  5105. if (showLoading) {
  5106. if (is_mSite) $("header").after(newElement);
  5107. else $(".menu-box:first").next().after(newElement);
  5108. }
  5109.  
  5110. if (loaded) {
  5111. processPage();
  5112. } else {
  5113. // 页面完全加载完成后执行
  5114. window.onload = function () {
  5115. processPage();
  5116. };
  5117. }
  5118. }
  5119. }
  5120. checkJQuery(50);
  5121. });
  5122.  
  5123. // 配置自动迁移代码(将在10个小版本后移除-1.66)
  5124. if (GM_getValue("openai_key") || GM_getValue("api2d_key")) {
  5125. const newConfig = { "choice": -1, "configurations": [] };
  5126. if (GM_getValue("openai_key")) {
  5127. let config1 = {
  5128. "note": "我的配置1",
  5129. "model": GM_getValue("openai_model") || "",
  5130. "key": GM_getValue("openai_key"),
  5131. "proxy": GM_getValue("openai_proxy") || "",
  5132. "_header": "",
  5133. "_data": ""
  5134. }
  5135. if (GM_getValue("translation") === "openai") newConfig.choice = 0;
  5136. newConfig.configurations.push(config1);
  5137. }
  5138. if (GM_getValue("api2d_key")) {
  5139. let config2 = {
  5140. "note": "api2d",
  5141. "model": GM_getValue("api2d_model"),
  5142. "key": GM_getValue("api2d_key"),
  5143. "proxy": GM_getValue("api2d_request_entry") + '/v1/chat/completions',
  5144. "_header": GM_getValue("x_api2d_no_cache") ? "" : " x-api2d-no-cache : 1",
  5145. "_data": ""
  5146. }
  5147. if (GM_getValue("translation") === "api2d") {
  5148. if (GM_getValue("openai_key")) newConfig.choice = 1;
  5149. else newConfig.choice = 0;
  5150. }
  5151. newConfig.configurations.push(config2);
  5152. }
  5153. GM_setValue("chatgpt-config", newConfig);
  5154. const keysToDelete = ["openai_key", "openai_model", "openai_proxy", "api2d_key", "api2d_model", "api2d_request_entry", "x_api2d_no_cache", "showOpneAiAdvanced"];
  5155. keysToDelete.forEach(key => {
  5156. if (GM_getValue(key) != undefined) GM_deleteValue(key);
  5157. });
  5158. if (GM_getValue("translation") === "api2d") GM_setValue("translation", "openai");
  5159. location.reload();
  5160. }
  5161. // 配置自动迁移代码(将在10个小版本后移除-1.71)
  5162. if (GM_getValue("darkMode") === true || GM_getValue("darkMode") === false) {
  5163. GM_setValue("darkMode", "follow");
  5164. location.reload();
  5165. }
  5166.