Codeforces Better!

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

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

  1. // ==UserScript==
  2. // @name Codeforces Better!
  3. // @namespace https://greasyfork.org/users/747162
  4. // @version 1.60
  5. // @description Codeforces界面汉化、黑暗模式支持、题目翻译,markdown视图,一键复制题目,跳转到洛谷、评论区分页
  6. // @author 北极小狐
  7. // @match *://*.codeforces.com/*
  8. // @run-at document-start
  9. // @connect www2.deepl.com
  10. // @connect m.youdao.com
  11. // @connect translate.google.com
  12. // @connect openai.api2d.net
  13. // @connect api.openai.com
  14. // @connect www.luogu.com.cn
  15. // @connect greasyfork.org
  16. // @connect *
  17. // @grant GM_xmlhttpRequest
  18. // @grant GM_info
  19. // @grant GM_setValue
  20. // @grant GM_getValue
  21. // @grant GM_deleteValue
  22. // @grant GM_addStyle
  23. // @grant GM_cookie
  24. // @grant GM_setClipboard
  25. // @icon https://aowuucdn.oss-cn-beijing.aliyuncs.com/codeforces.png
  26. // @require https://cdn.staticfile.org/turndown/7.1.2/turndown.min.js
  27. // @require https://cdn.staticfile.org/markdown-it/13.0.1/markdown-it.min.js
  28. // @license MIT
  29. // @compatible Chrome
  30. // @compatible Firefox
  31. // @compatible Edge
  32. // ==/UserScript==
  33.  
  34. // 状态与初始化
  35. const getGMValue = (key, defaultValue) => {
  36. const value = GM_getValue(key);
  37. if (value === undefined || value === "") {
  38. GM_setValue(key, defaultValue);
  39. return defaultValue;
  40. }
  41. return value;
  42. };
  43. var darkMode = getGMValue("darkMode", 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.  
  1127. // 工具
  1128. // 获取cookie
  1129. function getCookie(name) {
  1130. const cookies = document.cookie.split(";");
  1131. for (let i = 0; i < cookies.length; i++) {
  1132. const cookie = cookies[i].trim();
  1133. const [cookieName, cookieValue] = cookie.split("=");
  1134.  
  1135. if (cookieName === name) {
  1136. return decodeURIComponent(cookieValue);
  1137. }
  1138. }
  1139. return "";
  1140. }
  1141.  
  1142. // 防抖函数
  1143. function debounce(callback) {
  1144. let timer;
  1145. let immediateExecuted = false;
  1146. const delay = 500;
  1147. return function () {
  1148. clearTimeout(timer);
  1149. if (!immediateExecuted) { callback.call(this); immediateExecuted = true; }
  1150. timer = setTimeout(() => { immediateExecuted = false; }, delay);
  1151. };
  1152. }
  1153.  
  1154. // 为元素添加鼠标拖动
  1155. function addDraggable(element) {
  1156. let isDragging = false;
  1157. let initialX, initialY; // 元素的初始位置
  1158. let startX, startY, offsetX, offsetY; // 鼠标起始位置,移动偏移量
  1159. let isSpecialMouseDown = false; // 选取某些元素时不拖动
  1160.  
  1161. element.on('mousedown', function (e) {
  1162. var elem = $(this);
  1163. var elemOffset = elem.offset();
  1164. var centerX = elemOffset.left + elem.outerWidth() / 2;
  1165. var centerY = elemOffset.top + elem.outerHeight() / 2;
  1166. initialX = centerX - window.pageXOffset;
  1167. initialY = centerY - window.pageYOffset;
  1168.  
  1169. isDragging = true;
  1170. startX = e.clientX;
  1171. startY = e.clientY;
  1172.  
  1173. isSpecialMouseDown = $(e.target).is('label, p, input, textarea, span');
  1174. if (isSpecialMouseDown) return;
  1175. $('body').css('cursor', 'all-scroll');
  1176. });
  1177.  
  1178. $(document).on('mousemove', function (e) {
  1179. if (!isDragging) return;
  1180. // 不执行拖动操作
  1181. if ($(e.target).is('label, p, input, textarea, span') || isSpecialMouseDown && !$(e.target).is('input, textarea')) return;
  1182. e.preventDefault();
  1183. offsetX = e.clientX - startX;
  1184. offsetY = e.clientY - startY;
  1185. element.css({ top: initialY + offsetY + 'px', left: initialX + offsetX + 'px' });
  1186. });
  1187.  
  1188. $(document).on('mouseup', function () {
  1189. isDragging = false;
  1190. isSpecialMouseDown = false;
  1191. $('body').css('cursor', 'default');
  1192. });
  1193. }
  1194.  
  1195. // 更新检查
  1196. function checkScriptVersion() {
  1197. function compareVersions(version1 = "0", version2 = "0") {
  1198. const v1Array = String(version1).split(".");
  1199. const v2Array = String(version2).split(".");
  1200. const minLength = Math.min(v1Array.length, v2Array.length);
  1201. let result = 0;
  1202. for (let i = 0; i < minLength; i++) {
  1203. const curV1 = Number(v1Array[i]);
  1204. const curV2 = Number(v2Array[i]);
  1205. if (curV1 > curV2) {
  1206. result = 1;
  1207. break;
  1208. } else if (curV1 < curV2) {
  1209. result = -1;
  1210. break;
  1211. }
  1212. }
  1213. if (result === 0 && v1Array.length !== v2Array.length) {
  1214. const v1IsBigger = v1Array.length > v2Array.length;
  1215. const maxLenArray = v1IsBigger ? v1Array : v2Array;
  1216. for (let i = minLength; i < maxLenArray.length; i++) {
  1217. const curVersion = Number(maxLenArray[i]);
  1218. if (curVersion > 0) {
  1219. v1IsBigger ? result = 1 : result = -1;
  1220. break;
  1221. }
  1222. }
  1223. }
  1224. return result;
  1225. }
  1226.  
  1227. GM_xmlhttpRequest({
  1228. method: "GET",
  1229. url: "https://greasyfork.org/zh-CN/scripts/465777.json",
  1230. timeout: 10 * 1e3,
  1231. onload: function (response) {
  1232. const scriptData = JSON.parse(response.responseText);
  1233. const skipUpdate = getCookie("skipUpdate");
  1234.  
  1235. if (
  1236. scriptData.name === GM_info.script.name &&
  1237. compareVersions(scriptData.version, GM_info.script.version) === 1 &&
  1238. skipUpdate !== "true"
  1239. ) {
  1240. const styleElement = GM_addStyle(darkenPageStyle);
  1241. $("body").append(`
  1242. <div id='update_panel'>
  1243. <h3>${GM_info.script.name}有新版本!</h3>
  1244. <hr>
  1245. <div class='update_panel_menu'>
  1246. <span class ='tip'>版本信息:${GM_info.script.version} ${scriptData.version}</span>
  1247. </div>
  1248. <br>
  1249. <div id="skip_menu">
  1250. <div class="help_tip">
  1251. `+ helpCircleHTML + `
  1252. <div class="tip_text">
  1253. <p><b>更新遇到了问题?</b></p>
  1254. <p>由于 Greasyfork 平台的原因,当新版本刚发布时,点击 Greasyfork 上的更新按钮<u>可能</u>会出现<u>实际更新/安装的却是上一个版本</u>的情况</p>
  1255. <p>通常你只需要稍等几分钟,然后再次前往更新/安装即可</p>
  1256. <p>你也可以<u>点击下方按钮,在本次浏览器会话期间将不再提示更新</u></p>
  1257. <button id='skip_update' class='html2mdButton'>暂不更新</button>
  1258. </div>
  1259. </div>
  1260. <button id='updating'><a target="_blank" href="${scriptData.url}">更新</a></button>
  1261. </div>
  1262. </div>
  1263. `);
  1264.  
  1265. $("#skip_update").click(function () {
  1266. document.cookie = "skipUpdate=true; expires=session; path=/";
  1267. styleElement.remove();
  1268. $("#update_panel").remove();
  1269. });
  1270. }
  1271. }
  1272. });
  1273.  
  1274. };
  1275.  
  1276. // 汉化替换
  1277. function toZH_CN() {
  1278. if (!bottomZh_CN) return;
  1279. // 设置语言为zh
  1280. var htmlTag = document.getElementsByTagName("html")[0];
  1281. htmlTag.setAttribute("lang", "zh-CN");
  1282.  
  1283. // 文本节点遍历替换
  1284. function traverseTextNodes(node, rules) {
  1285. if (!node) return;
  1286. if (node.nodeType === Node.TEXT_NODE) {
  1287. rules.forEach(rule => {
  1288. const regex = new RegExp(rule.match, 'g');
  1289. node.textContent = node.textContent.replace(regex, rule.replace);
  1290. });
  1291. } else {
  1292. $(node).contents().each((_, child) => traverseTextNodes(child, rules));
  1293. }
  1294. }
  1295.  
  1296. // 严格
  1297. function strictTraverseTextNodes(node, rules) {
  1298. if (!node) return;
  1299. if (node.nodeType === Node.TEXT_NODE) {
  1300. const nodeText = node.textContent.trim();
  1301. rules.forEach(rule => {
  1302. if (nodeText === rule.match) {
  1303. node.textContent = rule.replace;
  1304. }
  1305. });
  1306. } else {
  1307. $(node).contents().each((_, child) => strictTraverseTextNodes(child, rules));
  1308. }
  1309. }
  1310.  
  1311. const rules1 = [
  1312. { match: 'Virtual participation', replace: '参加虚拟重现赛' },
  1313. { match: 'Enter', replace: '进入' },
  1314. { match: 'Current standings', replace: '当前榜单' },
  1315. { match: 'Final standings', replace: '最终榜单' },
  1316. { match: 'Preliminary results', replace: '初步结果' },
  1317. { match: 'open hacking:', replace: '公开黑客攻击中(即尝试提交数据加强,对已通过的代码重测)' },
  1318. { match: 'School/University/City/Region Championship', replace: '学校/大学/城市/区域比赛' },
  1319. { match: 'Official School Contest', replace: '学校官方比赛' },
  1320. { match: 'Training Contest', replace: '训练赛' },
  1321. { match: 'Training Camp Contest', replace: '训练营比赛' },
  1322. { match: 'Official ICPC Contest', replace: 'ICPC官方比赛' },
  1323. { match: 'Official International Personal Contest', replace: '官方国际个人赛' },
  1324. { match: 'China', replace: '中国' },
  1325. { match: 'Statements', replace: '题目描述' },
  1326. { match: 'in Chinese', replace: '中文' },
  1327. { match: 'Trainings', replace: '训练' },
  1328. { match: 'Prepared by', replace: '编写人' },
  1329. { match: 'Current or upcoming contests', replace: '当前或即将举行的比赛' },
  1330. { match: 'Past contests', replace: '过去的比赛' },
  1331. { match: 'Exclusions', replace: '排除' },
  1332. { match: 'Before start', replace: '距比赛开始还有' },
  1333. { match: 'Before registration', replace: '距报名开始还有' },
  1334. { match: 'Until closing ', replace: '距报名结束还有' },
  1335. { match: 'Before extra registration', replace: '额外报名还未开始' },
  1336. { match: 'Register »', replace: '报名 »' },
  1337. { match: 'Registration completed', replace: '已报名' },
  1338. { match: 'Registration closed', replace: '报名已结束' },
  1339. { match: 'Problems', replace: '问题集' },
  1340. { match: 'Questions about problems', replace: '关于问题的提问' },
  1341. { match: 'Contest status', replace: '比赛状态' },
  1342. ];
  1343. traverseTextNodes($('.datatable'), rules1);
  1344.  
  1345. const rules2 = [
  1346. { match: 'Home', replace: '主页' },
  1347. { match: 'Top', replace: '热门' },
  1348. { match: 'Catalog', replace: '指南目录' },
  1349. { match: 'Contests', replace: '比赛' },
  1350. { match: 'Gym', replace: '训练营' },
  1351. { match: 'Problemset', replace: '题单' },
  1352. { match: 'Groups', replace: '团体' },
  1353. { match: 'Rating', replace: 'Rating(评级)排行榜' },
  1354. { match: 'Edu', replace: '培训' },
  1355. { match: 'Calendar', replace: '日历' },
  1356. { match: 'Help', replace: '帮助' }
  1357. ];
  1358. traverseTextNodes($('.menu-list.main-menu-list'), rules2);
  1359.  
  1360. const rules3 = [
  1361. { match: 'Settings', replace: '设置' },
  1362. { match: 'Blog', replace: '博客' },
  1363. { match: 'Teams', replace: '队伍' },
  1364. { match: 'Submissions', replace: '提交' },
  1365. { match: 'Favourites', replace: '收藏' },
  1366. { match: 'Talks', replace: '私信' },
  1367. { match: 'Contests', replace: '比赛' },
  1368. ];
  1369. traverseTextNodes($('.nav-links'), rules3);
  1370.  
  1371. const rules4 = [
  1372. { match: 'Before contest', replace: '即将进行的比赛' },
  1373. { match: 'Contest is running', replace: '比赛进行中' },
  1374. ];
  1375. traverseTextNodes($('.contest-state-phase'), rules4);
  1376.  
  1377. const rules5 = [
  1378. { match: 'has extra registration', replace: '有额外的报名时期' },
  1379. { 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分钟。' },
  1380. ];
  1381. traverseTextNodes($('.notice'), rules5);
  1382.  
  1383. const rules6 = [
  1384. { match: 'Contribution', replace: '贡献' },
  1385. ];
  1386. traverseTextNodes($('.propertyLinks'), rules6);
  1387.  
  1388. const rules7 = [
  1389. { match: 'Contest history', replace: '比赛历史' },
  1390. ];
  1391. traverseTextNodes($('.contests-table'), rules7);
  1392.  
  1393. const rules8 = [
  1394. { match: 'Register now', replace: '现在报名' },
  1395. { match: 'No tag edit access', replace: '没有标签编辑权限' },
  1396. { match: 'Language:', replace: '语言:' },
  1397. { match: 'Choose file:', replace: '选择文件:' },
  1398. ];
  1399. traverseTextNodes($('.roundbox.sidebox.borderTopRound '), rules8);
  1400.  
  1401. const rules9 = [
  1402. { match: 'Add to exclusions', replace: '添加到排除列表' },
  1403. ];
  1404. traverseTextNodes($('.icon-eye-close.icon-large'), rules9);
  1405.  
  1406. const rules10 = [
  1407. { match: 'Add to exclusions for gym contests filter', replace: '添加训练营过滤器的排除项' },
  1408. ];
  1409. traverseTextNodes($("._ContestFilterExclusionsManageFrame_addExclusionLink"), rules10);
  1410.  
  1411. const rules11 = [
  1412. { match: 'Announcement', replace: '公告' },
  1413. { match: 'Statements', replace: '统计报表' },
  1414. { match: 'Tutorial', replace: '题解' },
  1415. ];
  1416. traverseTextNodes($('.roundbox.sidebox.sidebar-menu.borderTopRound '), rules11);
  1417.  
  1418. const rules12 = [
  1419. { match: 'Problems', replace: '问题' },
  1420. { match: 'Submit Code', replace: '提交代码' },
  1421. { match: 'My Submissions', replace: '我的提交' },
  1422. { match: 'Status', replace: '状态' },
  1423. { match: 'Standings', replace: '榜单' },
  1424. { match: 'Custom Invocation', replace: '自定义调试' },
  1425. { match: 'Common standings', replace: '全部排行' },
  1426. { match: 'Friends standings', replace: '只看朋友' },
  1427. { match: 'Submit', replace: '提交' },
  1428. { match: 'Hacks', replace: '黑客' },
  1429. { match: 'Room', replace: '房间' },
  1430. { match: 'Custom test', replace: '自定义测试' },
  1431. { match: 'Blog', replace: '博客' },
  1432. { match: 'Teams', replace: '队伍' },
  1433. { match: 'Submissions', replace: '提交记录' },
  1434. { match: 'Groups', replace: '团体' },
  1435. { match: 'Favourites', replace: '收藏' },
  1436. { match: 'Contests', replace: '比赛' },
  1437. { match: 'Members', replace: '成员' },
  1438. { match: '问题etting', replace: '参与编写的问题' },
  1439. { match: 'Streams', replace: '直播' },
  1440. { match: 'Gym', replace: '训练营' },
  1441. { match: 'Mashups', replace: '组合混搭' },
  1442. { match: 'Posts', replace: '帖子' },
  1443. { match: 'Comments', replace: '回复' },
  1444. { match: 'Main', replace: '主要的' },
  1445. { match: 'Settings', replace: '设置' },
  1446. { match: 'Lists', replace: '列表' },
  1447. { match: 'General', replace: '基本' },
  1448. { match: 'Sidebar', replace: '侧边栏' },
  1449. { match: 'Social', replace: '社会信息' },
  1450. { match: 'Address', replace: '地址' },
  1451. { match: 'Wallets', replace: '钱包' },
  1452. ];
  1453. traverseTextNodes($('.second-level-menu'), rules12);
  1454. if (is_mSite) {
  1455. traverseTextNodes($('nav'), rules12);
  1456. }
  1457.  
  1458. const rules13 = [
  1459. { match: 'Expand', replace: '展开' }
  1460. ];
  1461. traverseTextNodes($('.topic-toggle-collapse'), rules13);
  1462.  
  1463. const rules14 = [
  1464. { match: 'Full text and comments', replace: '阅读全文/评论' }
  1465. ];
  1466. traverseTextNodes($('.topic-read-more'), rules14);
  1467.  
  1468. const rules15 = [
  1469. { match: 'Switch off editor', replace: '关闭编辑器语法高亮' }
  1470. ];
  1471. traverseTextNodes($('.toggleEditorCheckboxLabel'), rules15);
  1472.  
  1473. const rules16 = [
  1474. { match: 'Registration for the contest', replace: '比赛报名' }
  1475. ];
  1476. traverseTextNodes($('.submit'), rules16);
  1477.  
  1478. const rules17 = [
  1479. { match: 'Difficulty:', replace: '难度:' },
  1480. ];
  1481. traverseTextNodes($('._FilterByTagsFrame_difficulty'), rules17);
  1482.  
  1483. const rules18 = [
  1484. { match: 'Add tag', replace: '添加标签' }
  1485. ];
  1486. traverseTextNodes($('._FilterByTagsFrame_addTagLink'), rules18);
  1487.  
  1488. const rules19 = [
  1489. { match: 'Rating changes for last rounds are temporarily rolled back. They will be returned soon.', replace: '上一轮的评级变化暂时回滚。它们将很快恢复。' },
  1490. { match: 'Reminder: in case of any technical issues, you can use the lightweight website', replace: '提醒:如果出现任何技术问题,您可以使用轻量网站' },
  1491. { match: 'Please subscribe to the official Codeforces channel in Telegram via the link ', replace: '请通过链接订阅Codeforces的官方Telegram频道' }
  1492. ];
  1493. traverseTextNodes($('.alert'), rules19);
  1494.  
  1495. const rules20 = [
  1496. { match: 'Enter', replace: '登录' },
  1497. { match: 'Register', replace: '注册' },
  1498. { match: 'Contest rating', replace: '测试 rating' },
  1499. { match: 'Logout', replace: '退出登录' }
  1500. ];
  1501. traverseTextNodes($('.lang-chooser'), rules20);
  1502.  
  1503. const rules21 = [
  1504. { match: 'Change photo', replace: '更换图片' },
  1505. { match: 'Contest rating', replace: '比赛Rating' },
  1506. { match: 'Contribution', replace: '贡献' },
  1507. { match: 'My friends', replace: '我的好友' },
  1508. { match: 'Change settings', replace: '改变设置' },
  1509. { match: 'Last visit', replace: '最后访问' },
  1510. { match: 'Registered', replace: '注册于' },
  1511. { match: 'Blog entries', replace: '博客条目' },
  1512. { match: 'comments', replace: '评论' },
  1513. { match: 'Write new entry', replace: '编写新条目' },
  1514. { match: 'View my talks', replace: '查看我的私信' },
  1515. { match: 'Talks', replace: '私信' },
  1516. { match: 'Send message', replace: '发送消息' },
  1517. ];
  1518. traverseTextNodes($('.userbox'), rules21);
  1519.  
  1520. const rules22 = [
  1521. { match: 'Reset', replace: '重置' },
  1522. ];
  1523. traverseTextNodes($('#vote-reset-filterDifficultyLowerBorder'), rules22);
  1524. traverseTextNodes($('#vote-reset-filterDifficultyUpperBorder'), rules22);
  1525.  
  1526. const rules23 = [
  1527. { match: 'The problem statement has recently been changed.', replace: '题目描述最近已被更改。\n(说明:有极小概率可能是Codeforces Better!插入翻译按钮导致的)' },
  1528. { match: 'View the changes.', replace: '查看更改' },
  1529. ];
  1530. traverseTextNodes($('.alert.alert-info'), rules23);
  1531.  
  1532. const rules24 = [
  1533. { match: 'Fill in the form to login into Codeforces.', replace: '填写表单以登录到Codeforces。' },
  1534. { match: 'You can use', replace: '你也可以使用' },
  1535. { match: 'as an alternative way to enter.', replace: '登录' },
  1536. ];
  1537. traverseTextNodes($('.enterPage'), rules24);
  1538.  
  1539. const rules25 = [
  1540. { match: '\\* To view the complete list, click ', replace: '* 要查看完整列表,请点击' },
  1541. ];
  1542. traverseTextNodes($('.notice.small'), rules25);
  1543.  
  1544. const rules26 = [
  1545. { match: 'Contest type:', replace: '比赛类型:' },
  1546. { match: 'Rated:', replace: '已评级:' },
  1547. { match: 'Tried:', replace: '已尝试' },
  1548. { match: 'Substring:', replace: '关键字' },
  1549. ];
  1550. traverseTextNodes($('.setting-name'), rules26);
  1551.  
  1552. // 元素选择替换
  1553. // 侧栏titled汉化
  1554. (function () {
  1555. var translations = {
  1556. "Pay attention": "→ 注意",
  1557. "Top rated": "→ 评级排行",
  1558. "Top contributors": "→ 贡献者排行",
  1559. "Find user": "→ 查找用户",
  1560. "Recent actions": "→ 最新动态",
  1561. "Training filter": "→ 过滤筛选",
  1562. "Find training": "→ 搜索比赛/问题",
  1563. "Virtual participation": "→ 什么是虚拟参赛",
  1564. "Contest materials": "→ 比赛相关资料",
  1565. "Settings": "→ 设置",
  1566. "Create Mashup Contest": "→ 克隆比赛到组合混搭",
  1567. "Clone Contest to Mashup": "→ 克隆比赛到组合混搭",
  1568. "Create Mashup Contest": "→ 创建混搭比赛",
  1569. "Submit": "→ 提交",
  1570. "Practice": "→ 练习",
  1571. "Problem tags": "→ 问题标签",
  1572. "Filter Problems": "→ 过滤问题",
  1573. "Attention": "→ 注意",
  1574. "Past contests filter": "→ 过去的比赛筛选",
  1575. "About Contest": "→ 关于比赛",
  1576. "Last submissions": "→ 提交历史",
  1577. "Streams": "→ 直播",
  1578. "Coach rights": "→ 教练权限",
  1579. "Advices to fill address": "→ 填写地址的建议",
  1580. "Hacks filter": "→ 黑客过滤器",
  1581. "Score table": "→ 评分表",
  1582. "Contests": "→ 比赛",
  1583. "History": "→ 编辑历史",
  1584. "Login into Codeforces": "登录 Codeforces",
  1585. };
  1586.  
  1587. $(".caption.titled").each(function () {
  1588. var tag = $(this).text();
  1589. for (var property in translations) {
  1590. if (tag.match(property)) {
  1591. $(this).addClass(property);
  1592. $(this).text(translations[property]);
  1593. break;
  1594. }
  1595. }
  1596. });
  1597. })();
  1598. // 题目Tag汉化
  1599. (function () {
  1600. var parentElement = $('._FilterByTagsFrame_addTagLabel');
  1601. var selectElement = parentElement.find('select');
  1602. var translations = {
  1603. "*combine tags by OR": "*按逻辑或组合我选择的标签",
  1604. "combine-tags-by-or": "*按逻辑或组合我选择的标签(combine-tags-by-or)",
  1605. "2-sat": "二分图可满足性问题(2-sat)",
  1606. "binary search": "二分搜索(binary search)",
  1607. "bitmasks": "位掩码(bitmasks)",
  1608. "brute force": "暴力枚举(brute force)",
  1609. "chinese remainder theorem": "中国剩余定理(chinese remainder theorem)",
  1610. "combinatorics": "组合数学(combinatorics)",
  1611. "constructive algorithms": "构造算法(constructive algorithms)",
  1612. "data structures": "数据结构(data structures)",
  1613. "dfs and similar": "深度优先搜索及其变种(dfs and similar)",
  1614. "divide and conquer": "分治算法(divide and conquer)",
  1615. "dp": "动态规划(dp)",
  1616. "dsu": "并查集(dsu)",
  1617. "expression parsing": "表达式解析(expression parsing)",
  1618. "fft": "快速傅里叶变换(fft)",
  1619. "flows": "流(flows)",
  1620. "games": "博弈论(games)",
  1621. "geometry": "计算几何(geometry)",
  1622. "graph matchings": "图匹配(graph matchings)",
  1623. "graphs": "图论(graphs)",
  1624. "greedy": "贪心策略(greedy)",
  1625. "hashing": "哈希表(hashing)",
  1626. "implementation": "实现问题,编程技巧,模拟(implementation)",
  1627. "interactive": "交互性问题(interactive)",
  1628. "math": "数学(math)",
  1629. "matrices": "矩阵(matrices)",
  1630. "meet-in-the-middle": "meet-in-the-middle算法(meet-in-the-middle)",
  1631. "number theory": "数论(number theory)",
  1632. "probabilities": "概率论(probabilities)",
  1633. "schedules": "调度算法(schedules)",
  1634. "shortest paths": "最短路算法(shortest paths)",
  1635. "sortings": "排序算法(sortings)",
  1636. "string suffix structures": "字符串后缀结构(string suffix structures)",
  1637. "strings": "字符串处理(strings)",
  1638. "ternary search": "三分搜索(ternary search)",
  1639. "trees": "树形结构(trees)",
  1640. "two pointers": "双指针算法(two pointers)"
  1641. };
  1642. selectElement.find("option").each(function () {
  1643. var optionValue = $(this).val();
  1644. if (translations[optionValue]) {
  1645. $(this).text(translations[optionValue]);
  1646. }
  1647. });
  1648. $("._FilterByTagsFrame_tagBoxCaption").each(function () {
  1649. var tag = $(this).text();
  1650. if (tag in translations) {
  1651. $(this).text(translations[tag]);
  1652. }
  1653. });
  1654. $(".notice").each(function () {
  1655. var tag = $(this).text();
  1656. if (tag in translations) {
  1657. $(this).text(translations[tag]);
  1658. }
  1659. });
  1660. $(".tag-box").each(function () {
  1661. var tag = $(this).text();
  1662. for (var property in translations) {
  1663. property = property.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
  1664. if (tag.match(property)) {
  1665. $(this).text(translations[property]);
  1666. break;
  1667. }
  1668. }
  1669. });
  1670. })();
  1671. // 题目过滤器选项汉化
  1672. (function () {
  1673. var parentElement = $('#gym-filter-form');
  1674. var selectElement = parentElement.find('div');
  1675. var translations = {
  1676. "Contest type:": "比赛类型:",
  1677. "ICPC region:": "ICPC地区:",
  1678. "Contest format:": "比赛形式:",
  1679. "Order by:": "排序方式:",
  1680. "Secondary order by:": "次要排序方式:",
  1681. "Hide, if participated:": "隐藏我参加过的:",
  1682. };
  1683. selectElement.find("label").each(function () {
  1684. var optionValue = $(this).text();
  1685. if (translations[optionValue]) {
  1686. $(this).text(translations[optionValue]);
  1687. }
  1688. });
  1689. translations = {
  1690. "Season:": "时间范围(年度)",
  1691. "Duration, hours:": "持续时间(小时):",
  1692. "Difficulty:": "难度:"
  1693. };
  1694. selectElement.each(function () {
  1695. var optionValue = $(this).text();
  1696. if (translations[optionValue]) {
  1697. $(this).text(translations[optionValue]);
  1698. }
  1699. });
  1700. })();
  1701. (function () {
  1702. var parentElement = $('.setting-value');
  1703. var selectElement = parentElement.find('select');
  1704. var translations = {
  1705. "Official ACM-ICPC Contest": "ICPC官方比赛",
  1706. "Official School Contest": "学校官方比赛",
  1707. "Opencup Contest": "Opencup比赛",
  1708. "School/University/City/Region Championship": "学校/大学/城市/地区锦标赛",
  1709. "Training Camp Contest": "训练营比赛",
  1710. "Official International Personal Contest": "官方国际个人赛",
  1711. "Training Contest": "训练比赛",
  1712. "ID_ASC": "创建时间(升序)",
  1713. "ID_DESC": "创建时间(降序)",
  1714. "RATING_ASC": "评分(升序)",
  1715. "RATING_DESC": "评分(降序)",
  1716. "DIFFICULTY_ASC": "难度(升序)",
  1717. "DIFFICULTY_DESC": "难度(降序)",
  1718. "START_TIME_ASC": "开始时间(升序)",
  1719. "START_TIME_DESC": "开始时间(降序)",
  1720. "DURATION_ASC": "持续时间(升序)",
  1721. "DURATION_DESC": "持续时间(降序)",
  1722. "POPULARITY_ASC": "热度(升序)",
  1723. "POPULARITY_DESC": "热度(降序)",
  1724. "UPDATE_TIME_ASC": "更新时间(升序)",
  1725. "UPDATE_TIME_DESC": "更新时间(降序)"
  1726. };
  1727. selectElement.find("option").each(function () {
  1728. var optionValue = $(this).val();
  1729. if (translations[optionValue]) {
  1730. $(this).text(translations[optionValue]);
  1731. }
  1732. });
  1733. parentElement = $('.setting-last-value');
  1734. selectElement = parentElement.find('select');
  1735. selectElement.find("option").each(function () {
  1736. var optionValue = $(this).val();
  1737. if (translations[optionValue]) {
  1738. $(this).text(translations[optionValue]);
  1739. }
  1740. });
  1741. })();
  1742. // 比赛过滤器选项汉化
  1743. (function () {
  1744. var parentElement = $('.options');
  1745. var selectElement = parentElement.find('li');
  1746. var translations = {
  1747. "Educational": "教育性",
  1748. "Global": "全球",
  1749. "VK Cup": "VK杯",
  1750. "Long Rounds": "长期回合",
  1751. "April Fools": "愚人节",
  1752. "Team Contests": "团队比赛",
  1753. "ICPC Scoring": "ICPC计分",
  1754. "Doesn't matter": "----",
  1755. "Any": "所有",
  1756. "Yes": "是",
  1757. "No": "否",
  1758. "No submission(s)": "无提交",
  1759. "Have submission(s)": "有提交",
  1760. "No solved problem(s)": "无解决问题",
  1761. "Have solved problem(s)": "有解决问题"
  1762. };
  1763. selectElement.find('label').each(function () {
  1764. var optionValue = $(this).text();
  1765. if (translations[optionValue]) {
  1766. $(this).text(translations[optionValue]);
  1767. }
  1768. });
  1769. $('.CaptionCont').find('span').each(function () {
  1770. var optionValue = $(this).text();
  1771. if (translations[optionValue]) {
  1772. $(this).text(translations[optionValue]);
  1773. }
  1774. });
  1775. })();
  1776. // 右侧sidebox通用汉化
  1777. (function () {
  1778. var parentElement = $('.sidebox');
  1779. var selectElement = parentElement.find('div');
  1780. var translations = {
  1781. "Show tags for unsolved problems": "显示未解决问题的标签",
  1782. "Hide solved problems": "隐藏已解决的问题",
  1783. };
  1784. selectElement.find("label").each(function () {
  1785. var optionValue = $(this).text();
  1786. if (translations[optionValue]) {
  1787. $(this).text(translations[optionValue]);
  1788. }
  1789. });
  1790. })();
  1791. // 表单字段名汉化
  1792. (function () {
  1793. var translations = {
  1794. "Problem:": "题目:",
  1795. "Language:": "语言:",
  1796. "Source code:": "源代码:",
  1797. "Or choose file:": "或者选择文件:",
  1798. "Choose file:": "选择文件:",
  1799. "Notice:": "注意:",
  1800. "virtual participation:": "虚拟参与:",
  1801. "Registration for the contest:": "比赛报名:",
  1802. "Take part:": "参与:",
  1803. "as individual participant:": "作为个人参与者:",
  1804. "as a team member:": "作为团队成员:",
  1805. "Virtual start time:": "虚拟开始时间:",
  1806. "Complete problemset:": "完整的问题集:",
  1807. "First name (English)": "名字(英文)",
  1808. "Last name (English)": "姓氏(英文)",
  1809. "First name (Native)": "名字(本地语言)",
  1810. "Last name (Native)": "姓氏(本地语言)",
  1811. "Birth date": "出生日期",
  1812. "Country": "国家",
  1813. "City": "城市",
  1814. "Organization": "组织",
  1815. "Handle/Email": "账号/邮箱",
  1816. "Password": "密码",
  1817. };
  1818. $(".field-name").each(function () {
  1819. var optionValue = $(this).text();
  1820. if (translations[optionValue]) {
  1821. $(this).text(translations[optionValue]);
  1822. }
  1823. });
  1824. })();
  1825. (function () {
  1826. var translations = {
  1827. "Terms of agreement:": "协议条款:",
  1828. "Choose team:": "选择团队:"
  1829. };
  1830. $(".field-name label").each(function () {
  1831. var optionValue = $(this).text();
  1832. if (translations[optionValue]) {
  1833. $(this).text(translations[optionValue]);
  1834. }
  1835. });
  1836. })();
  1837. (function () {
  1838. var translations = {
  1839. "Hide sidebar block \"Find user\"": "隐藏侧边栏块“查找用户”",
  1840. "Hide sidebar block \"Current user\"": "隐藏侧边栏块“当前用户”",
  1841. "Hide sidebar block \"Recent аctions\"": "隐藏侧边栏块“最新动态”",
  1842. "Hide sidebar block \"Favourite groups\"": "隐藏侧边栏块“收藏组”",
  1843. "Hide sidebar block \"Top contributors\"": "隐藏侧边栏块“贡献者排行”",
  1844. "Hide sidebar block \"Top rated\"": "隐藏侧边栏块“评级排行”",
  1845. "Hide sidebar block \"Streams\"": "隐藏侧边栏块“直播”",
  1846. "Old password": "旧密码",
  1847. "New password": "新密码",
  1848. "Confirm new password": "确认新密码",
  1849. "Contest email notification": "比赛邮件通知",
  1850. "Send email on new user talk": "在有新用户对话时发送电子邮件",
  1851. "Send email on new comment": "在有新评论时发送电子邮件",
  1852. "Hide contact information": "隐藏联系人信息",
  1853. "Remember me by Gmail, Facebook and etc": "通过 Gmail、Facebook 等记住我",
  1854. "Show tags for unsolved problems": "显示未解决问题的标签",
  1855. "Hide solved problems from problemset": "从问题集中隐藏已解决的问题",
  1856. "Hide low rated blogs": "隐藏评级较低的博客",
  1857. "Offer to publish great rating rises": "提供展示Rating显著提升的机会",
  1858. "Enforce https": "强制 HTTPS",
  1859. "Show private activity in the profile": "在个人资料中显示私人活动",
  1860. "Show diagnostics": "显示诊断信息"
  1861. };
  1862. $(".field-name").each(function () {
  1863. var tag = $(this).text();
  1864. for (var property in translations) {
  1865. property = property.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
  1866. if (tag.match(property)) {
  1867. $(this).text(translations[property]);
  1868. break;
  1869. }
  1870. }
  1871. });
  1872. })();
  1873. (function () {
  1874. var translations = {
  1875. "Postal/zip code": "邮政编码/邮编",
  1876. "Country (English)": "国家(英文)",
  1877. "State (English)": "州/省份(英文)",
  1878. "City (English)": "城市(英文)",
  1879. "Address (English)": "地址(英文)",
  1880. "Recipient (English)": "收件人姓名(英文)",
  1881. "Country (Native)": "国家(本地语言)",
  1882. "State (Native)": "州/省份(本地语言)",
  1883. "City (Native)": "城市(本地语言)",
  1884. "Address (Native)": "地址(本地语言)",
  1885. "Recipient (Native)": "收件人姓名(本地语言)",
  1886. "Phone": "电话",
  1887. "TON Wallet:": "TON 钱包:",
  1888. "Secret Code:": "验证码:"
  1889. };
  1890. $("td.field-name label").each(function () {
  1891. var optionValue = $(this).text();
  1892. if (translations[optionValue]) {
  1893. $(this).text(translations[optionValue]);
  1894. }
  1895. });
  1896. })();
  1897.  
  1898. // 按钮汉化input[type="submit"]
  1899. (function () {
  1900. var translations = {
  1901. "Register for virtual participation": "报名虚拟参赛",
  1902. "Register for practice": "登录以开始练习",
  1903. "Apply": "应用",
  1904. "Register": "报名",
  1905. "Login": "登录",
  1906. "Run": "运行",
  1907. "Start virtual contest": "开始虚拟参赛",
  1908. "Clone Contest": "克隆比赛",
  1909. "Submit": "提交",
  1910. "Save changes": "保存设置",
  1911. "Filter": "过滤",
  1912. "Find": "查找",
  1913. "Create Mashup Contest": "创建混搭比赛"
  1914. };
  1915. $('input[type="submit"]').each(function () {
  1916. var optionValue = $(this).val();
  1917. if (translations[optionValue]) {
  1918. $(this).val(translations[optionValue]);
  1919. }
  1920. });
  1921. })();
  1922. (function () {
  1923. var translations = {
  1924. "Reset": "重置",
  1925. };
  1926. $('input[type="button"]').each(function () {
  1927. var optionValue = $(this).val();
  1928. if (translations[optionValue]) {
  1929. $(this).val(translations[optionValue]);
  1930. }
  1931. });
  1932. })();
  1933.  
  1934. // 选项汉化input[type="radio"]
  1935. (function () {
  1936. var translations = {
  1937. "as individual participant": "个人",
  1938. "as a team member": "作为一个团队成员",
  1939. };
  1940. $('input[type="radio"]').each(function () {
  1941. var tag = $(this).parent().contents().filter(function () {
  1942. return this.nodeType === Node.TEXT_NODE;
  1943. });
  1944. for (var i = 0; i < tag.length; i++) {
  1945. var text = tag[i].textContent.trim();
  1946. if (translations.hasOwnProperty(text)) {
  1947. $(this).addClass(text);
  1948. tag[i].replaceWith(translations[text]);
  1949. break;
  1950. }
  1951. }
  1952. });
  1953. })();
  1954.  
  1955.  
  1956. // 杂项
  1957. (function () {
  1958. var translations = {
  1959. "(standard input\/output)": "标准输入/输出",
  1960. };
  1961. $("div.notice").each(function () {
  1962. var tag = $(this).children().eq(0).text();
  1963. for (var property in translations) {
  1964. if (tag.match(property)) {
  1965. $(this).children().eq(0).text(translations[property]);
  1966. break;
  1967. }
  1968. }
  1969. });
  1970. })();
  1971. (function () {
  1972. var translations = {
  1973. "Ask a question": "提一个问题",
  1974. };
  1975. $(".ask-question-link").each(function () {
  1976. var optionValue = $(this).text();
  1977. if (translations[optionValue]) {
  1978. $(this).text(translations[optionValue]);
  1979. }
  1980. });
  1981. })();
  1982.  
  1983. // 轻量站特殊
  1984. if (is_mSite) {
  1985. (function () {
  1986. var translations = {
  1987. "Announcements": "公告",
  1988. "Submissions": "提交记录",
  1989. "Contests": "比赛",
  1990. };
  1991. $(".caption").each(function () {
  1992. var optionValue = $(this).text();
  1993. if (translations[optionValue]) {
  1994. $(this).text(translations[optionValue]);
  1995. }
  1996. });
  1997. })();
  1998. }
  1999. };
  2000.  
  2001. // 配置管理函数
  2002. function setupConfigManagement(element, tempConfig, structure, configHTML, checkable) {
  2003. let counter = 0;
  2004. createControlBar();
  2005. createContextMenu();
  2006.  
  2007. // 键值对校验
  2008. function valiKeyValue(value) {
  2009. const keyValuePairs = value.split('\n');
  2010. const regex = /^[a-zA-Z0-9_-]+\s*:\s*[a-zA-Z0-9_-]+$/;
  2011. for (let i = 0; i < keyValuePairs.length; i++) {
  2012. if (!regex.test(keyValuePairs[i])) {
  2013. return false;
  2014. }
  2015. }
  2016. return true;
  2017. }
  2018.  
  2019. // 新增数据
  2020. function onAdd() {
  2021. const styleElement = createWindow();
  2022.  
  2023. const settingMenu = $("#config_edit_menu");
  2024. settingMenu.on("click", "#save", () => {
  2025. const config = {};
  2026. let allFieldsValid = true;
  2027. for (const key in structure) {
  2028. let value = $(key).val();
  2029. if (value || $(key).attr('require') === 'false') {
  2030. config[structure[key]] = $(key).val();
  2031. $(key).removeClass('is_null');
  2032. } else {
  2033. $(key).addClass('is_null');
  2034. allFieldsValid = false;
  2035. }
  2036. }
  2037.  
  2038. // 校验提示
  2039. for (let i = 0, len = checkable.length; i < len; i++) {
  2040. let value = $(checkable[i]).val();
  2041. if (value && !valiKeyValue(value)) {
  2042. if (!$(checkable[i]).prev('span.text-error').length) {
  2043. $(checkable[i]).before('<span class="text-error" style="color: red;">格式不符或存在非法字符</span>');
  2044. }
  2045. allFieldsValid = false;
  2046. } else {
  2047. $(checkable[i]).prev('span.text-error').remove();
  2048. }
  2049. }
  2050.  
  2051. if (!allFieldsValid) return;
  2052. tempConfig.configurations.push(config);
  2053.  
  2054. const list = $("#config_bar_ul");
  2055. createListItemElement(config[structure['#note']]).insertBefore($('#add_button'));
  2056.  
  2057. settingMenu.remove();
  2058. $(styleElement).remove();
  2059. });
  2060.  
  2061. settingMenu.on("click", ".btn-close", () => {
  2062. settingMenu.remove();
  2063. $(styleElement).remove();
  2064. });
  2065. }
  2066.  
  2067. // 编辑数据
  2068. function onEdit() {
  2069. const menu = $("#config_bar_menu");
  2070. menu.css({ display: "none" });
  2071.  
  2072. const list = $("#config_bar_ul");
  2073. const index = Array.from(list.children()).indexOf(this);
  2074.  
  2075. const styleElement = createWindow();
  2076.  
  2077. const settingMenu = $("#config_edit_menu");
  2078. const configAtIndex = tempConfig.configurations[index];
  2079.  
  2080. if (configAtIndex) {
  2081. for (const key in structure) {
  2082. $(key).val(configAtIndex[structure[key]]);
  2083. }
  2084. }
  2085.  
  2086. settingMenu.on("click", "#save", () => {
  2087. const config = {};
  2088. let allFieldsValid = true;
  2089. for (const key in structure) {
  2090. let value = $(key).val();
  2091. if (value || $(key).attr('require') === 'false') {
  2092. config[structure[key]] = $(key).val();
  2093. $(key).removeClass('is_null');
  2094. } else {
  2095. $(key).addClass('is_null');
  2096. allFieldsValid = false;
  2097. }
  2098. }
  2099.  
  2100. // 校验提示
  2101. for (let i = 0, len = checkable.length; i < len; i++) {
  2102. let value = $(checkable[i]).val();
  2103. if (value && !valiKeyValue(value)) {
  2104. if (!$(checkable[i]).prev('span.text-error').length) {
  2105. $(checkable[i]).before('<span class="text-error" style="color: red;">格式不符或存在非法字符</span>');
  2106. }
  2107. allFieldsValid = false;
  2108. } else {
  2109. $(checkable[i]).prev('span.text-error').remove();
  2110. }
  2111. }
  2112.  
  2113. if (!allFieldsValid) return;
  2114. tempConfig.configurations[index] = config;
  2115.  
  2116. settingMenu.remove();
  2117. $(styleElement).remove();
  2118. menu.css({ display: "none" });
  2119.  
  2120. list.children().eq(index).find("label").text(config.note);
  2121. });
  2122.  
  2123. // 关闭按钮
  2124. settingMenu.on("click", ".btn-close", () => {
  2125. settingMenu.remove();
  2126. $(styleElement).remove();
  2127. });
  2128. }
  2129.  
  2130. // 删除数据
  2131. function onDelete() {
  2132. const menu = $("#config_bar_menu");
  2133. menu.css({ display: "none" });
  2134.  
  2135. const list = $("#config_bar_ul");
  2136. const index = Array.from(list.children()).indexOf(this);
  2137.  
  2138. tempConfig.configurations.splice(index, 1);
  2139.  
  2140. list.children().eq(index).remove();
  2141. }
  2142.  
  2143. // 创建编辑窗口
  2144. function createWindow() {
  2145. const styleElement = GM_addStyle(darkenPageStyle2);
  2146. $("body").append(configHTML);
  2147. addDraggable($('#config_edit_menu'));
  2148. return styleElement;
  2149. }
  2150.  
  2151. // 创建控制面板
  2152. function createControlBar() {
  2153. $(element).append(`
  2154. <div id='configControlTip' style='color:red;'></div>
  2155. <div class='config_bar'>
  2156. <div class='config_bar_list' id='config_bar_list'>
  2157. <ul class='config_bar_ul' id='config_bar_ul'></ul>
  2158. </div>
  2159. </div>
  2160. `);
  2161. }
  2162.  
  2163. // 创建右键菜单
  2164. function createContextMenu() {
  2165. const menu = $("<div id='config_bar_menu' style='display: none;'></div>");
  2166. menu.html(`
  2167. <div class='config_bar_menu_item' id='config_bar_menu_edit'>修改</div>
  2168. <div class='config_bar_menu_item' id='config_bar_menu_delete'>删除</div>
  2169. `);
  2170. $("body").append(menu);
  2171. }
  2172.  
  2173. // 创建新的li元素
  2174. function createListItemElement(text) {
  2175. const li = $("<li></li>");
  2176. const radio = $("<input type='radio' name='config_item'></input>").appendTo(li);
  2177. radio.attr("value", counter).attr("id", counter++);
  2178. const label = $("<label class='config_bar_ul_li_text'></label>").text(text).attr("for", radio.attr("value")).appendTo(li);
  2179.  
  2180. // 添加右键菜单
  2181. li.on("contextmenu", function (event) {
  2182. event.preventDefault();
  2183. const menu = $("#config_bar_menu");
  2184. menu.css({ display: "block", left: event.pageX, top: event.pageY });
  2185.  
  2186. const deleteItem = $("#config_bar_menu_delete");
  2187. const editItem = $("#config_bar_menu_edit");
  2188.  
  2189. // 移除旧事件
  2190. deleteItem.off("click");
  2191. editItem.off("click");
  2192.  
  2193. deleteItem.on("click", onDelete.bind(this));
  2194. editItem.on("click", onEdit.bind(this));
  2195.  
  2196. $(document).one("click", (event) => {
  2197. if (!menu.get(0).contains(event.target)) {
  2198. menu.css({ display: "none" });
  2199. deleteItem.off("click", onDelete);
  2200. editItem.off("click", onEdit);
  2201. }
  2202. });
  2203. });
  2204.  
  2205.  
  2206. return li;
  2207. }
  2208.  
  2209. // 渲染列表
  2210. function renderList() {
  2211. const listContainer = $("#config_bar_list");
  2212. const list = $("#config_bar_ul");
  2213. list.empty();
  2214. tempConfig.configurations.forEach((item) => {
  2215. list.append(createListItemElement(item[structure['#note']]));
  2216. });
  2217.  
  2218. list.append(`
  2219. <li id='add_button'>
  2220. <span>+ 添加</span>
  2221. </li>
  2222. `);
  2223. const addItem = $('#add_button');
  2224. addItem.on("click", onAdd);
  2225. };
  2226.  
  2227. renderList();
  2228. return tempConfig;
  2229. }
  2230.  
  2231. const CFBetterSettingMenuHTML = `
  2232. <div class='CFBetter_setting_menu' id='CFBetter_setting_menu'>
  2233. <div class="tool-box">
  2234. <button class="btn-close">×</button>
  2235. </div>
  2236. <h3>基本设置</h3>
  2237. <hr>
  2238. <div class='CFBetter_setting_list'>
  2239. <label for="bottomZh_CN">界面汉化</label>
  2240. <input type="checkbox" id="bottomZh_CN" name="bottomZh_CN">
  2241. </div>
  2242. <div class='CFBetter_setting_list'>
  2243. <label for="darkMode">强制黑暗模式</label>
  2244. <input type="checkbox" id="darkMode" name="darkMode">
  2245. </div>
  2246. <div class='CFBetter_setting_list'>
  2247. <label for="showLoading">显示加载提示信息</label>
  2248. <div class="help_tip">
  2249. `+ helpCircleHTML + `
  2250. <div class="tip_text">
  2251. <p>当你开启 显示加载信息 时,每次加载页面时会在上方显示加载信息提示:“Codeforces Better! —— xxx”</p>
  2252. <p>这用于了解脚本当前的工作情况,<strong>如果你不想看到,可以选择关闭</strong></p>
  2253. <p><u>需要说明的是,如果你需要反馈脚本的任何加载问题,请开启该选项后再截图,以便于分析问题</u></p>
  2254. </div>
  2255. </div>
  2256. <input type="checkbox" id="showLoading" name="showLoading">
  2257. </div>
  2258. <div class='CFBetter_setting_list'>
  2259. <label for="hoverTargetAreaDisplay">显示目标区域范围</label>
  2260. <div class="help_tip">
  2261. `+ helpCircleHTML + `
  2262. <div class="tip_text">
  2263. <p>开启后当鼠标悬浮在 MD视图/复制/翻译 按钮上时,会显示其目标区域的范围</p>
  2264. </div>
  2265. </div>
  2266. <input type="checkbox" id="hoverTargetAreaDisplay" name="hoverTargetAreaDisplay">
  2267. </div>
  2268. <div class='CFBetter_setting_list'>
  2269. <label for="expandFoldingblocks">自动展开折叠块</label>
  2270. <input type="checkbox" id="expandFoldingblocks" name="expandFoldingblocks">
  2271. </div>
  2272. <div class='CFBetter_setting_list'>
  2273. <label for="renderPerfOpt">折叠块渲染优化</label>
  2274. <div class="help_tip">
  2275. `+ helpCircleHTML + `
  2276. <div class="tip_text">
  2277. <p>为折叠块元素启用可见渲染(content-visibility: auto)</p>
  2278. <p>如果您的浏览器查看大量折叠块时比较卡顿,开启后会有一定程度的改善</p>
  2279. <p>注意:本特性有小概率可能导致页面在某些位置时上下快速跳动闪屏</p>
  2280. </div>
  2281. </div>
  2282. <input type="checkbox" id="renderPerfOpt" name="renderPerfOpt">
  2283. </div>
  2284. <div class='CFBetter_setting_list'>
  2285. <label for="commentPaging">评论区分页</label>
  2286. <div class="help_tip">
  2287. `+ helpCircleHTML + `
  2288. <div class="tip_text">
  2289. <p>对评论区分页显示,每页显示指定数量的<strong>主楼</strong></p>
  2290. <p>注意:开启后评论回复不可用</p>
  2291. </div>
  2292. </div>
  2293. <input type="checkbox" id="commentPaging" name="commentPaging">
  2294. </div>
  2295. <div class='CFBetter_setting_list'>
  2296. <label for="showJumpToLuogu">显示跳转到洛谷</label>
  2297. <div class="help_tip">
  2298. `+ helpCircleHTML + `
  2299. <div class="tip_text">
  2300. <p>洛谷OJ上收录了Codeforces的部分题目,一些题目有翻译和题解</p>
  2301. <p>开启显示后,如果当前题目被收录,则会在题目的右上角显示洛谷标志,</p>
  2302. <p>点击即可一键跳转到该题洛谷的对应页面。</strong></p>
  2303. </div>
  2304. </div>
  2305. <input type="checkbox" id="showJumpToLuogu" name="showJumpToLuogu">
  2306. </div>
  2307. <div class='CFBetter_setting_list'>
  2308. <label for="loaded"><span style="font-size: 14px;">兼容选项-不等待页面资源加载</span></label>
  2309. <div class="help_tip">
  2310. `+ helpCircleHTML + `
  2311. <div class="tip_text">
  2312. <p>为了防止在页面资源未加载完成前(主要是各种js)执行脚本产生意外的错误,脚本默认会等待 window.onload 事件</p>
  2313. <p>如果您的页面上方的加载信息始终停留在:“等待页面资源加载”,即使页面已经完成加载</p>
  2314. <p><u>您首先应该确认是否是网络问题,</u></p>
  2315. <p>如果不是,那这可能是由于 window.onload 事件在您的浏览器中触发过早(早于DOMContentLoaded),</p>
  2316. <p>您可以尝试开启该选项来不再等待 window.onload 事件</p>
  2317. <p><u>注意:如果没有上述问题,请不要开启该选项</u></p>
  2318. </div>
  2319. </div>
  2320. <input type="checkbox" id="loaded" name="loaded">
  2321. </div>
  2322. <h3>翻译设置</h3>
  2323. <hr>
  2324. <div class='CFBetter_setting_list'>
  2325. <label for="enableSegmentedTranslation">分段翻译</label>
  2326. <div class="help_tip">
  2327. `+ helpCircleHTML + `
  2328. <div class="tip_text">
  2329. <p>分段翻译会对区域内的每一个&#60;&#112;&#47;&#62;和&#60;&#105;&#47;&#62;标签依次进行翻译,</p>
  2330. <p>这通常在翻译<strong>长篇博客</strong>或者<strong>超长的题目</strong>时很有用。</p>
  2331. <p><u>注意:开启分段翻译会产生如下问题:</u></p>
  2332. <p>- 使得翻译接口无法知晓整个文本的上下文信息,会降低翻译质量。</p>
  2333. <p>- 会有<strong>部分内容不会被翻译</strong>,因为它们不是&#60;&#112;&#47;&#62;或&#60;&#105;&#47;&#62;元素</p>
  2334. </div>
  2335. </div>
  2336. <input type="checkbox" id="enableSegmentedTranslation" name="enableSegmentedTranslation">
  2337. </div>
  2338. <label>
  2339. <input type='radio' name='translation' value='deepl'>
  2340. <span class='CFBetter_setting_menu_label_text'>deepl翻译</span>
  2341. </label>
  2342. <label>
  2343. <input type='radio' name='translation' value='youdao'>
  2344. <span class='CFBetter_setting_menu_label_text'>有道翻译</span>
  2345. </label>
  2346. <label>
  2347. <input type='radio' name='translation' value='google'>
  2348. <span class='CFBetter_setting_menu_label_text'>Google翻译</span>
  2349. </label>
  2350. <label>
  2351. <input type='radio' name='translation' value='openai'>
  2352. <span class='CFBetter_setting_menu_label_text'>使用ChatGPT翻译(API)
  2353. <div class="help_tip">
  2354. `+ helpCircleHTML + `
  2355. <div class="tip_text">
  2356. <p><b>请在下方添加并选定你想使用的配置信息</b></p>
  2357. <p>具体请阅读脚本页的介绍</p>
  2358. </div>
  2359. </div>
  2360. </span>
  2361. </label>
  2362. <div class='CFBetter_setting_menu_input' id='openai' style='display: none;'>
  2363. <div id="chatgpt-config"></div>
  2364. </div>
  2365. <button id='save'>保存</button>
  2366. </div>
  2367. `;
  2368.  
  2369. const chatgptConfigEditHTML = `
  2370. <div class='CFBetter_setting_menu' id='config_edit_menu'>
  2371. <div class="tool-box">
  2372. <button class="btn-close">×</button>
  2373. </div>
  2374. <h4>配置</h4>
  2375. <h5>基本</h5>
  2376. <hr>
  2377. <label for='note'>
  2378. <span class="input_label">备注:</span>
  2379. </label>
  2380. <input type='text' id='note' class='no_default' placeholder='请为该配置取一个备注名' require = true>
  2381. <label for='openai_model'>
  2382. <div style="display: flex;align-items: center;">
  2383. <span class="input_label">模型:</span>
  2384. <div class="help_tip">
  2385. `+ helpCircleHTML + `
  2386. <div class="tip_text">
  2387. <p>留空则默认为:gpt-3.5-turbo</p>
  2388. <p>模型列表请查阅<a target="_blank" href="https://platform.openai.com/docs/models">OpenAI官方文档</a></p>
  2389. <p><strong>此外,如果您使用的是服务商提供的代理API,请确认服务商是否支持对应模型</strong></p>
  2390. </div>
  2391. </div>
  2392. </div>
  2393. </label>
  2394. <input type='text' id='openai_model' placeholder='gpt-3.5-turbo' require = false>
  2395. <label for='openai_key'>
  2396. <div style="display: flex;align-items: center;">
  2397. <span class="input_label">KEY:</span>
  2398. <div class="help_tip">
  2399. `+ helpCircleHTML + `
  2400. <div class="tip_text">
  2401. <p>您需要输入自己的OpenAI key,<a target="_blank" href="https://platform.openai.com/account/usage">官网</a></p>
  2402. <p><b>如果您使用的是服务商提供的代理API,则应该填写服务商提供的 Key</b></p>
  2403. </div>
  2404. </div>
  2405. </div>
  2406. </label>
  2407. <input type='text' id='openai_key' class='no_default' placeholder='请输入KEY' require = true>
  2408. <label for='openai_proxy'>
  2409. <div style="display: flex;align-items: center;">
  2410. <span class="input_label">Proxy API:</span>
  2411. <div class="help_tip">
  2412. `+ helpCircleHTML + `
  2413. <div class="tip_text">
  2414. <p>留空则默认为OpenAI官方API</p>
  2415. <p>您也可以填写指定的API来代理访问OpenAIAPI,</p>
  2416. <p>如果您使用的是服务商提供的代理APIKEY,则这里应该填写其提供的<strong>完整</strong>API地址,详请阅读脚本说明</p>
  2417. <p><strong>由于您指定了自定义的APITampermonkey会对您的跨域请求进行警告,您需要自行授权</strong></p>
  2418. </div>
  2419. </div>
  2420. </div>
  2421. </label>
  2422. <input type='text' id='openai_proxy' placeholder='https://api.openai.com/v1/chat/completions' require = false>
  2423. <h5>高级</h5>
  2424. <hr>
  2425. <label for='_header'>
  2426. <div style="display: flex;align-items: center;">
  2427. <span class="input_label">自定义header</span>
  2428. <div class="help_tip">
  2429. `+ helpCircleHTML + `
  2430. <div class="tip_text">
  2431. <p>格式样例:</p>
  2432. <div style="border: 1px solid #795548; padding: 10px;">
  2433. <p>name1 : 123<br>name2 : cccc</p>
  2434. </div>
  2435. </div>
  2436. </div>
  2437. </div>
  2438. </label>
  2439. <textarea id="_header" placeholder='(选填)您可以在这里填写向请求header中额外添加的键值对' require = false></textarea>
  2440. <label for='_data'>
  2441. <div style="display: flex;align-items: center;">
  2442. <span class="input_label">自定义data</span>
  2443. <div class="help_tip">
  2444. `+ helpCircleHTML + `
  2445. <div class="tip_text">
  2446. <p>格式样例:</p>
  2447. <div style="border: 1px solid #795548; padding: 10px;">
  2448. <p>name1 : 123<br>name2 : cccc</p>
  2449. </div>
  2450. </div>
  2451. </div>
  2452. </div>
  2453. </label>
  2454. <textarea id="_data" placeholder='(选填)您可以在这里填写向请求data中额外添加的键值对' require = false></textarea>
  2455. <button id='save'>保存</button>
  2456. </div>
  2457. `;
  2458.  
  2459. // 设置按钮面板
  2460. function settingPanel() {
  2461. $("div[class='lang-chooser']").each(function () {
  2462. $(this).before(
  2463. "<button class='html2mdButton CFBetter_setting'>CodeforcesBetter设置</button>"
  2464. );
  2465. });
  2466. $("div[class='enter-or-register-box']").each(function () {
  2467. $(this).after(
  2468. "<button class='html2mdButton CFBetter_setting'>CodeforcesBetter设置</button>"
  2469. );
  2470. });
  2471.  
  2472. const $settingBtns = $(".CFBetter_setting");
  2473. $settingBtns.click(() => {
  2474. const styleElement = GM_addStyle(darkenPageStyle);
  2475. $settingBtns.prop("disabled", true).addClass("open");
  2476. $("body").append(CFBetterSettingMenuHTML);
  2477.  
  2478. // 窗口初始化
  2479. addDraggable($('#CFBetter_setting_menu'));
  2480. const chatgptStructure = {
  2481. '#note': 'note',
  2482. '#openai_model': 'model',
  2483. '#openai_key': 'key',
  2484. '#openai_proxy': 'proxy',
  2485. '#_header': '_header',
  2486. '#_data': '_data',
  2487. }
  2488. const checkable = [
  2489. '#_header',
  2490. '#_data',
  2491. ]
  2492. let tempConfig = GM_getValue('chatgpt-config'); // 缓存配置信息
  2493. tempConfig = setupConfigManagement('#chatgpt-config', tempConfig, chatgptStructure, chatgptConfigEditHTML, checkable);
  2494.  
  2495. // 状态更新
  2496. $("#bottomZh_CN").prop("checked", GM_getValue("bottomZh_CN") === true);
  2497. $("#darkMode").prop("checked", GM_getValue("darkMode") === true);
  2498. $("#showLoading").prop("checked", GM_getValue("showLoading") === true);
  2499. $("#expandFoldingblocks").prop("checked", GM_getValue("expandFoldingblocks") === true);
  2500. $("#enableSegmentedTranslation").prop("checked", GM_getValue("enableSegmentedTranslation") === true);
  2501. $("#renderPerfOpt").prop("checked", GM_getValue("renderPerfOpt") === true);
  2502. $("#commentPaging").prop("checked", GM_getValue("commentPaging") === true);
  2503. $("#showJumpToLuogu").prop("checked", GM_getValue("showJumpToLuogu") === true);
  2504. $("#loaded").prop("checked", GM_getValue("loaded") === true);
  2505. $("#hoverTargetAreaDisplay").prop("checked", GM_getValue("hoverTargetAreaDisplay") === true);
  2506. $("input[name='translation'][value='" + translation + "']").prop("checked", true);
  2507. $("input[name='translation']").css("color", "gray");
  2508. if (translation == "openai") {
  2509. $("#openai").show();
  2510. if (tempConfig) {
  2511. $("input[name='config_item'][value='" + tempConfig.choice + "']").prop("checked", true);
  2512. }
  2513. }
  2514.  
  2515. // 翻译选择情况监听
  2516. $("input[name='translation']").change(function () {
  2517. var selected = $(this).val(); // 获取当前选中的值
  2518. if (selected === "openai") {
  2519. $("#openai").show();
  2520. if (tempConfig) {
  2521. $("input[name='config_item'][value='" + tempConfig.choice + "']").prop("checked", true);
  2522. }
  2523. } else {
  2524. $("#openai").hide();
  2525. }
  2526. });
  2527.  
  2528. // 配置选择情况监听
  2529. $("input[name='config_item']").change(function () {
  2530. var selected = $(this).val(); // 获取当前选中的值
  2531. tempConfig.choice = selected;
  2532. });
  2533.  
  2534. const $settingMenu = $(".CFBetter_setting_menu");
  2535.  
  2536. $("#save").click(debounce(function () {
  2537. const settings = {
  2538. bottomZh_CN: $("#bottomZh_CN").prop("checked"),
  2539. darkMode: $("#darkMode").prop("checked"),
  2540. showLoading: $("#showLoading").prop("checked"),
  2541. hoverTargetAreaDisplay: $("#hoverTargetAreaDisplay").prop("checked"),
  2542. expandFoldingblocks: $("#expandFoldingblocks").prop("checked"),
  2543. renderPerfOpt: $("#renderPerfOpt").prop("checked"),
  2544. commentPaging: $("#commentPaging").prop("checked"),
  2545. enableSegmentedTranslation: $("#enableSegmentedTranslation").prop("checked"),
  2546. showJumpToLuogu: $("#showJumpToLuogu").prop("checked"),
  2547. loaded: $("#loaded").prop("checked"),
  2548. translation: $("input[name='translation']:checked").val()
  2549. };
  2550. if (settings.translation === "openai") {
  2551. var selectedIndex = $('input[name="config_item"]:checked').closest('li').index();
  2552. if (selectedIndex === -1) {
  2553. $('#configControlTip').text('请选择一项配置!')
  2554. return;
  2555. }
  2556. }
  2557. GM_setValue('chatgpt-config', tempConfig);
  2558. let refreshPage = false; // 是否需要刷新页面
  2559. for (const [key, value] of Object.entries(settings)) {
  2560. if (!refreshPage && !(key == 'enableSegmentedTranslation' || key == 'translation' || key == 'darkMode')) {
  2561. if (GM_getValue(key) != value) refreshPage = true;
  2562. }
  2563. GM_setValue(key, value);
  2564. }
  2565.  
  2566. if (refreshPage) location.reload();
  2567. else {
  2568. // 切换黑暗模式
  2569. if (darkMode != settings.darkMode) {
  2570. if (darkMode) $('html').removeAttr('data-theme');
  2571. else $('html').attr('data-theme', 'dark');
  2572. darkMode = settings.darkMode;
  2573. }
  2574. // 更新配置信息
  2575. enableSegmentedTranslation = settings.enableSegmentedTranslation;
  2576. translation = settings.translation;
  2577. if (settings.translation === "openai") {
  2578. var selectedIndex = $('#config_bar_ul li input[type="radio"]:checked').closest('li').index();
  2579. if (selectedIndex !== opneaiConfig.choice) {
  2580. opneaiConfig = GM_getValue("chatgpt-config");
  2581. const configAtIndex = opneaiConfig.configurations[selectedIndex];
  2582. openai_model = configAtIndex.model;
  2583. openai_key = configAtIndex.key;
  2584. openai_proxy = configAtIndex.proxy;
  2585. openai_header = configAtIndex._header ?
  2586. configAtIndex._header.split("\n").map(header => {
  2587. const [key, value] = header.split(":");
  2588. return { [key.trim()]: value.trim() };
  2589. }) : [];
  2590. openai_data = configAtIndex._data ?
  2591. configAtIndex._data.split("\n").map(header => {
  2592. const [key, value] = header.split(":");
  2593. return { [key.trim()]: value.trim() };
  2594. }) : [];
  2595. }
  2596. }
  2597. }
  2598.  
  2599. $settingMenu.remove();
  2600. $settingBtns.prop("disabled", false).removeClass("open");
  2601. $(styleElement).remove();
  2602. }));
  2603.  
  2604. // 关闭
  2605. $settingMenu.on("click", ".btn-close", () => {
  2606. $settingMenu.remove();
  2607. $settingBtns.prop("disabled", false).removeClass("open");
  2608. $(styleElement).remove();
  2609. });
  2610. });
  2611. };
  2612.  
  2613. // html2md转换/处理规则
  2614. var turndownService = new TurndownService({ bulletListMarker: '-' });
  2615. var turndown = turndownService.turndown;
  2616.  
  2617. // 保留原始
  2618. turndownService.keep(['del']);
  2619.  
  2620. // 丢弃
  2621. turndownService.addRule('remove-by-class', {
  2622. filter: function (node) {
  2623. return node.classList.contains('sample-tests') ||
  2624. node.classList.contains('header') ||
  2625. node.classList.contains('overlay') ||
  2626. node.classList.contains('html2md-panel');
  2627. },
  2628. replacement: function (content, node) {
  2629. return "";
  2630. }
  2631. });
  2632. turndownService.addRule('remove-script', {
  2633. filter: function (node, options) {
  2634. return node.tagName.toLowerCase() == "script" && node.type.startsWith("math/tex");
  2635. },
  2636. replacement: function (content, node) {
  2637. return "";
  2638. }
  2639. });
  2640.  
  2641. // inline math
  2642. turndownService.addRule('inline-math', {
  2643. filter: function (node, options) {
  2644. return node.tagName.toLowerCase() == "span" && node.className == "MathJax";
  2645. },
  2646. replacement: function (content, node) {
  2647. var latex = $(node).next().text();
  2648. latex = latex.replace(/</g, "&lt;").replace(/>/g, "&gt;");
  2649. return "$" + latex + "$";
  2650. }
  2651. });
  2652.  
  2653. // block math
  2654. turndownService.addRule('block-math', {
  2655. filter: function (node, options) {
  2656. return node.tagName.toLowerCase() == "div" && node.className == "MathJax_Display";
  2657. },
  2658. replacement: function (content, node) {
  2659. var latex = $(node).next().text();
  2660. latex = latex.replace(/</g, "&lt;").replace(/>/g, "&gt;");
  2661. return "\n$$\n" + latex + "\n$$\n";
  2662. }
  2663. });
  2664.  
  2665. // texFontStyle
  2666. turndownService.addRule('texFontStyle', {
  2667. filter: function (node) {
  2668. return (
  2669. node.nodeName === 'SPAN' &&
  2670. node.classList.contains('tex-font-style-bf')
  2671. )
  2672. },
  2673. replacement: function (content) {
  2674. return '**' + content + '**'
  2675. }
  2676. })
  2677.  
  2678. // sectionTitle
  2679. turndownService.addRule('sectionTitle', {
  2680. filter: function (node) {
  2681. return (
  2682. node.nodeName === 'DIV' &&
  2683. node.classList.contains('section-title')
  2684. )
  2685. },
  2686. replacement: function (content) {
  2687. return '**' + content + '**'
  2688. }
  2689. })
  2690.  
  2691. // bordertable
  2692. turndownService.addRule('bordertable', {
  2693. filter: 'table',
  2694. replacement: function (content, node) {
  2695. if (node.classList.contains('bordertable')) {
  2696. var output = [],
  2697. thead = '',
  2698. trs = node.querySelectorAll('tr');
  2699. if (trs.length > 0) {
  2700. var ths = trs[0].querySelectorAll('td,th');
  2701. if (ths.length > 0) {
  2702. thead = '| ' + Array.from(ths).map(th => turndownService.turndown(th.innerHTML.trim())).join(' | ') + ' |\n'
  2703. + '| ' + Array.from(ths).map(() => ' --- ').join('|') + ' |\n';
  2704. }
  2705. }
  2706. var rows = node.querySelectorAll('tr');
  2707. Array.from(rows).forEach(function (row, i) {
  2708. if (i > 0) {
  2709. var cells = row.querySelectorAll('td,th');
  2710. var trow = '| ' + Array.from(cells).map(cell => turndownService.turndown(cell.innerHTML.trim())).join(' | ') + ' |';
  2711. output.push(trow);
  2712. }
  2713. });
  2714. return thead + output.join('\n');
  2715. } else {
  2716. return content;
  2717. }
  2718. }
  2719. });
  2720.  
  2721. // 随机数生成
  2722. function getRandomNumber(numDigits) {
  2723. let min = Math.pow(10, numDigits - 1);
  2724. let max = Math.pow(10, numDigits) - 1;
  2725. return Math.floor(Math.random() * (max - min + 1)) + min;
  2726. }
  2727.  
  2728. // 题目markdown转换/翻译面板
  2729. function addButtonPanel(parent, suffix, type, is_simple = false) {
  2730. let htmlString = `<div class='html2md-panel'>
  2731. <button class='html2mdButton html2md-view${suffix}'>MarkDown视图</button>
  2732. <button class='html2mdButton html2md-cb${suffix}'>Copy</button>
  2733. <button class='html2mdButton translateButton${suffix}'>翻译</button>
  2734. </div>`;
  2735. if (type === "this_level") {
  2736. $(parent).before(htmlString);
  2737. var block = $(".translateButton" + suffix).parent().next();
  2738. } else if (type === "child_level") {
  2739. $(parent).prepend(htmlString);
  2740. var block = $(".translateButton" + suffix).parent().parent();
  2741. }
  2742. if (is_simple) {
  2743. $('.html2md-panel').find('.html2mdButton.html2md-view' + suffix + ', .html2mdButton.html2md-cb' + suffix).remove();
  2744. }
  2745.  
  2746. if (block.css("display") === "none" || block.hasClass('ojbetter-alert')) $(".translateButton" + suffix).parent().remove();
  2747. }
  2748. function addButtonWithHTML2MD(parent, suffix, type) {
  2749. if (is_oldLatex) {
  2750. $(".html2md-view" + suffix).css({
  2751. "cursor": "not-allowed",
  2752. "background-color": "#ffffff",
  2753. "color": "#a8abb2",
  2754. "border": "1px solid #e4e7ed"
  2755. });
  2756. $(".html2md-view" + suffix).prop("disabled", true);
  2757. }
  2758. $(document).on("click", ".html2md-view" + suffix, debounce(function () {
  2759. var target, removedChildren = $();
  2760. if (type === "this_level") {
  2761. target = $(".html2md-view" + suffix).parent().next().get(0);
  2762. } else if (type === "child_level") {
  2763. target = $(".html2md-view" + suffix).parent().parent().get(0);
  2764. removedChildren = $(".html2md-view" + suffix).parent().parent().children(':first').detach();
  2765. }
  2766. if (target.viewmd) {
  2767. target.viewmd = false;
  2768. $(this).text("MarkDown视图");
  2769. $(this).removeClass("mdViewed");
  2770. $(target).html(target.original_html);
  2771. } else {
  2772. target.viewmd = true;
  2773. if (!target.original_html) {
  2774. target.original_html = $(target).html();
  2775. }
  2776. if (!target.markdown) {
  2777. target.markdown = turndownService.turndown($(target).html());
  2778. }
  2779. $(this).text("原始内容");
  2780. $(this).addClass("mdViewed");
  2781. $(target).html(`<span class="mdViewContent" oninput="$(this).parent().get(0).markdown=this.value;" style="width:auto; height:auto;">${target.markdown}</span>`);
  2782. }
  2783. // 恢复删除的元素
  2784. if (removedChildren) $(target).prepend(removedChildren);
  2785. }));
  2786.  
  2787. if (hoverTargetAreaDisplay && !is_oldLatex) {
  2788. var previousCSS;
  2789. $(document).on("mouseover", ".html2md-view" + suffix, function () {
  2790. var target;
  2791.  
  2792. if (type === "this_level") {
  2793. target = $(".html2md-view" + suffix).parent().next().get(0);
  2794. } else if (type === "child_level") {
  2795. target = $(".html2md-view" + suffix).parent().parent().get(0);
  2796. }
  2797.  
  2798. $(target).append('<div class="overlay">目标转换区域</div>');
  2799.  
  2800. previousCSS = {
  2801. "position": $(target).css("position"),
  2802. "display": $(target).css("display")
  2803. };
  2804. $(target).css({
  2805. "position": "relative",
  2806. "display": "block"
  2807. });
  2808.  
  2809. $(".html2md-view" + suffix).parent().css({
  2810. "position": "relative",
  2811. "z-index": "99999"
  2812. });
  2813. });
  2814.  
  2815. $(document).on("mouseout", ".html2md-view" + suffix, function () {
  2816. var target;
  2817.  
  2818. if (type === "this_level") {
  2819. target = $(".html2md-view" + suffix).parent().next().get(0);
  2820. } else if (type === "child_level") {
  2821. target = $(".html2md-view" + suffix).parent().parent().get(0);
  2822. }
  2823.  
  2824. $(target).find('.overlay').remove();
  2825. if (previousCSS) {
  2826. $(target).css(previousCSS);
  2827. }
  2828. $(".html2md-view" + suffix).parent().css({
  2829. "position": "static"
  2830. });
  2831. });
  2832. }
  2833. }
  2834.  
  2835. function addButtonWithCopy(parent, suffix, type) {
  2836. if (is_oldLatex) {
  2837. $(".html2md-cb" + suffix).css({
  2838. "cursor": "not-allowed",
  2839. "background-color": "#ffffff",
  2840. "color": "#a8abb2",
  2841. "border": "1px solid #e4e7ed"
  2842. });
  2843. $(".html2md-cb" + suffix).prop("disabled", true);
  2844. }
  2845. $(document).on("click", ".html2md-cb" + suffix, debounce(function () {
  2846. var target, removedChildren;
  2847. if (type === "this_level") {
  2848. target = $(".translateButton" + suffix).parent().next().eq(0).clone();
  2849. } else if (type === "child_level") {
  2850. target = $(".translateButton" + suffix).parent().parent().eq(0).clone();
  2851. $(target).children(':first').remove();
  2852. }
  2853. if ($(target).find('.mdViewContent').length <= 0) {
  2854. text = turndownService.turndown($(target).html());
  2855. } else {
  2856. text = $(target).find('.mdViewContent').text();
  2857. }
  2858. GM_setClipboard(text);
  2859. $(this).addClass("copied");
  2860. $(this).text("Copied");
  2861. // 更新复制按钮文本
  2862. setTimeout(() => {
  2863. $(this).removeClass("copied");
  2864. $(this).text("Copy");
  2865. }, 2000);
  2866. $(target).remove();
  2867. }));
  2868.  
  2869. if (hoverTargetAreaDisplay && !is_oldLatex) {
  2870. var previousCSS;
  2871. $(document).on("mouseover", ".html2md-cb" + suffix, function () {
  2872. var target;
  2873.  
  2874. if (type === "this_level") {
  2875. target = $(".html2md-cb" + suffix).parent().next().get(0);
  2876. } else if (type === "child_level") {
  2877. target = $(".html2md-cb" + suffix).parent().parent().get(0);
  2878. }
  2879.  
  2880. $(target).append('<div class="overlay">目标复制区域</div>');
  2881. previousCSS = {
  2882. "position": $(target).css("position"),
  2883. "display": $(target).css("display")
  2884. };
  2885. $(target).css({
  2886. "position": "relative",
  2887. "display": "block"
  2888. });
  2889. $(".html2md-cb" + suffix).parent().css({
  2890. "position": "relative",
  2891. "z-index": "99999"
  2892. })
  2893. });
  2894.  
  2895. $(document).on("mouseout", ".html2md-cb" + suffix, function () {
  2896. var target;
  2897.  
  2898. if (type === "this_level") {
  2899. target = $(".html2md-cb" + suffix).parent().next().get(0);
  2900. } else if (type === "child_level") {
  2901. target = $(".html2md-cb" + suffix).parent().parent().get(0);
  2902. }
  2903.  
  2904. $(target).find('.overlay').remove();
  2905. if (previousCSS) {
  2906. $(target).css(previousCSS);
  2907. }
  2908. $(".html2md-cb" + suffix).parent().css({
  2909. "position": "static"
  2910. })
  2911. });
  2912. }
  2913. }
  2914.  
  2915. async function addButtonWithTranslation(parent, suffix, type) {
  2916. var result;
  2917. $(document).on('click', '.translateButton' + suffix, debounce(async function () {
  2918. $(this).trigger('mouseout');
  2919. $(this).removeClass("translated");
  2920. $(this).text("翻译中");
  2921. $(this).css("cursor", "not-allowed");
  2922. $(this).prop("disabled", true);
  2923. var target, element_node, block, errerNum = 0;
  2924. if (type === "this_level") block = $(".translateButton" + suffix).parent().next();
  2925. else if (type === "child_level") block = $(".translateButton" + suffix).parent().parent();
  2926.  
  2927. // 重新翻译
  2928. if (result) {
  2929. if (result.translateDiv) {
  2930. $(result.translateDiv).remove();
  2931. }
  2932. if (!is_oldLatex) {
  2933. if (result.copyDiv) {
  2934. $(result.copyDiv).remove();
  2935. }
  2936. if (result.copyButton) {
  2937. $(result.copyButton).remove();
  2938. }
  2939. }
  2940. // 移除旧的事件
  2941. $(document).off("mouseover", ".translateButton" + suffix);
  2942. $(document).off("mouseout", ".translateButton" + suffix);
  2943. // 重新绑定悬停事件
  2944. if (hoverTargetAreaDisplay) bindHoverEvents(suffix, type);
  2945. }
  2946.  
  2947. // 分段翻译
  2948. if (enableSegmentedTranslation) {
  2949. var pElements = block.find("p, li");
  2950. for (let i = 0; i < pElements.length; i++) {
  2951. target = $(pElements[i]).eq(0).clone();
  2952. if (type === "child_level") $(target).children(':first').remove();
  2953. element_node = pElements[i];
  2954. if (type === "child_level") {
  2955. $(pElements[i]).append("<div></div>");
  2956. element_node = $(pElements[i]).find("div:last-child").get(0);
  2957. }
  2958. result = await blockProcessing(target, element_node, $(".translateButton" + suffix));
  2959. if (result.status) errerNum += 1;
  2960. $(target).remove();
  2961. if (translation == "deepl") await new Promise(resolve => setTimeout(resolve, 2000));
  2962. }
  2963. } else {
  2964. target = block.eq(0).clone();
  2965. if (type === "child_level") $(target).children(':first').remove();
  2966. element_node = $(block).get(0);
  2967. if (type === "child_level") {
  2968. $(parent).append("<div></div>");
  2969. element_node = $(parent).find("div:last-child").get(0);
  2970. }
  2971. //是否跳过折叠块
  2972. if ($(target).find('.spoiler').length > 0) {
  2973. const shouldSkip = await skiFoldingBlocks();
  2974. if (shouldSkip) {
  2975. $(target).find('.spoiler').remove();
  2976. } else {
  2977. $(target).find('.html2md-panel').remove();
  2978. }
  2979. }
  2980. result = await blockProcessing(target, element_node, $(".translateButton" + suffix));
  2981. if (result.status) errerNum += 1;
  2982. $(target).remove();
  2983. }
  2984.  
  2985. if (!errerNum) {
  2986. $(this).addClass("translated")
  2987. .text("已翻译")
  2988. .css("cursor", "pointer")
  2989. .removeClass("error")
  2990. .prop("disabled", false);
  2991. } else {
  2992. $(this).prop("disabled", false);
  2993. }
  2994.  
  2995. // 重新翻译
  2996. let currentText, is_error;
  2997. $(document).on("mouseover", ".translateButton" + suffix, function () {
  2998. currentText = $(this).text();
  2999. $(this).text("重新翻译");
  3000. if ($(this).hasClass("error")) {
  3001. is_error = true;
  3002. $(this).removeClass("error");
  3003. }
  3004. });
  3005.  
  3006. $(document).on("mouseout", ".translateButton" + suffix, function () {
  3007. $(this).text(currentText);
  3008. if (is_error) $(this).addClass("error");
  3009. });
  3010. }));
  3011.  
  3012. // 目标区域指示
  3013. function bindHoverEvents(suffix, type) {
  3014. var previousCSS;
  3015.  
  3016. $(document).on("mouseover", ".translateButton" + suffix, function () {
  3017. var target;
  3018.  
  3019. if (type === "this_level") {
  3020. target = $(".translateButton" + suffix).parent().next().get(0);
  3021. } else if (type === "child_level") {
  3022. target = $(".translateButton" + suffix).parent().parent().get(0);
  3023. }
  3024.  
  3025. $(target).append('<div class="overlay">目标翻译区域</div>');
  3026.  
  3027. previousCSS = {
  3028. "position": $(target).css("position"),
  3029. "display": $(target).css("display")
  3030. };
  3031. $(target).css({
  3032. "position": "relative",
  3033. "display": ($(target).hasClass('question-response')) ? "block" : $(target).css("display")
  3034. });
  3035.  
  3036. $(".translateButton" + suffix).parent().css({
  3037. "position": "relative",
  3038. "z-index": "99999"
  3039. });
  3040. });
  3041.  
  3042. $(document).on("mouseout", ".translateButton" + suffix, function () {
  3043. var target;
  3044.  
  3045. if (type === "this_level") {
  3046. target = $(".translateButton" + suffix).parent().next().get(0);
  3047. } else if (type === "child_level") {
  3048. target = $(".translateButton" + suffix).parent().parent().get(0);
  3049. }
  3050.  
  3051. $(target).find('.overlay').remove();
  3052.  
  3053. if (previousCSS) {
  3054. $(target).css(previousCSS);
  3055. }
  3056.  
  3057. $(".translateButton" + suffix).parent().css({
  3058. "position": "static"
  3059. });
  3060. });
  3061. }
  3062.  
  3063. if (hoverTargetAreaDisplay) bindHoverEvents(suffix, type);
  3064. }
  3065.  
  3066. // 块处理
  3067. async function blockProcessing(target, element_node, button) {
  3068. if (is_oldLatex) {
  3069. $(target).find('.overlay').remove();
  3070. target.markdown = $(target).html();
  3071. } else if (!target.markdown) {
  3072. target.markdown = turndownService.turndown($(target).html());
  3073. }
  3074. const textarea = document.createElement('textarea');
  3075. textarea.value = target.markdown;
  3076. var result = await translateProblemStatement(textarea.value, element_node, $(button));
  3077. //
  3078. if (result.status == 1) {
  3079. $(button).addClass("error")
  3080. .text("翻译中止")
  3081. .css("cursor", "pointer")
  3082. .prop("disabled", false);
  3083. $(result.translateDiv).remove();
  3084. $(target).remove();
  3085. } else if (result.status == 2) {
  3086. result.translateDiv.classList.add("error_translate");
  3087. $(button).addClass("error")
  3088. .text("翻译出错")
  3089. .css("cursor", "pointer")
  3090. .prop("disabled", false);
  3091. $(target).remove();
  3092. }
  3093. return result;
  3094. }
  3095.  
  3096. function addConversionButton() {
  3097. // 题目页添加按钮
  3098. if (window.location.href.includes("problem")) {
  3099. var exContentsPageClasses = ["sample-tests",];
  3100. $('.problem-statement').children('div').each(function () {
  3101. var className = $(this).attr('class');
  3102. if (!exContentsPageClasses.includes(className)) {
  3103. var id = "_" + getRandomNumber(8);
  3104. addButtonPanel(this, id, "this_level");
  3105. addButtonWithHTML2MD(this, id, "this_level");
  3106. addButtonWithCopy(this, id, "this_level");
  3107. addButtonWithTranslation(this, id, "this_level");
  3108. }
  3109. });
  3110. }
  3111. // 添加按钮到ttypography部分
  3112. $(".ttypography").each(function () {
  3113. // 题目页特判
  3114. if (!$(this).parent().hasClass('problemindexholder')) {
  3115. let id = "_comment_" + getRandomNumber(8);
  3116. addButtonPanel(this, id, "this_level");
  3117. addButtonWithHTML2MD(this, id, "this_level");
  3118. addButtonWithCopy(this, id, "this_level");
  3119. addButtonWithTranslation(this, id, "this_level");
  3120. }
  3121. });
  3122.  
  3123. // 添加按钮到spoiler部分
  3124. $('.spoiler-content').each(function () {
  3125. if ($(this).find('.html2md-panel').length === 0) {
  3126. let id = "_spoiler_" + getRandomNumber(8);
  3127. addButtonPanel(this, id, "child_level");
  3128. addButtonWithHTML2MD(this, id, "child_level");
  3129. addButtonWithCopy(this, id, "child_level");
  3130. addButtonWithTranslation(this, id, "child_level");
  3131. }
  3132. });
  3133.  
  3134. // 添加按钮到titled部分
  3135. (function () {
  3136. var elements = [".Virtual.participation", ".Attention", ".Practice"];//只为部分titled添加
  3137. $.each(elements, function (index, value) {
  3138. $(value).each(function () {
  3139. let id = "_titled_" + getRandomNumber(8);
  3140. var $nextDiv = $(this).next().children().get(0);
  3141. addButtonPanel($nextDiv, id, "child_level", true);
  3142. addButtonWithTranslation($nextDiv, id, "child_level");
  3143. });
  3144. });
  3145. })();
  3146. if (is_mSite) {
  3147. $("div[class='_IndexPage_notice']").each(function () {
  3148. let id = "_titled_" + getRandomNumber(8);
  3149. addButtonPanel(this, id, "this_level", true);
  3150. addButtonWithTranslation(this, id, "this_level");
  3151. });
  3152. }
  3153.  
  3154. // 添加按钮到比赛QA部分
  3155. $(".question-response").each(function () {
  3156. let id = "_question_" + getRandomNumber(8);
  3157. addButtonPanel(this, id, "this_level", true);
  3158. addButtonWithTranslation(this, id, "this_level");
  3159. });
  3160. if (is_mSite) {
  3161. $("div._ProblemsPage_announcements table tbody tr:gt(0)").each(function () {
  3162. var $nextDiv = $(this).find("td:first");
  3163. let id = "_question_" + getRandomNumber(8);
  3164. addButtonPanel($nextDiv, id, "this_level", true);
  3165. addButtonWithTranslation($nextDiv, id, "this_level");
  3166. });
  3167. }
  3168.  
  3169. // 添加按钮到弹窗confirm-proto部分
  3170. $(".confirm-proto").each(function () {
  3171. let id = "_titled_" + getRandomNumber(8);
  3172. var $nextDiv = $(this).children().get(0);
  3173. addButtonPanel($nextDiv, id, "this_level", true);
  3174. addButtonWithTranslation($nextDiv, id, "this_level");
  3175. });
  3176.  
  3177. // 添加按钮到_CatalogHistorySidebarFrame_item部分
  3178. $("._CatalogHistorySidebarFrame_item").each(function () {
  3179. let id = "_history_sidebar_" + getRandomNumber(8);
  3180. addButtonPanel(this, id, "this_level", true);
  3181. addButtonWithTranslation(this, id, "this_level");
  3182. });
  3183.  
  3184. $(".problem-lock-link").on("click", function () {
  3185. $(".popup .content div").each(function () {
  3186. let id = "_popup_" + getRandomNumber(8);
  3187. addButtonPanel(this, id, "this_level", true);
  3188. addButtonWithTranslation(this, id, "this_level");
  3189. });
  3190. });
  3191.  
  3192. // 添加按钮到弹窗alert部分
  3193. $(".alert:not(.CFBetter_alert)").each(function () {
  3194. let id = "_alert_" + getRandomNumber(8);
  3195. addButtonPanel(this, id, "this_level", true);
  3196. addButtonWithTranslation(this, id, "this_level");
  3197. });
  3198.  
  3199. // 添加按钮到talk-text部分
  3200. $(".talk-text").each(function () {
  3201. let id = "_talk-text_" + getRandomNumber(8);
  3202. addButtonPanel(this, id, "child_level", true);
  3203. addButtonWithTranslation(this, id, "child_level");
  3204. });
  3205. };
  3206.  
  3207. //弹窗翻译
  3208. function alertZh() {
  3209. var _alert = window.alert;
  3210. window.alert = async function (msg) {
  3211. _alert(msg + "\n=========翻译=========\n" + await translate_deepl(msg));
  3212. return true;
  3213. }
  3214. };
  3215.  
  3216. // 折叠块
  3217. function ExpandFoldingblocks() {
  3218. $('.spoiler').addClass('spoiler-open');
  3219. $('.spoiler-content').attr('style', '');
  3220. };
  3221.  
  3222. // 折叠块渲染优化
  3223. function RenderPerfOpt() {
  3224. return new Promise(function (resolve) {
  3225. var currentIndex = 0;
  3226. var delay = 50;
  3227. var maxDelay = 1000;
  3228.  
  3229. var elements = $('.spoiler-content');
  3230. var batchSize = 10;
  3231. var initialDelay = 50;
  3232.  
  3233. function processBatch(callback) {
  3234. var endIndex = currentIndex + batchSize;
  3235. for (var i = currentIndex; i < endIndex; i++) {
  3236. if (i >= elements.length) {
  3237. callback();
  3238. resolve();
  3239. return;
  3240. }
  3241. var element = elements.eq(i);
  3242. var height = element.outerHeight();
  3243. element.css('contain-intrinsic-size', height + 'px');
  3244. }
  3245.  
  3246. currentIndex += batchSize;
  3247.  
  3248. // 延时
  3249. delay *= 2;
  3250. if (delay >= maxDelay) delay = initialDelay;
  3251.  
  3252. setTimeout(function () {
  3253. processBatch(callback); // 递归
  3254. }, delay);
  3255. }
  3256.  
  3257. processBatch(function () {
  3258. GM_addStyle(`
  3259. .spoiler-content {
  3260. content-visibility: auto;
  3261. }
  3262. `);
  3263. });
  3264. });
  3265. }
  3266.  
  3267. // 分页
  3268. function CommentPagination() {
  3269. GM_addStyle(`
  3270. /* 分页 */
  3271. .comments > .comment {
  3272. display: none;
  3273. }
  3274. #next-page-btn, #prev-page-btn {
  3275. display: none;
  3276. }
  3277. #jump-input, #items-per-page{
  3278. height: 22px;
  3279. border: 1px solid #dcdfe6;
  3280. border-radius: 0.3rem;
  3281. }
  3282. #jump-input:focus-visible{
  3283. border-style: solid;
  3284. border-color: #3f51b5;
  3285. outline: none;
  3286. }
  3287. `);
  3288. $('.comments').after(`
  3289. <div id="pagBar" style="display: flex; align-items: center; justify-content: center; color: #606266;">
  3290. <label for="items-per-page">每页展示主楼数:</label>
  3291. <select id="items-per-page" style="margin-right: 15px;">
  3292. <option value="5">5</option>
  3293. <option value="10">10</option>
  3294. <option value="20">20</option>
  3295. </select>
  3296. <div class="paging" style="margin-right: 15px;">
  3297. <span id="current-page">1</span> / <span id="total-pages"></span>
  3298. </div>
  3299. <input type="text" id="jump-input" placeholder="跳转到页码">
  3300. <button type="button" id="jump-btn" class="html2mdButton">跳转</button>
  3301. <button id="prev-page-btn" class="html2mdButton">上一页</button>
  3302. <button id="next-page-btn" class="html2mdButton">下一页</button>
  3303. </div>
  3304. `);
  3305.  
  3306. var batchSize = 5;
  3307. var elements = $(".comments > .comment");
  3308. elements.last().detach(); // 去掉最后一个元素(评论框)
  3309. var start = 0;
  3310. var end = batchSize;
  3311. var currentPage = 1;
  3312. var displayedIndexes = []; // 存储已显示元素的索引
  3313.  
  3314. function showBatch(start, end) {
  3315. // 隐藏上一页
  3316. for (var i = 0; i < displayedIndexes.length; i++) {
  3317. elements.eq(displayedIndexes[i]).hide();
  3318. }
  3319.  
  3320. displayedIndexes = [];
  3321.  
  3322. // 显示当前页
  3323. elements.slice(start, end).each(function (index) {
  3324. $(this).show();
  3325. displayedIndexes.push(start + index);
  3326. });
  3327.  
  3328. // 更新页码和翻页按钮
  3329. $("#current-page").text(currentPage);
  3330. $("#total-pages").text(Math.ceil(elements.length / batchSize));
  3331.  
  3332. if (currentPage === 1) $("#prev-page-btn").hide();
  3333. else $("#prev-page-btn").show();
  3334.  
  3335. if (end >= elements.length) $("#next-page-btn").hide();
  3336. else $("#next-page-btn").show();
  3337. }
  3338.  
  3339. // 初始化第一页
  3340. showBatch(0, parseInt($("#items-per-page").val()));
  3341.  
  3342. $("#prev-page-btn").on("click", function () {
  3343. var itemsPerPage = parseInt($("#items-per-page").val());
  3344. var start = (currentPage - 2) * itemsPerPage;
  3345. var end = (currentPage - 1) * itemsPerPage;
  3346.  
  3347. currentPage--;
  3348.  
  3349. showBatch(start, end);
  3350. });
  3351.  
  3352. $("#next-page-btn").on("click", function () {
  3353. var itemsPerPage = parseInt($("#items-per-page").val());
  3354. var start = currentPage * itemsPerPage;
  3355. var end = (currentPage + 1) * itemsPerPage;
  3356.  
  3357. currentPage++;
  3358.  
  3359. showBatch(start, end);
  3360. });
  3361.  
  3362. $("#jump-btn").on("click", function () {
  3363. var inputPage = parseInt($("#jump-input").val());
  3364.  
  3365. if (inputPage >= 1 && inputPage <= Math.ceil(elements.length / parseInt($("#items-per-page").val()))) {
  3366. var itemsPerPage = parseInt($("#items-per-page").val());
  3367. start = (inputPage - 1) * itemsPerPage;
  3368. end = inputPage * itemsPerPage;
  3369.  
  3370. currentPage = inputPage; // 更新当前页码
  3371.  
  3372. showBatch(start, end);
  3373. }
  3374. });
  3375.  
  3376. $("#items-per-page").on("change", function () {
  3377. batchSize = parseInt($(this).val());
  3378. let page = Math.floor(start / batchSize);
  3379. currentPage = !page ? 1 : page;
  3380. showBatch(currentPage * batchSize, (currentPage + 1) * batchSize);
  3381. });
  3382. }
  3383.  
  3384. // 跳转洛谷
  3385. async function CF2luogu() {
  3386. const getProblemId = () => {
  3387. const url = window.location.href;
  3388. const regex = url.includes('/contest/')
  3389. ? /\/contest\/(\d+)\/problem\/([A-Za-z\d]+)/
  3390. : /\/problemset\/problem\/(\d+)\/([A-Za-z\d]+)/;
  3391. const matchResult = url.match(regex);
  3392. return matchResult && matchResult.length >= 3
  3393. ? `${matchResult[1]}${matchResult[2]}`
  3394. : '';
  3395. };
  3396.  
  3397. const checkLinkExistence = (url) => {
  3398. return new Promise((resolve, reject) => {
  3399. GM.xmlHttpRequest({
  3400. method: "GET",
  3401. url,
  3402. headers: { "Range": "bytes=0-9999" }, // 获取前10KB数据
  3403. onload(response) {
  3404. if (response.responseText.match(/题目未找到/g)) {
  3405. resolve(false);
  3406. } else {
  3407. resolve(true);
  3408. }
  3409. },
  3410. onerror(error) {
  3411. reject(error);
  3412. }
  3413. });
  3414. });
  3415. };
  3416. const panelElement = $("<div>")
  3417. .addClass("html2md-panel")
  3418. .attr("id", "CF2luoguPanel")
  3419. .insertBefore('.problemindexholder');
  3420.  
  3421. const url = `https://www.luogu.com.cn/problem/CF${getProblemId()}`;
  3422. const result = await checkLinkExistence(url);
  3423. if (getProblemId() && result) {
  3424. const problemLink = $("<a>")
  3425. .attr("id", "problemLink")
  3426. .attr("href", url)
  3427. .attr("target", "_blank")
  3428. .html(`<button style="height: 25px;" class="html2mdButton"><img style="width:45px; margin-right:2px;" src="https://cdn.luogu.com.cn/fe/logo.png"></button>`);
  3429. panelElement.append(problemLink);
  3430. }
  3431. }
  3432.  
  3433. // 等待Latex渲染队列全部完成
  3434. function waitUntilIdleThenDo(callback) {
  3435. var intervalId = setInterval(function () {
  3436. var queue = MathJax.Hub.queue;
  3437. if (queue.pending === 0 && queue.running === 0) {
  3438. clearInterval(intervalId);
  3439. callback();
  3440. }
  3441. }, 100);
  3442. }
  3443.  
  3444. // 字数超限确认
  3445. function showWordsExceededDialog(button) {
  3446. return new Promise(resolve => {
  3447. const styleElement = GM_addStyle(darkenPageStyle);
  3448. $(button).removeClass("translated");
  3449. $(button).text("字数超限");
  3450. $(button).css("cursor", "not-allowed");
  3451. $(button).prop("disabled", true);
  3452. let htmlString = `
  3453. <div class="wordsExceeded">
  3454. <h2>字数超限!</h2>
  3455. <p>注意,即将翻译的内容字数超过了4950个字符,您可能选择了错误的翻译按钮</p>
  3456. <div style="display:flex; padding:5px 0px; align-items: center;">
  3457. `+ helpCircleHTML + `
  3458. <p>
  3459. 由于实现方式,区域中会出现多个翻译按钮,请点击更小的子区域中的翻译按钮,
  3460. <br>或者在设置面板中开启 分段翻译 后重试。
  3461. </p>
  3462. </div>
  3463. <p>对于免费的接口,大量请求可能导致你的IP被暂时禁止访问,对于GPT,会消耗大量的token</p>
  3464. <p>您确定要继续翻译吗?</p>
  3465. <div style="display:flex; padding-top:10px">
  3466. <button id="continueButton">继续</button><button id="cancelButton">取消</button>
  3467. </div>
  3468. </div>
  3469. `;
  3470. $('body').before(htmlString);
  3471. $("#continueButton").click(function () {
  3472. $(styleElement).remove();
  3473. $('.wordsExceeded').remove();
  3474. resolve(true);
  3475. });
  3476. $("#cancelButton").click(function () {
  3477. $(styleElement).remove();
  3478. $('.wordsExceeded').remove();
  3479. resolve(false);
  3480. });
  3481. });
  3482. }
  3483.  
  3484. //跳过折叠块确认
  3485. function skiFoldingBlocks() {
  3486. return new Promise(resolve => {
  3487. const styleElement = GM_addStyle(darkenPageStyle);
  3488. let htmlString = `
  3489. <div class="wordsExceeded">
  3490. <h2>是否跳过折叠块?</h2>
  3491. <p></p>
  3492. <div style="display:grid; padding:5px 0px; align-items: center;">
  3493. <p>
  3494. 即将翻译的区域中包含折叠块,折叠块可能是代码,通常不需要翻译,现在您需要选择是否跳过这些折叠块,
  3495. </p>
  3496. <p>
  3497. 如果其中有您需要翻译的折叠块,可以稍后再单独点击这些折叠块内的翻译按钮进行翻译
  3498. </p>
  3499. </div>
  3500. <p>要跳过折叠块吗?(建议选择跳过)</p>
  3501. <div style="display:flex; padding-top:10px">
  3502. <button id="cancelButton">否</button><button id="skipButton">跳过</button>
  3503. </div>
  3504. </div>
  3505. `;
  3506. $('body').before(htmlString);
  3507. $("#skipButton").click(function () {
  3508. $(styleElement).remove();
  3509. $('.wordsExceeded').remove();
  3510. resolve(true);
  3511. });
  3512. $("#cancelButton").click(function () {
  3513. $(styleElement).remove();
  3514. $('.wordsExceeded').remove();
  3515. resolve(false);
  3516. });
  3517. });
  3518. }
  3519.  
  3520. // 翻译框/翻译处理器
  3521. var translatedText = "";
  3522. async function translateProblemStatement(text, element_node, button) {
  3523. let status = 0;
  3524. let id = getRandomNumber(8);
  3525. let matches = [];
  3526. let replacements = {};
  3527. // 创建元素并放在element_node的后面
  3528. const translateDiv = document.createElement('div');
  3529. translateDiv.setAttribute('id', id);
  3530. translateDiv.classList.add('translate-problem-statement');
  3531. const spanElement = document.createElement('span');
  3532. translateDiv.appendChild(spanElement);
  3533. element_node.insertAdjacentElement('afterend', translateDiv);
  3534. // 替换latex公式
  3535. if (is_oldLatex) {
  3536. //去除开头结尾的<p>标签
  3537. text = text.replace(/^<p>/i, "");
  3538. text = text.replace(/<\/p>$/i, "");
  3539. //
  3540. let i = 0;
  3541. let regex = /<span\s+class="tex-span">.*?<\/span>/gi;
  3542. matches = text.match(regex);
  3543. try {
  3544. for (i; i < matches.length; i++) {
  3545. let match = matches[i];
  3546. text = text.replace(match, `【${i + 1}】`);
  3547. replacements[`【${i + 1}】`] = match;
  3548. }
  3549. } catch (e) { }
  3550. } else if (translation != "openai") {
  3551. // 使用GPT翻译时不必替换latex公式
  3552. let i = 0;
  3553. // 块公式
  3554. matches = matches.concat(text.match(/\$\$([\s\S]*?)\$\$/g));
  3555. try {
  3556. for (i; i < matches.length; i++) {
  3557. let match = matches[i];
  3558. text = text.replace(match, `【${i + 1}】`);
  3559. replacements[`【${i + 1}】`] = match;
  3560. }
  3561. } catch (e) { }
  3562. // 行内公式
  3563. matches = matches.concat(text.match(/\$(.*?)\$/g));
  3564. try {
  3565. for (i; i < matches.length; i++) {
  3566. let match = matches[i];
  3567. text = text.replace(match, `【${i + 1}】`);
  3568. replacements[`【${i + 1}】`] = match;
  3569. }
  3570. } catch (e) { }
  3571. }
  3572.  
  3573. if (text.length > 4950) {
  3574. const shouldContinue = await showWordsExceededDialog(button);
  3575. if (!shouldContinue) {
  3576. status = 1;
  3577. return {
  3578. translateDiv: translateDiv,
  3579. status: status
  3580. };
  3581. }
  3582. }
  3583. // 翻译
  3584. if (translation == "deepl") {
  3585. translateDiv.innerHTML = "正在使用 deepl 翻译中……请稍等";
  3586. translatedText = await translate_deepl(text);
  3587. } else if (translation == "youdao") {
  3588. translateDiv.innerHTML = "正在使用 有道 翻译中……请稍等";
  3589. translatedText = await translate_youdao_mobile(text);
  3590. } else if (translation == "google") {
  3591. translateDiv.innerHTML = "正在使用 google 翻译中……请稍等";
  3592. translatedText = await translate_gg(text);
  3593. } else if (translation == "openai") {
  3594. try {
  3595. translateDiv.innerHTML = "正在使用 ChatGPT 翻译中……" +
  3596. "<br><br>应用的配置:" + opneaiConfig.configurations[opneaiConfig.choice].note +
  3597. "<br><br>使用 ChatGPT 翻译需要很长的时间,请耐心等待";
  3598. translatedText = await translate_openai(text);
  3599. } catch (error) {
  3600. status = 2;
  3601. translatedText = error;
  3602. }
  3603. }
  3604. if (/^翻译出错/.test(translatedText)) status = 2;
  3605. // 还原latex公式
  3606. translatedText = translatedText.replace(/】【/g, '】 【');
  3607. if (is_oldLatex) {
  3608. translatedText = "<p>" + translatedText;
  3609. translatedText += "</p>";
  3610. try {
  3611. for (let i = 0; i < matches.length; i++) {
  3612. let match = matches[i];
  3613. let replacement = replacements[`【${i + 1}】`];
  3614. let regex;
  3615. regex = new RegExp(`【\\s*${i + 1}\\s*】`, 'g');
  3616. translatedText = translatedText.replace(regex, replacement);
  3617. regex = new RegExp(`\\[\\s*${i + 1}\\s*\\]`, 'g');
  3618. translatedText = translatedText.replace(regex, replacement);
  3619. regex = new RegExp(`【\\s*${i + 1}(?![】\\d])`, 'g');
  3620. translatedText = translatedText.replace(regex, replacement);
  3621. regex = new RegExp(`(?<![【\\d])${i + 1}\\s*】`, 'g');
  3622. translatedText = translatedText.replace(regex, " " + replacement);
  3623. }
  3624. } catch (e) { }
  3625. }
  3626. else if (translation != "openai") {
  3627. try {
  3628. for (let i = 0; i < matches.length; i++) {
  3629. let match = matches[i];
  3630. let replacement = replacements[`【${i + 1}】`];
  3631. let regex;
  3632. regex = new RegExp(`【\\s*${i + 1}\\s*】`, 'g');
  3633. translatedText = translatedText.replace(regex, replacement);
  3634. regex = new RegExp(`\\[\\s*${i + 1}\\s*\\]`, 'g');
  3635. translatedText = translatedText.replace(regex, replacement);
  3636. regex = new RegExp(`【\\s*${i + 1}(?![】\\d])`, 'g');
  3637. translatedText = translatedText.replace(regex, replacement);
  3638. regex = new RegExp(`(?<![【\\d])${i + 1}\\s*】`, 'g');
  3639. translatedText = translatedText.replace(regex, " " + replacement);
  3640. }
  3641. } catch (e) { }
  3642. }
  3643.  
  3644. // 结果复制按钮
  3645. if (!is_oldLatex) {
  3646. // 创建一个隐藏的元素来保存 translatedText 的值
  3647. var textElement = document.createElement("div");
  3648. textElement.style.display = "none";
  3649. textElement.textContent = translatedText;
  3650. translateDiv.parentNode.insertBefore(textElement, translateDiv);
  3651.  
  3652. // 按钮
  3653. var copyButton = document.createElement("button");
  3654. copyButton.textContent = "Copy";
  3655. var wrapperDiv = document.createElement("div");
  3656. $(wrapperDiv).css({
  3657. display: "flex",
  3658. justifyContent: "flex-end"
  3659. });
  3660. $(wrapperDiv).append(copyButton);
  3661. $(copyButton).addClass("html2mdButton html2md-cb");
  3662.  
  3663. copyButton.addEventListener("click", function () {
  3664. var translatedText = textElement.textContent;
  3665. GM_setClipboard(translatedText);
  3666. $(this).addClass("copied").text("Copied");
  3667. // 更新复制按钮文本
  3668. setTimeout(() => {
  3669. $(this).removeClass("copied");
  3670. $(this).text("Copy");
  3671. }, 2000);
  3672. });
  3673. translateDiv.parentNode.insertBefore(wrapperDiv, translateDiv);
  3674. }
  3675.  
  3676. // 转义LaTex中的特殊符号
  3677. if (!is_oldLatex) {
  3678. const escapeRules = [
  3679. { pattern: /(?<!\\)>(?!\s)/g, replacement: " &gt; " }, // >符号
  3680. { pattern: /(?<!\\)</g, replacement: " &lt; " }, // <符号
  3681. { pattern: /(?<!\\)\*/g, replacement: " &#42; " }, // *符号
  3682. { pattern: /(?<!\\)&(?=\s)/g, replacement: "\\&" }, // &符号
  3683. { pattern: /\\&/g, replacement: "\\\\&" }, // &符号
  3684. { pattern: /(?<!\\)\\\\(?=\s)/g, replacement: "\\\\\\\\" }, // \\符号
  3685. ];
  3686.  
  3687. let latexMatches = [...translatedText.matchAll(/\$\$([\s\S]*?)\$\$|\$(.*?)\$|\$([\s\S]*?)\$/g)];
  3688.  
  3689. for (const match of latexMatches) {
  3690. const matchedText = match[0];
  3691. var escapedText = matchedText;
  3692. for (const rule of escapeRules) {
  3693. escapedText = matchedText.replaceAll(rule.pattern, rule.replacement);
  3694. }
  3695. translatedText = translatedText.replace(matchedText, escapedText);
  3696. }
  3697. }
  3698.  
  3699. // 使符合mathjx的转换语法
  3700. const ruleMap = [
  3701. { pattern: /(\s_[\u4e00-\u9fa5]+_)([\u4e00-\u9fa5]+)/g, replacement: "$1 $2" }, // 斜体
  3702. { pattern: /(_[\u4e00-\u9fa5]+_\s)([\u4e00-\u9fa5]+)/g, replacement: " $1$2" },
  3703. { pattern: /(_[\u4e00-\u9fa5]+_)([\u4e00-\u9fa5]+)/g, replacement: " $1 $2" },
  3704. { pattern: /(\$\$[\r\n])/g, replacement: "$$$$$$$$$$$$" }, // $$ 行间
  3705. { pattern: /(?<!\$)\$(?!\$)/g, replacement: "$$$$$" }, // $ 内联
  3706. ];
  3707. ruleMap.forEach(({ pattern, replacement }) => {
  3708. translatedText = translatedText.replace(pattern, replacement);
  3709. });
  3710.  
  3711. // 更新
  3712. if (is_oldLatex) {
  3713. // oldlatex
  3714. translatedText = $.parseHTML(translatedText);
  3715. $(translateDiv).empty().append($(translatedText));
  3716. return {
  3717. translateDiv: translateDiv,
  3718. status: status
  3719. };
  3720. } else {
  3721. // 渲染MarkDown
  3722. var md = window.markdownit();
  3723. var html = md.render(translatedText);
  3724. translateDiv.innerHTML = html;
  3725. // 渲染Latex
  3726. MathJax.Hub.Queue(["Typeset", MathJax.Hub, translateDiv]);
  3727. return {
  3728. translateDiv: translateDiv,
  3729. status: status,
  3730. copyDiv: textElement,
  3731. copyButton: copyButton
  3732. };
  3733. }
  3734.  
  3735. }
  3736.  
  3737. // ChatGPT
  3738. async function translate_openai(raw) {
  3739. var openai_retext = "";
  3740. var data;
  3741. if (is_oldLatex) {
  3742. data = {
  3743. model: (openai_model !== null && openai_model !== "") ? openai_model : 'gpt-3.5-turbo',
  3744. messages: [{
  3745. role: "user",
  3746. content: "请将下面的文本翻译为中文,这是一道编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的【】、HTML标签本身以及其中的内容不翻译不变动,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw
  3747. }],
  3748. temperature: 0.7,
  3749. ...Object.assign({}, ...openai_data)
  3750. };
  3751. } else {
  3752. data = {
  3753. model: (openai_model !== null && openai_model !== "") ? openai_model : 'gpt-3.5-turbo',
  3754. messages: [{
  3755. role: "user",
  3756. content: "请将下面的文本翻译为中文,这是一道编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw
  3757. }],
  3758. temperature: 0.7
  3759. };
  3760. };
  3761. return new Promise(function (resolve, reject) {
  3762. GM_xmlhttpRequest({
  3763. method: 'POST',
  3764. url: (openai_proxy !== null && openai_proxy !== "") ? openai_proxy : 'https://api.openai.com/v1/chat/completions',
  3765.  
  3766. data: JSON.stringify(data),
  3767. headers: {
  3768. 'Content-Type': 'application/json',
  3769. 'Authorization': 'Bearer ' + openai_key,
  3770. ...Object.assign({}, ...openai_header)
  3771. },
  3772. responseType: 'json',
  3773. onload: function (response) {
  3774. if (!response.response) {
  3775. reject("发生了未知的错误,如果你启用了代理API,请确认是否填写正确,并确保代理能够正常工作。\n\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈 请注意打码响应报文的敏感部分\n\n响应报文:" + JSON.stringify(response));
  3776. }
  3777. else if (!response.response.choices || response.response.choices.length < 1 || !response.response.choices[0].message) {
  3778. resolve("翻译出错,请重试\n\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈 \n\n报错信息:" + JSON.stringify(response.response, null, '\n'));
  3779. } else {
  3780. openai_retext = response.response.choices[0].message.content;
  3781. resolve(openai_retext);
  3782. }
  3783. },
  3784. onerror: function (response) {
  3785. reject("发生了未知的错误,请确认你是否能正常访问OpenAi的接口,如果使用代理API,请检查是否正常工作\n\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈 请注意打码响应报文的敏感部分\n\n响应报文:" + JSON.stringify(response));
  3786. },
  3787. });
  3788. });
  3789. }
  3790.  
  3791. //--谷歌翻译--start
  3792. async function translate_gg(raw) {
  3793. return new Promise((resolve, reject) => {
  3794. const url = 'https://translate.google.com/m';
  3795. const params = `tl=zh-CN&q=${encodeURIComponent(raw)}`;
  3796.  
  3797. GM_xmlhttpRequest({
  3798. method: 'GET',
  3799. url: `${url}?${params}`,
  3800. onload: function (response) {
  3801. const html = response.responseText;
  3802. const translatedText = $(html).find('.result-container').text();
  3803. resolve(translatedText);
  3804. },
  3805. onerror: function (error) {
  3806. console.error('Error:', error);
  3807. reject(error);
  3808. }
  3809. });
  3810. });
  3811. }
  3812. //--谷歌翻译--end
  3813.  
  3814. //--有道翻译m--start
  3815. async function translate_youdao_mobile(raw) {
  3816. const options = {
  3817. method: "POST",
  3818. url: 'http://m.youdao.com/translate',
  3819. data: "inputtext=" + encodeURIComponent(raw) + "&type=AUTO",
  3820. anonymous: true,
  3821. headers: {
  3822. "Content-Type": "application/x-www-form-urlencoded",
  3823. 'Host': 'm.youdao.com',
  3824. 'Origin': 'http://m.youdao.com',
  3825. 'Referer': 'http://m.youdao.com/translate',
  3826. }
  3827. }
  3828. return await BaseTranslate('有道翻译mobile', raw, options, res => /id="translateResult">\s*?<li>([\s\S]*?)<\/li>\s*?<\/ul/.exec(res)[1])
  3829. }
  3830. //--有道翻译m--end
  3831.  
  3832. //--Deepl翻译--start
  3833. function getTimeStamp(iCount) {
  3834. const ts = Date.now();
  3835. if (iCount !== 0) {
  3836. iCount = iCount + 1;
  3837. return ts - (ts % iCount) + iCount;
  3838. } else {
  3839. return ts;
  3840. }
  3841. }
  3842.  
  3843. async function translate_deepl(raw) {
  3844. const id = (Math.floor(Math.random() * 99999) + 100000) * 1000;
  3845. const data = {
  3846. jsonrpc: '2.0',
  3847. method: 'LMT_handle_texts',
  3848. id,
  3849. params: {
  3850. splitting: 'newlines',
  3851. lang: {
  3852. source_lang_user_selected: 'auto',
  3853. target_lang: 'ZH',
  3854. },
  3855. texts: [{
  3856. text: raw,
  3857. requestAlternatives: 3
  3858. }],
  3859. timestamp: getTimeStamp(raw.split('i').length - 1)
  3860. }
  3861. }
  3862. let postData = JSON.stringify(data);
  3863. if ((id + 5) % 29 === 0 || (id + 3) % 13 === 0) {
  3864. postData = postData.replace('"method":"', '"method" : "');
  3865. } else {
  3866. postData = postData.replace('"method":"', '"method": "');
  3867. }
  3868. const options = {
  3869. method: 'POST',
  3870. url: 'https://www2.deepl.com/jsonrpc',
  3871. data: postData,
  3872. headers: {
  3873. 'Content-Type': 'application/json',
  3874. 'Host': 'www2.deepl.com',
  3875. 'Origin': 'https://www.deepl.com',
  3876. 'Referer': 'https://www.deepl.com/',
  3877. },
  3878. anonymous: true,
  3879. nocache: true,
  3880. }
  3881. return await BaseTranslate('Deepl翻译', raw, options, res => JSON.parse(res).result.texts[0].text)
  3882. }
  3883.  
  3884. //--Deepl翻译--end
  3885.  
  3886. //--异步请求包装工具--start
  3887. async function PromiseRetryWrap(task, options, ...values) {
  3888. const { RetryTimes, ErrProcesser } = options || {};
  3889. let retryTimes = RetryTimes || 5;
  3890. const usedErrProcesser = ErrProcesser || (err => { throw err });
  3891. if (!task) return;
  3892. while (true) {
  3893. try {
  3894. return await task(...values);
  3895. } catch (err) {
  3896. if (!--retryTimes) {
  3897. console.log(err);
  3898. return usedErrProcesser(err);
  3899. }
  3900. }
  3901. }
  3902. }
  3903.  
  3904. async function BaseTranslate(name, raw, options, processer) {
  3905. let errtext;
  3906. const toDo = async () => {
  3907. var tmp;
  3908. try {
  3909. const data = await Request(options);
  3910. tmp = data.responseText;
  3911. const result = await processer(tmp);
  3912. if (result) sessionStorage.setItem(name + '-' + raw, result);
  3913. return result
  3914. } catch (err) {
  3915. errtext = tmp;
  3916. throw {
  3917. responseText: tmp,
  3918. err: err
  3919. }
  3920. }
  3921. }
  3922. return await PromiseRetryWrap(toDo, { RetryTimes: 3, ErrProcesser: () => "翻译出错,请重试或更换翻译接口\n\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈 请注意打码报错信息的敏感部分\n\n报错信息:" + errtext })
  3923. }
  3924.  
  3925. function Request(options) {
  3926. return new Promise((reslove, reject) => GM_xmlhttpRequest({ ...options, onload: reslove, onerror: reject }))
  3927. }
  3928.  
  3929. //--异步请求包装工具--end
  3930.  
  3931. // 开始
  3932. document.addEventListener("DOMContentLoaded", function () {
  3933. function checkJQuery(retryDelay) {
  3934. if (typeof jQuery === 'undefined') {
  3935. console.warn("JQuery未加载," + retryDelay + "毫秒后重试");
  3936. setTimeout(function () {
  3937. var newRetryDelay = Math.min(retryDelay * 2, 2000);
  3938. checkJQuery(newRetryDelay);
  3939. }, retryDelay);
  3940. } else {
  3941. init();
  3942. settingPanel();
  3943. checkScriptVersion();
  3944. toZH_CN();
  3945. var newElement = $("<div></div>").addClass("alert alert-info CFBetter_alert")
  3946. .html(`Codeforces Better! —— 正在等待页面资源加载……`)
  3947. .css({
  3948. "margin": "1em",
  3949. "text-align": "center",
  3950. "font-weight": "600",
  3951. "position": "relative"
  3952. });
  3953. var tip_SegmentedTranslation = $("<div></div>").addClass("alert alert-error CFBetter_alert")
  3954. .html(`Codeforces Better! —— 注意!分段翻译已开启,这会造成负面效果,
  3955. <p>除非你现在需要翻译超长篇的博客或者题目,否则请前往设置关闭分段翻译</p>`)
  3956. .css({
  3957. "margin": "1em",
  3958. "text-align": "center",
  3959. "font-weight": "600",
  3960. "position": "relative"
  3961. });
  3962.  
  3963. async function processPage() {
  3964. if (showLoading) newElement.html('Codeforces Better! —— 正在等待Latex渲染队列全部完成……');
  3965. await waitUntilIdleThenDo(async function () {
  3966. if (enableSegmentedTranslation) $(".menu-box:first").next().after(tip_SegmentedTranslation); //显示分段翻译警告
  3967. if (showJumpToLuogu) CF2luogu();
  3968. Promise.resolve()
  3969. .then(() => {
  3970. if (showLoading && expandFoldingblocks) newElement.html('Codeforces Better! —— 正在展开折叠块……');
  3971. return delay(100).then(() => { if (expandFoldingblocks) ExpandFoldingblocks() });
  3972. })
  3973. .then(() => {
  3974. if (showLoading && commentPaging) newElement.html('Codeforces Better! —— 正在对评论区分页……');
  3975. return delay(100).then(() => { if (commentPaging) CommentPagination() });
  3976. })
  3977. .then(() => {
  3978. if (showLoading) newElement.html('Codeforces Better! —— 正在加载按钮……');
  3979. return delay(100).then(() => addConversionButton());
  3980. })
  3981. .then(async () => {
  3982. if (showLoading && renderPerfOpt) newElement.html('Codeforces Better! —— 正在优化折叠块渲染……');
  3983. await delay(100);
  3984. if (renderPerfOpt) await RenderPerfOpt();
  3985. })
  3986. .then(() => {
  3987. alertZh();
  3988. if (showLoading) {
  3989. newElement.html('Codeforces Better! —— 加载已完成');
  3990. newElement.removeClass('alert-info').addClass('alert-success');
  3991. setTimeout(function () {
  3992. newElement.remove();
  3993. }, 3000);
  3994. }
  3995. })
  3996. .catch((error) => {
  3997. console.log(error);
  3998. });
  3999. });
  4000. }
  4001.  
  4002. function delay(ms) {
  4003. return new Promise((resolve) => setTimeout(resolve, ms));
  4004. }
  4005.  
  4006. if (showLoading) {
  4007. if (is_mSite) $("header").after(newElement);
  4008. else $(".menu-box:first").next().after(newElement);
  4009. }
  4010.  
  4011. if (loaded) {
  4012. processPage();
  4013. } else {
  4014. // 页面完全加载完成后执行
  4015. window.onload = function () {
  4016. processPage();
  4017. };
  4018. }
  4019. }
  4020. }
  4021. checkJQuery(50);
  4022. });
  4023.  
  4024. // 配置自动迁移代码(将在10个小版本后移除)
  4025. if (GM_getValue("openai_key") || GM_getValue("api2d_key")) {
  4026. const newConfig = { "choice": -1, "configurations": [] };
  4027. if (GM_getValue("openai_key")) {
  4028. let config1 = {
  4029. "note": "我的配置1",
  4030. "model": GM_getValue("openai_model") || "",
  4031. "key": GM_getValue("openai_key"),
  4032. "proxy": GM_getValue("openai_proxy") || "",
  4033. "_header": "",
  4034. "_data": ""
  4035. }
  4036. if (GM_getValue("translation") === "openai") newConfig.choice = 0;
  4037. newConfig.configurations.push(config1);
  4038. }
  4039. if (GM_getValue("api2d_key")) {
  4040. let config2 = {
  4041. "note": "api2d",
  4042. "model": GM_getValue("api2d_model"),
  4043. "key": GM_getValue("api2d_key"),
  4044. "proxy": GM_getValue("api2d_request_entry") + '/v1/chat/completions',
  4045. "_header": GM_getValue("x_api2d_no_cache") ? "" : " x-api2d-no-cache : 1",
  4046. "_data": ""
  4047. }
  4048. if (GM_getValue("translation") === "api2d") {
  4049. if (GM_getValue("openai_key")) newConfig.choice = 1;
  4050. else newConfig.choice = 0;
  4051. }
  4052. newConfig.configurations.push(config2);
  4053. }
  4054. GM_setValue("chatgpt-config", newConfig);
  4055. const keysToDelete = ["openai_key", "openai_model", "openai_proxy", "api2d_key", "api2d_model", "api2d_request_entry", "x_api2d_no_cache", "showOpneAiAdvanced"];
  4056. keysToDelete.forEach(key => {
  4057. if (GM_getValue(key) != undefined) GM_deleteValue(key);
  4058. });
  4059. if (GM_getValue("translation") === "api2d") GM_setValue("translation", "openai");
  4060. location.reload();
  4061. }
  4062.