Add Copy Button to Chat Messages on Gtihub Copilot web page

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

目前為 2024-12-10 提交的版本,檢視 最新版本

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

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

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==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();
    }

})();