const SESSION_OBSERVER_KEY = 'enhancedChat_observerArray';
let observerArray = JSON.parse(sessionStorage.getItem(SESSION_OBSERVER_KEY)) || [];
const DEBOUNCE_WAIT = 300;
initializeObservers();
function captureMessages() {
const messageWrap = document.querySelector('.bubble-wrap.svelte-1e1jlin');
if (!messageWrap) {
console.error("Message wrap not found.");
return;
}
const messages = Array.from(messageWrap.querySelectorAll('.message-row')).map(div => ({
htmlContent: div.outerHTML,
type: div.classList.contains('user-row') ? 'user' : 'bot'
}));
mergeNewMessagesIntoObserverArray(messages);
storeChatHistory();
}
function mergeNewMessagesIntoObserverArray(newMessages) {
newMessages.forEach(msg => {
if (!observerArray.some(existingMsg => existingMsg.htmlContent === msg.htmlContent)) {
observerArray.push(msg);
}
});
console.log('Observer array updated:', observerArray);
}
function storeChatHistory() {
sessionStorage.setItem(SESSION_OBSERVER_KEY, JSON.stringify(observerArray));
console.clear();
console.log('Stored Observer State:', observerArray);
}
function saveChatHistoryToFile() {
if (typeof JSZip === 'undefined' || observerArray.length === 0) {
console.error('JSZip is not loaded or chat history is empty.');
return;
}
const zip = new JSZip();
zip.file('chat_history.txt', observerArray.map(msg => extractTextFromHTML(msg.htmlContent)).join('\n'));
zip.generateAsync({ type: 'blob' }).then(content => {
const blobURL = URL.createObjectURL(content);
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const a = document.createElement('a');
a.href = blobURL;
a.download = `chat_history_${timestamp}.zip`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
console.log('ZIP file created and downloaded successfully!');
});
}
function copyChatHistoryToClipboard() {
const chatContent = observerArray.map(msg => extractTextFromHTML(msg.htmlContent)).join('\n');
navigator.clipboard.writeText(chatContent).then(() => {
console.log('Observer chat copied to clipboard.');
}).catch(err => {
console.error('Failed to copy chat history:', err);
});
}
function extractTextFromHTML(htmlContent) {
const tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlContent;
return tempDiv.textContent;
}
function copySpecificMessagesToClipboard(type) {
const filteredMessages = observerArray
.filter(msg => msg.type === type)
.map(msg => extractTextFromHTML(msg.htmlContent));
const messageString = filteredMessages.join('\n');
navigator.clipboard.writeText(messageString).then(() => {
console.log(`Copied ${type} messages to clipboard.`);
}).catch(err => {
console.error(`Failed to copy ${type} messages to clipboard:`, err);
});
}
function handleCommand() {
const inputBox = document.querySelector('textarea[data-testid="textbox"]');
if (inputBox) {
const command = inputBox.value.trim().toLowerCase();
switch (command) {
case 'sve':
saveChatHistoryToFile();
break;
case 'svr':
copyChatHistoryToClipboard();
break;
case 'svu':
copySpecificMessagesToClipboard('user');
break;
case 'svb':
copySpecificMessagesToClipboard('bot');
break;
default:
console.log("Unknown command.");
break;
}
inputBox.value = ''; // Clear input box after handling command
}
}
function initializeObservers() {
const messageWrap = document.querySelector('.bubble-wrap.svelte-1e1jlin');
if (messageWrap) {
const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
if (mutation.type === "childList") {
captureMessagesDebounced();
}
});
});
observer.observe(messageWrap, { childList: true, subtree: true });
const inputBox = document.querySelector('textarea[data-testid="textbox"]');
if (inputBox) {
inputBox.addEventListener('input', handleCommand);
}
} else {
console.error("Message wrap not found, retrying...");
setTimeout(initializeObservers, 1000);
}
}
const captureMessagesDebounced = debounce(captureMessages, DEBOUNCE_WAIT);
function debounce(func, wait) {
let timeout;
return function (...args) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), wait);
};
}
})();
need to enwire console into handlablaments and remove from handlablaments these manual commands through original chat input.
need independent console to not activate if focused inside original input, only outside with "`" key.
To integrate the custom overlay console into the EnhancedChatment script and remove the manual commands from the original chat input, you need to make adjustments in several areas. Here is how you can do it:
Remove Command Handling from the Original Chat Input:
You'll want to eliminate any event listeners or command processing tied to the original textarea input in EnhancedChatment.
Integrate the Custom Console Overlay:
Use the overlay console defined in OverlayConsole for entering and processing commands.
Modify Command Handling in EnhancedChatment:
Direct the commands entered in the console overlay to interact with EnhancedChatment's functionalities.
Here's a revised version of the script integrating these changes:
The overlay console now directly manages command inputs and is the sole point for executing commands related to chat capture and management.
All command handling logic (previously tied to the chat input) is now encapsulated within the handleCommand function triggered by the custom console overlay.
Added checks to ensure the console overlays open only outside the original chat input when the backtick key is pressed.
This code snippet should integrate the console's command handling into the enhanced observer system and make the experience cleaner and more intuitive.