Caveduck Modifier

修改Caveduck網站的樣式。

当前为 2024-12-09 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Caveduck Modifier
  3. // @namespace https://labs.muyi.tw/caveduck_modifier/
  4. // @version 0.29
  5. // @description 修改Caveduck網站的樣式。
  6. // @license AGPL-3.0-or-later
  7. // @author 慕儀
  8. // @match *://caveduck.io/*
  9. // @grant GM_addStyle
  10. // @icon data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgdmlld0JveD0iMCAwIDEyODAgMTI4MCI+CiAgPGRlZnM+CiAgICA8c3R5bGU+CiAgICAgIC5jbHMtMSB7CiAgICAgICAgZmlsbDogI2ZmZjsKICAgICAgfQoKICAgICAgLmNscy0yIHsKICAgICAgICBmaWxsOiAjZjJiNDEyOwogICAgICB9CiAgICA8L3N0eWxlPgogIDwvZGVmcz4KICA8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMjguNy4xLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogMS4yLjAgQnVpbGQgMTQyKSAgLS0+CiAgPGc+CiAgICA8ZyBpZD0iQ2F2ZWR1Y2siPgogICAgICA8ZyBpZD0iQ2F2ZWR1Y2stMiIgZGF0YS1uYW1lPSJDYXZlZHVjayI+CiAgICAgICAgPHBhdGggZD0iTTEwOTYuMSw0NTMuNWMzMDUuMiw0OTcuMywxNTIuNiw3NDYtNDU3LjgsNzQ2Uy0xMjQuNiw5NTAuOCwxODAuNiw0NTMuNWMzMDUuMi00OTcuMyw2MTAuMy00OTcuMyw5MTUuNSwwWiIvPgogICAgICAgIDxwYXRoIGNsYXNzPSJjbHMtMSIgZD0iTTExNDcuNiw0NTMuNWMyMDguOCwzNjEuNywxMDQuNCw1NDIuNS0zMTMuMiw1NDIuNXMtNTIyLTE4MC44LTMxMy4yLTU0Mi41YzIwOC44LTM2MS43LDQxNy42LTM2MS43LDYyNi41LDBaIi8+CiAgICAgICAgPHBhdGggY2xhc3M9ImNscy0yIiBkPSJNNjg0LDcyMS4yYzEwMC4yLDE3My42LDUwLjEsMjYwLjQtMTUwLjMsMjYwLjRzLTI1MC42LTg2LjgtMTUwLjMtMjYwLjRjMTAwLjItMTczLjYsMjAwLjUtMTczLjYsMzAwLjcsMFoiLz4KICAgICAgICA8cGF0aCBkPSJNODcxLjksNjEyLjdjMjUuMSw0My40LDEyLjUsNjUuMS0zNy42LDY1LjFzLTYyLjYtMjEuNy0zNy42LTY1LjFjMjUuMS00My40LDUwLjEtNDMuNCw3NS4yLDBaIi8+CiAgICAgIDwvZz4KICAgIDwvZz4KICA8L2c+Cjwvc3ZnPg==
  11. // ==/UserScript==
  12.  
  13. (function () {
  14. 'use strict';
  15.  
  16. let inLanguage;
  17. let debouncedAutoHeight;
  18. const $ = (selector) => document.querySelectorAll(selector);
  19. const $$ = (selector) => document.querySelector(selector);
  20. const tarAutoHeight = `prompt-input`;
  21. const tarAutoScrollHeight = `lorebook-data-input textarea, #charDesc`;
  22. const textReplaceSelector = `#chatMessages b:not([data-text-replaced]), #chatMessages p:not([data-text-replaced])`;
  23. const cURL = window.location.href;
  24. const muyiStyles = 'https://labs.muyi.tw/caveduck_modifier/style2.css?v=11312091930';
  25. const fontStyles = `
  26. user-input-form div[ng-repeat] textarea,
  27. #chatMessages b,
  28. #chatMessages p,
  29. form[ng-if~="!!chat.editMode"] textarea {
  30. font: normal clamp(16px, .95vw, 32px) / 1.75em var(--m_ff1);
  31. }
  32. #chatMessages b {
  33. font-family: var(--m_ff2);
  34. font-weight: 400;
  35. }
  36. form[ng-if~="!!chat.editMode"] textarea {
  37. font-size: var(--m_font-size);
  38. }
  39. user-input-form div[ng-repeat] textarea {
  40. font-size: var(--m_font-size);
  41. }
  42. `;
  43. const charMap = {
  44. '\\.{2,}': '⋯⋯',
  45. '⋯': '⋯⋯',
  46. '⋯{3,}': '⋯⋯',
  47. '!': '!',
  48. '\\?': '?',
  49. '~': '~',
  50. ';': ';',
  51. ':': ':',
  52. ',': ',',
  53. '\\.': '。',
  54. '\\(': '(',
  55. '\\)': ')'
  56. };
  57. const locale = {
  58. 'zh-hant': {
  59. cb_fontOverride: ['覆蓋字型', '作用頁:Talk<br>用慕儀喜歡的自訂字型取代預設字型。'],
  60. cb_shortButtons: ['快捷按鈕', '作用頁:Talk<br>將「我的資訊」與「使用者筆記」按鈕移到右側。'],
  61. cb_replaceText: ['取代符號', '作用頁:Talk<br>Claude 3 Haiku會使用錯誤的中文標點符號,這個功能可以修正它。'],
  62. cb_deskFix: ['桌面顯示修正', '作用頁:Talk<br>修正高解析度下的顯示體驗,讓對話畫面佔用全版,且圖片顯示區域更大。'],
  63. cb_mdFix: ['行動顯示修正', '作用頁:Talk<br>修正行動裝置的顯示問題。'],
  64. cb_hideLLM: ['隱藏低效LLM', '作用頁:Talk<br>隱藏表現與成本不合比例的LLM,避免誤選取。'],
  65. cb_autoHeight: ['編輯框自動高度', '作用頁:Edit Character、Lorebook、Custom prompt<br>每個項目使用卷軸十分愚蠢,勾選此項可以將其設為自動高度。'],
  66. toggleButton: '慕儀\n神器',
  67. reloadButton: '套用並重載',
  68. },
  69. 'en': {
  70. cb_fontOverride: ['Override Font', 'Active on: Talk<br>Replace default font with MuYi\'s preferred custom font.'],
  71. cb_shortButtons: ['Shortcut buttons', 'Active on: Talk<br>Move the "My Information" and "User Notes" buttons to the right side.'],
  72. cb_replaceText: ['Replace Symbols', 'Active on: Talk<br>Claude 3 Haiku uses incorrect Chinese punctuation. This feature fixes it.'],
  73. cb_deskFix: ['Desktop Display Fix', 'Active on: Talk<br>Fix display experience on high resolution, making the chat screen occupy the full screen and enlarging the image display area.'],
  74. cb_mdFix: ['Mobile Display Fix', 'Active on: Talk<br>Fix the display issues of mobile devices.'],
  75. cb_hideLLM: ['Hide unimportant LLMs', 'Active on: Talk<br>Hide LLMs whose performance does not correlate with their costs to avoid misselection.'],
  76. cb_autoHeight: ['Auto Height for Edit Box', 'Active on: Edit Character、Lorebook、Custom prompt<br>Using scrollbars for each item is stupid. Enable this to auto-height.'],
  77. toggleButton: 'MuYi\'s\nToolbox',
  78. reloadButton: 'Apply and reload',
  79. },
  80. };
  81.  
  82. const settings = Object.keys(locale['en'])
  83. .filter(key => key.startsWith('cb_'))
  84. .map(localeName => ({
  85. localeName: localeName,
  86. key: `sw_${localeName.slice(3)}`
  87. }));
  88.  
  89. const switches = {};
  90. settings.forEach(setting => {
  91. switches[setting.key] = JSON.parse(localStorage.getItem(`enable${setting.key.slice(3)}`) || 'false');
  92. });
  93.  
  94. const domElements = {
  95. o_editMyInfoButton: 'button[ng-click="onEditMyInfoButtonClicked()"]',
  96. o_editUserNoteButton: 'button[ng-click="onEditUserNoteButtonClicked()"]',
  97. o_optionButton: '#optionButton',
  98. o_editButton: '#editButton',
  99. o_imgButton: '.hidden[ng-show~="backgroundImage"]'
  100. };
  101.  
  102. const [
  103. o_editMyInfoButton,
  104. o_editUserNoteButton,
  105. o_optionButton,
  106. o_editButton,
  107. o_imgButton
  108. ] = Object.values(domElements).map(selector => $$(selector));
  109.  
  110. // 添加自訂樣式
  111. function addCustomStyles() {
  112. GM_addStyle(fontStyles);
  113. console.log("Custom styles added.");
  114. }
  115.  
  116. // 自動調整高度的核心函式
  117. function autoHeight(el) {
  118. el.style.height = 'auto';
  119. el.style.overflow = 'auto';
  120. }
  121.  
  122. function autoScrollHeight(el) {
  123. autoHeight(el);
  124. el.style.height = `${el.scrollHeight}px`;
  125. }
  126.  
  127. // 初始化符合條件的元素
  128. function initializeAutoHeight() {
  129. if (!debouncedAutoHeight) {
  130. debouncedAutoHeight = debounce(() => {
  131. $(tarAutoHeight).forEach(autoHeight);
  132. $(tarAutoScrollHeight).forEach(autoScrollHeight);
  133. }, 666, 3);
  134. debouncedAutoHeight();
  135. window.addEventListener('keydown', debouncedAutoHeight);
  136. window.addEventListener('click', debouncedAutoHeight);
  137. }
  138. }
  139.  
  140.  
  141. // 替換指定選擇符的內容
  142. function replaceTextContent() {
  143. const processedAttribute = "data-text-replaced"; // 標記屬性名稱
  144. const el = $(`${textReplaceSelector}:not([${processedAttribute}])`);
  145. el.forEach((el) => {
  146. let originalText = el.textContent;
  147. for (const [pattern, replacement] of Object.entries(charMap)) {
  148. originalText = originalText.replace(new RegExp(pattern, 'g'), replacement);
  149. }
  150. el.textContent = originalText;
  151. el.setAttribute(processedAttribute, ""); // 添加標記屬性
  152. });
  153. }
  154.  
  155. // 延遲觸發的去抖函式
  156. function debounce(func, delay, repeat) {
  157. let timer = null;
  158. let count = 1;
  159. return () => {
  160. func();
  161. if (timer) clearInterval(timer);
  162. timer = setInterval(() => {
  163. func();
  164. count += 1;
  165. if (count >= repeat) {
  166. clearInterval(timer);
  167. }
  168. }, delay);
  169. };
  170. }
  171.  
  172. // 啟動 MutationObserver
  173. function initializeObserver() {
  174. const observer = new MutationObserver(() => {
  175. mainAction();
  176. });
  177. observer.observe(document.body, { childList: true, subtree: true });
  178. console.log("MutationObserver initialized.");
  179. }
  180.  
  181. // 檢查 inLanguage 並啟動必要功能
  182. function checkInLanguage() {
  183. const script = $$('script[type="application/ld+json"]');
  184. if (script) {
  185. try {
  186. const jsonData = JSON.parse(script.textContent);
  187. inLanguage = jsonData[0]?.inLanguage || '';
  188. } catch (error) {
  189. console.error("Failed to parse JSON:", error);
  190. }
  191. }
  192. }
  193.  
  194. function createSettingsUI() {
  195. const lang = ['zh-hant', 'zh-hans'].includes(inLanguage) ? 'zh-hant' : 'en';
  196. const texts = locale[lang];
  197.  
  198. // 創建核取方塊
  199. const createCheckbox = (setting) => {
  200. const container = document.createElement('div');
  201. const checkbox = document.createElement('input');
  202. const label = document.createElement('label');
  203. const desc = document.createElement('div');
  204. desc.className = 'desc';
  205.  
  206. checkbox.type = 'checkbox';
  207. const storageKey = `enable${setting.key.slice(3)}`;
  208. checkbox.id = storageKey;
  209.  
  210. const isChecked = JSON.parse(localStorage.getItem(storageKey) || 'false');
  211. checkbox.checked = isChecked;
  212. label.setAttribute('for', storageKey);
  213. label.textContent = texts[setting.localeName][0];
  214. desc.innerHTML = texts[setting.localeName][1];
  215. label.appendChild(desc);
  216. checkbox.addEventListener('change', () => {
  217. localStorage.setItem(storageKey, checkbox.checked);
  218. });
  219. container.appendChild(checkbox);
  220. container.appendChild(label);
  221. return container;
  222. };
  223.  
  224. // 創建按鈕和設定視窗
  225. const mt = document.createElement('div');
  226. mt.id = 'mt';
  227.  
  228. const toggleButton = document.createElement('button');
  229. toggleButton.className = 'button--red mt_toggleButton';
  230. toggleButton.textContent = texts.toggleButton;
  231. if (lang === 'zh-hant') toggleButton.style.fontSize = '.8rem';
  232.  
  233. const settingsPanel = document.createElement('div');
  234. settingsPanel.className = 'mt_fixed mt_settingsPanel';
  235. settingsPanel.style.display = 'none';
  236.  
  237. // 添加核取方塊
  238. settings.forEach((setting) => {
  239. settingsPanel.appendChild(createCheckbox(setting));
  240. });
  241.  
  242. // 重整按鈕
  243. const reloadButton = document.createElement('button');
  244. reloadButton.textContent = texts.reloadButton;
  245. reloadButton.className = 'button--red';
  246. reloadButton.addEventListener('click', () => location.reload());
  247. settingsPanel.appendChild(reloadButton);
  248.  
  249. // 切換視窗顯示
  250. toggleButton.addEventListener('click', () => {
  251. settingsPanel.style.display = settingsPanel.style.display === 'none' ? 'block' : 'none';
  252. });
  253.  
  254. // 添加到頁面
  255. document.body.appendChild(mt);
  256. mt.appendChild(toggleButton);
  257. document.body.appendChild(settingsPanel);
  258.  
  259. // 快捷按鈕
  260. if (switches.sw_shortButtons && mURL('*/talk/*')) {
  261. ['👤', '📝'].forEach((text, index) => {
  262. const button = document.createElement('button');
  263. button.textContent = text;
  264. button.addEventListener('click', () => {
  265. o_optionButton.click();
  266. o_editButton.click();
  267. (index === 0 ? o_editMyInfoButton : o_editUserNoteButton).click();
  268. });
  269. mt.appendChild(button);
  270. });
  271. }
  272. }
  273.  
  274. function checkSettings() {
  275. checkInLanguage();
  276. settings.forEach(setting => {
  277. switches[setting.switchVar] = JSON.parse(localStorage.getItem(setting.storageKey) || 'false');
  278. });
  279.  
  280. if (switches.sw_fontOverride) addCustomStyles();
  281. mainAction();
  282. }
  283.  
  284. function mURL(pattern) {
  285. const patternParts = pattern.split('*');
  286. let lastIndex = 0;
  287. for (let part of patternParts) {
  288. if (part === "") continue;
  289. const index = cURL.indexOf(part, lastIndex);
  290. if (index === -1) return false;
  291. lastIndex = index + part.length;
  292. }
  293. return true;
  294. }
  295.  
  296. function setStylesheet() {
  297. const link = document.createElement("link");
  298. link.rel = 'stylesheet';
  299. link.href = muyiStyles;
  300. document.head.appendChild(link);
  301. }
  302.  
  303. function mainAction() {
  304. if (switches.sw_autoHeight && (mURL('*/created-characters/*') || mURL('*/prompt-build-script/*') || mURL('*/lorebook-editor/*'))) initializeAutoHeight();
  305. if (['zh-hant', 'zh-hans', 'ja', 'ko'].includes(inLanguage) && (switches.sw_replaceText)) replaceTextContent();
  306. if (mURL('*/public')) {
  307. if (switches.sw_mdFix) {
  308. $$('section.flex-col.py-60 > h3.text-2xl').classList.remove('px-16');
  309. }
  310. }
  311. if (mURL('*/talk/*')) {
  312. if (switches.sw_mdFix) o_imgButton.classList.add('mt_fix');
  313. if (switches.sw_deskFix) {
  314. $('.container, .items-center.text-lg.relative, div.flex.overflow-hidden.flex-grow>div.flex[class*="md:w-[40%]"], div.flex.overflow-hidden.flex-grow>div.flex[class*="md:w-[60%]"]').forEach(el => {
  315. el.classList.add('mt_fix');
  316. });
  317. }
  318. if (switches.sw_hideLLM) {
  319. $(`
  320. input#gpt-4-turbo, label[for="gpt-4-turbo"],
  321. input#claude-v2, label[for="claude-v2"],
  322. input#claude-v3-opus, label[for="claude-v3-opus"],
  323. input#claude-v3-sonnet, label[for="claude-v3-sonnet"],
  324. input[id="claude-v3.5-sonnet"], label[for="claude-v3.5-sonnet"],
  325. input#gpt-4-turbo, label[for="gpt-4-turbo"],
  326. input#gpt-4-turbo, label[for="gpt-4-turbo"]
  327. `).forEach(el => {
  328. el.style.display = 'none';
  329. });
  330. }
  331. }
  332. }
  333.  
  334. window.addEventListener('load', () => {
  335. setStylesheet();
  336. checkSettings();
  337. createSettingsUI();
  338. setTimeout(initializeObserver, 100);
  339. });
  340. })();