Codeforces Better!

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

当前为 2023-09-14 提交的版本,查看 最新版本

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址