c.ai X Character Creation Helper

Gives visual feedback for the definition

目前為 2024-04-03 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name c.ai X Character Creation Helper
  3. // @namespace c.ai X Character Creation Helper
  4. // @version 1.9
  5. // @license MIT
  6. // @description Gives visual feedback for the definition
  7. // @author Vishanka
  8. // @match https://character.ai/*
  9. // @grant none
  10. // ==/UserScript==
  11.  
  12.  
  13. (function() {
  14. 'use strict';
  15.  
  16. // Function to check for element's presence and execute a callback when found
  17. const checkElementPresence = (selector, callback, maxAttempts = 10) => {
  18. let attempts = 0;
  19. const interval = setInterval(() => {
  20. const element = document.querySelector(selector);
  21. if (element) {
  22. clearInterval(interval);
  23. callback(element);
  24. } else if (++attempts >= maxAttempts) {
  25. clearInterval(interval);
  26. console.warn(`Element ${selector} not found after ${maxAttempts} attempts.`);
  27. }
  28. }, 1000);
  29. };
  30.  
  31. // Function to monitor elements on the page
  32. function monitorElements() {
  33. const initialElementIds = [
  34. 'div.flex-auto:nth-child(1) > div:nth-child(2) > div:nth-child(1)',
  35. 'div.relative:nth-child(5) > div:nth-child(1) > div:nth-child(1)', // Greeting
  36. 'div.relative:nth-child(4) > div:nth-child(1) > div:nth-child(1)' // Description
  37. ];
  38.  
  39.  
  40. initialElementIds.forEach(selector => {
  41. checkElementPresence(selector, (element) => {
  42. console.log(`Content of ${selector}:`, element.textContent);
  43. });
  44. });
  45.  
  46. // Selector for the definition
  47. const definitionSelector = '.transition > div:nth-child(1) > div:nth-child(1) > div:nth-child(1)';
  48. checkElementPresence(definitionSelector, (element) => {
  49. const textarea = element.querySelector('textarea');
  50. if (textarea && !document.querySelector('.custom-definition-panel')) {
  51. updatePanel(textarea); // Initial panel setup
  52.  
  53. // Observer to detect changes in the textarea content
  54. const observer = new MutationObserver(() => {
  55. updatePanel(textarea);
  56. });
  57.  
  58. observer.observe(textarea, {attributes: true, childList: true, subtree: true, characterData: true});
  59. }
  60. });
  61. }
  62.  
  63. // Function to update or create the DefinitionFeedbackPanel based on textarea content
  64. function updatePanel(textarea) {
  65. let DefinitionFeedbackPanel = document.querySelector('.custom-definition-panel');
  66. if (!DefinitionFeedbackPanel) {
  67. DefinitionFeedbackPanel = document.createElement('div');
  68. DefinitionFeedbackPanel.classList.add('custom-definition-panel');
  69. textarea.parentNode.insertBefore(DefinitionFeedbackPanel, textarea);
  70. }
  71. DefinitionFeedbackPanel.innerHTML = ''; // Clear existing content
  72. DefinitionFeedbackPanel.style.border = '0px solid #ccc';
  73. DefinitionFeedbackPanel.style.padding = '10px';
  74. DefinitionFeedbackPanel.style.marginBottom = '10px';
  75. var plaintextColor = localStorage.getItem('plaintext_color');
  76. var defaultColor = '#D1D5DB';
  77. var color = plaintextColor || defaultColor;
  78. DefinitionFeedbackPanel.style.color = color;
  79.  
  80. const cleanedContent = textarea.value.trim();
  81. console.log(`Content of Definition:`, cleanedContent);
  82. const textLines = cleanedContent.split('\n');
  83.  
  84. let lastColor = '#222326';
  85. let isDialogueContinuation = false; // Track if the current line continues a dialogue
  86. let prevColor = null; // Track the previous line's color for detecting color changes
  87.  
  88. let consecutiveCharCount = 0;
  89. let consecutiveUserCount = 0; // Track the number of consecutive {{user}} lines
  90. let lastCharColor = '';
  91. let lastNamedCharacterColor = '';
  92.  
  93. function determineLineColor(line, prevLine) {
  94. // Extract the part of the line before the first colon
  95. const indexFirstColon = line.indexOf(':');
  96. const firstPartOfLine = indexFirstColon !== -1 ? line.substring(0, indexFirstColon + 1) : line;
  97. // Define the dialogue starter regex with updated conditions
  98. const dialogueStarterRegex = /^\{\{(?:char|user|random_user_[^\}]*)\}\}:|^{{[\S\s]+}}:|^[^\s:]+:/;
  99. const isDialogueStarter = dialogueStarterRegex.test(firstPartOfLine);
  100. const continuesDialogue = prevLine && prevLine.trim().endsWith(':') && (line.startsWith(' ') || !dialogueStarterRegex.test(firstPartOfLine));
  101.  
  102. const currentTheme = document.documentElement.classList.contains('dark') ? 'dark' : 'light';
  103.  
  104. if (isDialogueStarter) {
  105. isDialogueContinuation = true;
  106. if (line.startsWith('{{char}}:')) {
  107. consecutiveCharCount++;
  108. if (currentTheme === 'dark') {
  109. lastColor = consecutiveCharCount % 2 === 0 ? '#26272B' : '#292A2E';
  110. lastCharColor = lastColor;
  111. } else {
  112. lastColor = consecutiveCharCount % 2 === 0 ? '#E4E4E7' : '#E3E3E6';
  113. lastCharColor = lastColor;
  114. }
  115. } else if (line.startsWith('{{user}}:')) {
  116. consecutiveUserCount++;
  117. if (currentTheme === 'dark') {
  118. lastColor = consecutiveUserCount % 2 === 0 ? '#363630' : '#383832';
  119. } else {
  120. lastColor = consecutiveUserCount % 2 === 0 ? '#D9D9DF' : '#D5D5DB'; // Light theme color
  121. }
  122. consecutiveCharCount = 0; // Reset this if you need to ensure it only affects consecutive {{char}} dialogues
  123.  
  124. } else if (line.match(/^\{\{(?:char|user|random_user_[^\}]*)\}\}:|^{{[\S\s]+}}:|^[\S]+:/)) {
  125. if (currentTheme === 'dark') {
  126. lastNamedCharacterColor = lastNamedCharacterColor === '#474747' ? '#4C4C4D' : '#474747';
  127. } else {
  128. lastNamedCharacterColor = lastNamedCharacterColor === '#CFDCE8' ? '#CCDAE6' : '#CFDCE8';
  129. }
  130. lastColor = lastNamedCharacterColor;
  131. }
  132. else if (line.match(/^\{\{random_user_[^\}]*\}\}:|^\{\{random_user_\}\}:|^{{random_user_}}/)) {
  133. if (currentTheme === 'dark') {
  134. lastNamedCharacterColor = lastNamedCharacterColor === '#474747' ? '#4C4C4D' : '#474747';
  135. } else {
  136. lastNamedCharacterColor = lastNamedCharacterColor === '#CFDCE8' ? '#CCDAE6' : '#CFDCE8';
  137. }
  138. lastColor = lastNamedCharacterColor;
  139. } else {
  140. consecutiveCharCount = 0;
  141. if (currentTheme === 'dark') {
  142. lastColor = '#474747' ? '#4C4C4D' : '#474747'; // Default case for non-{{char}} dialogues; adjust as needed
  143. } else {
  144. lastColor = '#CFDCE8' ? '#CCDAE6' : '#CFDCE8';
  145. }
  146. }
  147. } else if (line.startsWith('END_OF_DIALOG')) {
  148. isDialogueContinuation = false;
  149. lastColor = 'rgba(65, 65, 66, 0)';
  150. } else if (isDialogueContinuation && continuesDialogue) {
  151. // Do nothing, continuation of dialogue
  152. } else if (isDialogueContinuation && !isDialogueStarter) {
  153. // Do nothing, continuation of dialogue
  154. } else {
  155. isDialogueContinuation = false;
  156. lastColor = 'rgba(65, 65, 66, 0)';
  157. }
  158. return lastColor;
  159. }
  160.  
  161.  
  162. // Function to remove dialogue starters from the start of a line
  163. let trimmedParts = []; // Array to store trimmed parts
  164. let consecutiveLines = []; // Array to store consecutive lines with the same color
  165. //let prevColor = null;
  166.  
  167. function trimDialogueStarters(line) {
  168. // Find the index of the first colon
  169. const indexFirstColon = line.indexOf(':');
  170. // If there's no colon, return the line as is
  171. if (indexFirstColon === -1) return line;
  172.  
  173. // Extract the part of the line before the first colon to check against the regex
  174. const firstPartOfLine = line.substring(0, indexFirstColon + 1);
  175.  
  176. // Define the dialogue starter regex
  177. const dialogueStarterRegex = /^(\{\{char\}\}:|\{\{user\}\}:|\{\{random_user_[^\}]*\}\}:|^{{[\S\s]+}}:|^[^\s:]+:)\s*/;
  178.  
  179. // Check if the first part of the line matches the dialogue starter regex
  180. const trimmed = firstPartOfLine.match(dialogueStarterRegex);
  181. if (trimmed) {
  182. // Store the trimmed part
  183. trimmedParts.push(trimmed[0]);
  184. // Return the line without the dialogue starter and any leading whitespace that follows it
  185. return line.substring(indexFirstColon + 1).trim();
  186. }
  187.  
  188. // If the first part doesn't match, return the original line
  189. return line;
  190. }
  191.  
  192. function groupConsecutiveLines(color, lineDiv) {
  193. // Check if there are consecutive lines with the same color
  194. if (consecutiveLines.length > 0 && consecutiveLines[0].color === color) {
  195. consecutiveLines.push({ color, lineDiv });
  196. } else {
  197. // If not, append the previous group of consecutive lines and start a new group
  198. appendConsecutiveLines();
  199. consecutiveLines.push({ color, lineDiv });
  200. }
  201. }
  202.  
  203. function appendConsecutiveLines() {
  204. if (consecutiveLines.length > 0) {
  205. const groupDiv = document.createElement('div');
  206. const color = consecutiveLines[0].color;
  207.  
  208. const containerDiv = document.createElement('div');
  209. containerDiv.style.width = '100%';
  210.  
  211. groupDiv.style.backgroundColor = color;
  212. groupDiv.style.padding = '12px';
  213. groupDiv.style.paddingBottom = '15px'; // Increased bottom padding to provide space
  214. groupDiv.style.borderRadius = '16px';
  215. groupDiv.style.display = 'inline-block';
  216. groupDiv.style.maxWidth = '90%';
  217.  
  218. if (color === '#363630' || color === '#383832' || color === '#D9D9DF' || color === '#D5D5DB') {
  219. containerDiv.style.display = 'flex';
  220. containerDiv.style.justifyContent = 'flex-end';
  221. }
  222.  
  223. consecutiveLines.forEach(({ lineDiv }) => {
  224. const symbolCount = lineDiv.textContent.length;
  225. const lineContainer = document.createElement('div');
  226.  
  227. lineContainer.style.display = 'flex';
  228. lineContainer.style.justifyContent = 'space-between';
  229. lineContainer.style.alignItems = 'flex-end'; // Ensure items align to the bottom
  230. lineContainer.style.width = '100%'; // Ensure container takes full width
  231.  
  232. lineDiv.style.flexGrow = '1'; // Allow lineDiv to grow and fill space
  233.  
  234. const countDiv = document.createElement('div');
  235. countDiv.textContent = `${symbolCount}`;
  236. countDiv.style.alignSelf = 'flex-end'; // Align countDiv to the bottom
  237. countDiv.style.marginLeft = 'auto'; // Push to the right
  238. countDiv.style.marginBottom = '-11px';
  239. countDiv.style.fontSize = '11px';
  240. // darkmode user
  241. if (color === '#363630' || color === '#383832'){
  242. countDiv.style.color = '#5C5C52';
  243. //lightmode user
  244. } else if (color === '#D9D9DF' || color === '#D5D5DB') {
  245. countDiv.style.color = '#B3B3B8';
  246. //darkmode char
  247. } else if (color === '#26272B' || color === '#292A2E') {
  248. countDiv.style.color = '#44464D';
  249. //lightmode char
  250. } else if (color === '#E4E4E7' || color === '#E3E3E6') {
  251. countDiv.style.color = '#C4C4C7';
  252. //darkmode random
  253. } else if (color === '#474747' || color === '#4C4C4D') {
  254. countDiv.style.color = '#6E6E6E';
  255. //lightmode random
  256. } else if (color === '#CFDCE8' || color === '#CCDAE6') {
  257. countDiv.style.color = '#B4BFC9';
  258. } else {
  259. countDiv.style.color = 'rgba(65, 65, 66, 0)';
  260. }
  261. lineContainer.appendChild(lineDiv);
  262. lineContainer.appendChild(countDiv);
  263.  
  264. groupDiv.appendChild(lineContainer);
  265. });
  266.  
  267. containerDiv.appendChild(groupDiv);
  268. DefinitionFeedbackPanel.appendChild(containerDiv);
  269. consecutiveLines = [];
  270. }
  271. }
  272.  
  273.  
  274.  
  275.  
  276. function formatText(text) {
  277. // Handle headers; replace Markdown headers (# Header) with <h1>, <h2>, etc.
  278. text = text.replace(/^(######\s)(.*)$/gm, '<h6>$2</h6>'); // For h6
  279. text = text.replace(/^(#####\s)(.*)$/gm, '<h5>$2</h5>'); // For h5
  280. text = text.replace(/^(####\s)(.*)$/gm, '<h4>$2</h4>'); // For h4
  281. text = text.replace(/^(###\s)(.*)$/gm, '<h3>$2</h3>'); // For h3
  282. text = text.replace(/^(##\s)(.*)$/gm, '<h2>$2</h2>'); // For h2
  283. text = text.replace(/^(#\s)(.*)$/gm, '<h1>$2</h1>'); // For h1
  284.  
  285. // Process bold italic before bold or italic to avoid nesting conflicts
  286. text = text.replace(/\*\*\*([^*]+)\*\*\*/g, '<em><strong>$1</strong></em>');
  287. // Replace text wrapped in double asterisks with <strong> tags for bold
  288. text = text.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
  289. // Finally, replace text wrapped in single asterisks with <em> tags for italics
  290. text = text.replace(/\*([^*]+)\*/g, '<em>$1</em>');
  291.  
  292. return text;
  293. }
  294.  
  295.  
  296.  
  297. textLines.forEach((line, index) => {
  298. const prevLine = index > 0 ? textLines[index - 1] : null;
  299. const currentColor = determineLineColor(line, prevLine);
  300. const trimmedLine = trimDialogueStarters(line);
  301.  
  302. if (prevColor && currentColor !== prevColor) {
  303. appendConsecutiveLines(); // Append previous group of consecutive lines
  304.  
  305. const spacingDiv = document.createElement('div');
  306. spacingDiv.style.marginBottom = '20px';
  307. DefinitionFeedbackPanel.appendChild(spacingDiv);
  308. }
  309.  
  310. const lineDiv = document.createElement('div');
  311. lineDiv.style.wordWrap = 'break-word'; // Allow text wrapping
  312.  
  313. if (trimmedLine.startsWith("END_OF_DIALOG")) {
  314. appendConsecutiveLines(); // Make sure to append any pending groups before adding the divider
  315. const separatorLine = document.createElement('hr');
  316. DefinitionFeedbackPanel.appendChild(separatorLine); // This ensures the divider is on a new line
  317. } else {
  318. if (trimmedParts.length > 0) {
  319. const headerDiv = document.createElement('div');
  320. const headerText = trimmedParts.shift();
  321. const formattedHeaderText = headerText.replace(/:/g, '');
  322. headerDiv.textContent = formattedHeaderText;
  323. const currentTheme = document.documentElement.classList.contains('dark') ? 'dark' : 'light';
  324. if (currentTheme === 'dark') {
  325. headerDiv.style.color = '#A2A2AC'; // Dark mode text color
  326. } else {
  327. headerDiv.style.color = '#26272B';
  328. }
  329. if (formattedHeaderText.includes('{{user}}')) {
  330. headerDiv.style.textAlign = 'right';
  331. }
  332. DefinitionFeedbackPanel.appendChild(headerDiv);
  333. }
  334.  
  335. if (trimmedLine.trim() === '') {
  336. lineDiv.appendChild(document.createElement('br'));
  337. } else {
  338. const paragraph = document.createElement('p');
  339. // Call formatTextForItalics to wrap text in asterisks with <em> tags
  340. paragraph.innerHTML = formatText(trimmedLine);
  341. lineDiv.appendChild(paragraph);
  342. }
  343.  
  344. groupConsecutiveLines(currentColor, lineDiv);
  345. }
  346.  
  347. prevColor = currentColor;
  348. });
  349.  
  350. appendConsecutiveLines();
  351.  
  352.  
  353.  
  354.  
  355. }
  356.  
  357.  
  358.  
  359. // Monitor for URL changes to re-initialize element monitoring
  360. let currentUrl = window.location.href;
  361. setInterval(() => {
  362. if (window.location.href !== currentUrl) {
  363. console.log("URL changed. Re-initializing element monitoring.");
  364. currentUrl = window.location.href;
  365. monitorElements();
  366. }
  367. }, 1000);
  368.  
  369. monitorElements();
  370. })();