Add Copy Button to Chat Messages on Gtihub Copilot web page

Adds a "Copy" button to chat message elements to easily copy their content.

נכון ליום 10-12-2024. ראה הגרסה האחרונה.

You will need to install an extension such as Tampermonkey, Greasemonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Userscripts to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install a user script manager extension to install this script.

(I already have a user script manager, let me install it!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(I already have a user style manager, let me install it!)

// ==UserScript==
// @name         Add Copy Button to Chat Messages on Gtihub Copilot web page
// @namespace    http://tampermonkey.net/
// @version      1.1
// @description  Adds a "Copy" button to chat message elements to easily copy their content.
// @author       aspen138
// @match        *://github.com/copilot/c/*
// @match        *://github.com/copilot/
// @match        *://github.com/copilot/*
// @grant        none
// @run-at       document-end
// @icon         https://github.com/favicons/favicon-copilot.svg
// @license      MIT
// ==/UserScript==

(function() {
    'use strict';

    // Configuration: Update these class names if they change
    const MESSAGE_CONTENT_CLASS = 'UserMessage-module__container--cAvvK';
    const CHAT_MESSAGE_CONTENT_CLASS = 'ChatMessage-module__content--MYneF';

    /**
     * Creates and returns a copy button element.
     * @returns {HTMLButtonElement} The copy button.
     */
    function createCopyButton() {
        const button = document.createElement('button');
        button.innerText = 'Copy';
        button.style.marginLeft = '10px';
        button.style.padding = '5px 10px';
        button.style.cursor = 'pointer';
        button.style.fontSize = '0.9em';
        // Optional: Add more styles to match your site's design
        return button;
    }

    /**
     * Adds a copy button to a chat message element.
     * @param {HTMLElement} messageElement The chat message element.
     */
    function addCopyButton(messageElement) {
        // Prevent adding multiple buttons to the same message
        if (messageElement.querySelector('.copy-button')) {
            return;
        }

        const messageContent = messageElement.querySelector(`.${MESSAGE_CONTENT_CLASS}`);
        if (!messageContent) return;

        const copyButton = createCopyButton();
        copyButton.classList.add('copy-button');

        // Event listener for the copy action
        copyButton.addEventListener('click', () => {
            const textToCopy = messageContent.innerText.trim();
            navigator.clipboard.writeText(textToCopy).then(() => {
                // Optional: Provide feedback to the user
                copyButton.innerText = 'Copied!';
                setTimeout(() => {
                    copyButton.innerText = 'Copy';
                }, 2000);
            }).catch(err => {
                console.error('Failed to copy text: ', err);
            });
        });

        // Append the copy button to the message element
        // Adjust the append location as needed
        messageElement.appendChild(copyButton);
    }

    /**
     * Processes all existing chat message elements on the page.
     */
    function processExistingMessages() {
        const messageElements = document.querySelectorAll(`.${CHAT_MESSAGE_CONTENT_CLASS}`);
        messageElements.forEach(messageElement => {
            addCopyButton(messageElement);
        });
    }

    /**
     * Sets up a MutationObserver to watch for new chat messages being added to the DOM.
     */
    function observeNewMessages() {
        const targetNode = document.body;
        const config = { childList: true, subtree: true };

        const callback = function(mutationsList) {
            for (const mutation of mutationsList) {
                if (mutation.type === 'childList') {
                    mutation.addedNodes.forEach(node => {
                        if (node.nodeType === Node.ELEMENT_NODE) {
                            // Check if the added node is a chat message
                            if (node.classList && node.classList.contains(CHAT_MESSAGE_CONTENT_CLASS)) {
                                addCopyButton(node);
                            }

                            // Also check within the subtree of the added node
                            const nestedMessages = node.querySelectorAll(`.${CHAT_MESSAGE_CONTENT_CLASS}`);
                            nestedMessages.forEach(nestedNode => {
                                addCopyButton(nestedNode);
                            });
                        }
                    });
                }
            }
        };

        const observer = new MutationObserver(callback);
        observer.observe(targetNode, config);
    }

    /**
     * Initializes the script by processing existing messages and setting up observers.
     */
    function init() {
        processExistingMessages();
        observeNewMessages();
    }

    // Wait for the DOM to be fully loaded before initializing
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

})();