c.ai X Character Creation Helper

Gives visual feedback for the definition

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

  1. // ==UserScript==
  2. // @name c.ai X Character Creation Helper
  3. // @namespace c.ai X Character Creation Helper
  4. // @version 1.4
  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. initialElementIds.forEach(selector => {
  40. checkElementPresence(selector, (element) => {
  41. console.log(`Content of ${selector}:`, element.textContent);
  42. });
  43. });
  44.  
  45. // Selector for the definition
  46. const definitionSelector = '.transition > div:nth-child(1) > div:nth-child(1) > div:nth-child(1)';
  47. checkElementPresence(definitionSelector, (element) => {
  48. const textarea = element.querySelector('textarea');
  49. if (textarea && !document.querySelector('.custom-definition-panel')) {
  50. updatePanel(textarea); // Initial panel setup
  51.  
  52. // Observer to detect changes in the textarea content
  53. const observer = new MutationObserver(() => {
  54. updatePanel(textarea);
  55. });
  56.  
  57. observer.observe(textarea, {attributes: true, childList: true, subtree: true, characterData: true});
  58. }
  59. });
  60. }
  61.  
  62. // Function to update or create the DefinitionFeedbackPanel based on textarea content
  63. function updatePanel(textarea) {
  64. let DefinitionFeedbackPanel = document.querySelector('.custom-definition-panel');
  65. if (!DefinitionFeedbackPanel) {
  66. DefinitionFeedbackPanel = document.createElement('div');
  67. DefinitionFeedbackPanel.classList.add('custom-definition-panel');
  68. textarea.parentNode.insertBefore(DefinitionFeedbackPanel, textarea);
  69. }
  70. DefinitionFeedbackPanel.innerHTML = ''; // Clear existing content
  71. DefinitionFeedbackPanel.style.border = '0px solid #ccc';
  72. DefinitionFeedbackPanel.style.padding = '10px';
  73. DefinitionFeedbackPanel.style.marginBottom = '10px';
  74.  
  75. const cleanedContent = textarea.value.trim();
  76. console.log(`Content of Definition:`, cleanedContent);
  77. const textLines = cleanedContent.split('\n');
  78. let lastColor = '#222326';
  79. let isDialogueContinuation = false; // Track if the current line continues a dialogue
  80. let prevColor = null; // Track the previous line's color for detecting color changes
  81.  
  82.  
  83. // Determine line color based on content and dialogue continuation logic
  84. let consecutiveCharCount = 0;
  85. let lastCharColor = '';
  86. let lastNamedCharacterColor = '';
  87. //let isDialogueContinuation = false;
  88.  
  89. function determineLineColor(line, prevLine) {
  90. const dialogueStarterRegex = /^\{\{(?:char|user|random_user_[^\}]*)\}\}:|^[\S]+:/;
  91.  
  92. const isDialogueStarter = dialogueStarterRegex.test(line);
  93. const continuesDialogue = prevLine && prevLine.trim().endsWith(':') && (line.startsWith(' ') || !dialogueStarterRegex.test(line));
  94.  
  95. if (isDialogueStarter) {
  96. isDialogueContinuation = true;
  97. if (line.startsWith('{{char}}:')) {
  98. consecutiveCharCount++;
  99. lastColor = consecutiveCharCount % 2 === 0 ? '#26272B' : '#292A2E';
  100. lastCharColor = lastColor;
  101. } else if (line.match(/^(?!{{(?:char|user)}})[\S]+:/)) {
  102. lastNamedCharacterColor = lastNamedCharacterColor === '#474747' ? '#4C4C4D' : '#474747';
  103. lastColor = lastNamedCharacterColor;
  104. }
  105. else if (line.match(/^\{\{random_user_[^\}]*\}\}:|^\{\{random_user_\}\}:|^{{random_user_}}/)) {
  106. lastNamedCharacterColor = lastNamedCharacterColor === '#474747' ? '#4C4C4D' : '#474747';
  107. lastColor = lastNamedCharacterColor;
  108. } else {
  109. consecutiveCharCount = 0;
  110. lastColor = line.startsWith('{{user}}:') ? '#37362F' : '#3B3A32';
  111. }
  112. } else if (line.startsWith('END_OF_DIALOG')) {
  113. isDialogueContinuation = false;
  114. lastColor = 'rgba(65, 65, 66, 0)';
  115. } else if (isDialogueContinuation && continuesDialogue) {
  116. // Do nothing, continuation of dialogue
  117. } else if (isDialogueContinuation && !isDialogueStarter) {
  118. // Do nothing, continuation of dialogue
  119. } else {
  120. isDialogueContinuation = false;
  121. lastColor = 'rgba(65, 65, 66, 0)';
  122. }
  123. return lastColor;
  124. }
  125.  
  126. // Function to remove dialogue starters from the start of a line
  127. let trimmedParts = []; // Array to store trimmed parts
  128. let consecutiveLines = []; // Array to store consecutive lines with the same color
  129. //let prevColor = null;
  130.  
  131. function trimDialogueStarters(line) {
  132. const dialogueStarterRegex = /^(\{\{char\}\}:|\{\{user\}\}:|\{\{random_user_[^\}]*\}\}:|[A-Za-z\S]+:)\s*/;
  133.  
  134.  
  135. const trimmed = line.match(dialogueStarterRegex);
  136. if (trimmed) {
  137. trimmedParts.push(trimmed[0]); // Store the trimmed part
  138. }
  139. return line.replace(dialogueStarterRegex, '');
  140. }
  141.  
  142. function groupConsecutiveLines(color, lineDiv) {
  143. // Check if there are consecutive lines with the same color
  144. if (consecutiveLines.length > 0 && consecutiveLines[0].color === color) {
  145. consecutiveLines.push({ color, lineDiv });
  146. } else {
  147. // If not, append the previous group of consecutive lines and start a new group
  148. appendConsecutiveLines();
  149. consecutiveLines.push({ color, lineDiv });
  150. }
  151. }
  152.  
  153. function appendConsecutiveLines() {
  154. if (consecutiveLines.length > 0) {
  155. const groupDiv = document.createElement('div');
  156. const color = consecutiveLines[0].color;
  157.  
  158. // Create a container div that could potentially use flexbox
  159. const containerDiv = document.createElement('div');
  160. containerDiv.style.width = '100%';
  161.  
  162. groupDiv.style.backgroundColor = color;
  163. groupDiv.style.padding = '12px';
  164. groupDiv.style.borderRadius = '16px';
  165. groupDiv.style.display = 'inline-block';
  166. groupDiv.style.maxWidth = '90%'; // You might adjust this as needed
  167.  
  168. // Only apply flexbox styling if the color condition is met
  169. if (color === '#37362F' || color === '#3B3A32') {
  170. containerDiv.style.display = 'flex';
  171. containerDiv.style.justifyContent = 'flex-end'; // Aligns the child div to the right
  172. }
  173.  
  174. consecutiveLines.forEach(({ lineDiv }) => {
  175. groupDiv.appendChild(lineDiv);
  176. });
  177.  
  178. // Add the groupDiv to the containerDiv (flex or not based on color)
  179. containerDiv.appendChild(groupDiv);
  180.  
  181. // Append the containerDiv to the DefinitionFeedbackPanel
  182. DefinitionFeedbackPanel.appendChild(containerDiv);
  183. consecutiveLines = []; // Clear the array
  184. }
  185. }
  186.  
  187.  
  188.  
  189. function formatText(text) {
  190. // Handle headers; replace Markdown headers (# Header) with <h1>, <h2>, etc.
  191. text = text.replace(/^(######\s)(.*)$/gm, '<h6>$2</h6>'); // For h6
  192. text = text.replace(/^(#####\s)(.*)$/gm, '<h5>$2</h5>'); // For h5
  193. text = text.replace(/^(####\s)(.*)$/gm, '<h4>$2</h4>'); // For h4
  194. text = text.replace(/^(###\s)(.*)$/gm, '<h3>$2</h3>'); // For h3
  195. text = text.replace(/^(##\s)(.*)$/gm, '<h2>$2</h2>'); // For h2
  196. text = text.replace(/^(#\s)(.*)$/gm, '<h1>$2</h1>'); // For h1
  197.  
  198. // Process bold italic before bold or italic to avoid nesting conflicts
  199. text = text.replace(/\*\*\*([^*]+)\*\*\*/g, '<em><strong>$1</strong></em>');
  200. // Replace text wrapped in double asterisks with <strong> tags for bold
  201. text = text.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
  202. // Finally, replace text wrapped in single asterisks with <em> tags for italics
  203. text = text.replace(/\*([^*]+)\*/g, '<em>$1</em>');
  204.  
  205. return text;
  206. }
  207.  
  208.  
  209.  
  210. textLines.forEach((line, index) => {
  211. const prevLine = index > 0 ? textLines[index - 1] : null;
  212. const currentColor = determineLineColor(line, prevLine);
  213. const trimmedLine = trimDialogueStarters(line);
  214.  
  215. if (prevColor && currentColor !== prevColor) {
  216. appendConsecutiveLines(); // Append previous group of consecutive lines
  217.  
  218. const spacingDiv = document.createElement('div');
  219. spacingDiv.style.marginBottom = '20px';
  220. DefinitionFeedbackPanel.appendChild(spacingDiv);
  221. }
  222.  
  223. const lineDiv = document.createElement('div');
  224. lineDiv.style.wordWrap = 'break-word'; // Allow text wrapping
  225.  
  226. if (trimmedLine.startsWith("END_OF_DIALOG")) {
  227. appendConsecutiveLines(); // Make sure to append any pending groups before adding the divider
  228. const separatorLine = document.createElement('hr');
  229. DefinitionFeedbackPanel.appendChild(separatorLine); // This ensures the divider is on a new line
  230. } else {
  231. if (trimmedParts.length > 0) {
  232. const headerDiv = document.createElement('div');
  233. const headerText = trimmedParts.shift();
  234. const formattedHeaderText = headerText.replace(/:/g, '');
  235. headerDiv.textContent = formattedHeaderText;
  236. if (formattedHeaderText.includes('{{user}}')) {
  237. headerDiv.style.textAlign = 'right';
  238. }
  239. DefinitionFeedbackPanel.appendChild(headerDiv);
  240. }
  241.  
  242. if (trimmedLine.trim() === '') {
  243. lineDiv.appendChild(document.createElement('br'));
  244. } else {
  245. const paragraph = document.createElement('p');
  246. // Call formatTextForItalics to wrap text in asterisks with <em> tags
  247. paragraph.innerHTML = formatText(trimmedLine);
  248. lineDiv.appendChild(paragraph);
  249. }
  250.  
  251. groupConsecutiveLines(currentColor, lineDiv);
  252. }
  253.  
  254. prevColor = currentColor;
  255. });
  256.  
  257. appendConsecutiveLines();
  258.  
  259.  
  260.  
  261.  
  262. }
  263.  
  264.  
  265.  
  266. // Monitor for URL changes to re-initialize element monitoring
  267. let currentUrl = window.location.href;
  268. setInterval(() => {
  269. if (window.location.href !== currentUrl) {
  270. console.log("URL changed. Re-initializing element monitoring.");
  271. currentUrl = window.location.href;
  272. monitorElements();
  273. }
  274. }, 1000);
  275.  
  276. monitorElements();
  277. })();