// ==UserScript==
// @name         Django Docs Pre Copy Button
// @namespace    http://tampermonkey.net/
// @version      1.5
// @description  Add a copy button to pre tags on Django docs pages, excluding the $ symbol, with the button on the left side, rounded corners, and not blocking the code
// @author       YourName
// @match        https://docs.djangoproject.com/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    function addCopyButtons() {
        const preTags = document.querySelectorAll('pre');

        preTags.forEach((preTag) => {
            // Create a container for pre and button
            const container = document.createElement('div');
            container.style.position = 'relative';
            container.style.display = 'flex';
            container.style.alignItems = 'center';

            // Create a button element
            const button = document.createElement('button');
            button.innerText = '复制';
            button.style.backgroundColor = 'gray';
            button.style.color = 'white';
            button.style.border = 'none';
            button.style.padding = '5px 10px';
            button.style.marginRight = '-10px';
			button.style.marginLeft = '10px';
            button.style.cursor = 'pointer';
            button.style.zIndex = '10'; // Ensure button is above the pre tag
            button.style.borderRadius = '5px'; // Add rounded corners

            // Add click event to copy text
            button.addEventListener('click', function() {
                let code = preTag.innerText;

                // Remove the leading $ if present
                code = code.split('\n').map(line => {
                    return line.startsWith('$') ? line.substring(2) : line;
                }).join('\n');

                const textarea = document.createElement('textarea');
                textarea.style.position = 'fixed';
                textarea.style.opacity = '0';
                textarea.value = code;
                document.body.appendChild(textarea);
                textarea.select();
                try {
                    document.execCommand('copy');
                    button.innerText = '已复制';
                    setTimeout(() => {
                        button.innerText = '复制';
                    }, 2000);
                } catch (err) {
                    console.error('Failed to copy text: ', err);
                }
                document.body.removeChild(textarea);
            });

            // Wrap preTag in container
            preTag.parentNode.insertBefore(container, preTag);
            container.appendChild(button); // Add button first
            container.appendChild(preTag); // Then add the pre tag
        });
    }

    // Wait for the content to load and then add buttons
    window.addEventListener('load', addCopyButtons);
})();
