GitHub Gist Copier

Add copy button to Gist files for easy code copying.

09.05.2025 itibariyledir. En son verisyonu görün.

Bu betiği kurabilmeniz için Tampermonkey, Greasemonkey ya da Violentmonkey gibi bir kullanıcı betiği eklentisini kurmanız gerekmektedir.

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

Bu betiği kurabilmeniz için Tampermonkey ya da Violentmonkey gibi bir kullanıcı betiği eklentisini kurmanız gerekmektedir.

Bu betiği kurabilmeniz için Tampermonkey ya da Userscripts gibi bir kullanıcı betiği eklentisini kurmanız gerekmektedir.

Bu betiği indirebilmeniz için ayrıca Tampermonkey gibi bir eklenti kurmanız gerekmektedir.

Bu komut dosyasını yüklemek için bir kullanıcı komut dosyası yöneticisi uzantısı yüklemeniz gerekecek.

(Zaten bir kullanıcı komut dosyası yöneticim var, kurmama izin verin!)

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.

(Zateb bir user-style yöneticim var, yükleyeyim!)

// ==UserScript==
// @name         GitHub Gist Copier
// @description  Add copy button to Gist files for easy code copying.
// @icon         https://github.githubassets.com/favicons/favicon-dark.svg
// @version      1.2
// @author       afkarxyz
// @namespace    https://github.com/afkarxyz/userscripts/
// @supportURL   https://github.com/afkarxyz/userscripts/issues
// @license      MIT
// @run-at       document-end
// @match        https://gist.github.com/*
// @grant        GM_xmlhttpRequest
// @grant        GM_setClipboard
// @grant        GM_addStyle
// @connect      api.codetabs.com
// @connect      gist.githubusercontent.com
// ==/UserScript==

(function() {
    'use strict';

    GM_addStyle(`
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .gist-copy-spinner {
            animation: spin 0.75s linear infinite;
            transform-origin: center;
        }
    `);

    function noop() { }

    function debounce(f, delay) {
        let timeoutId = null;
        return function (...args) {
            if (timeoutId) {
                clearTimeout(timeoutId);
            }
            timeoutId = setTimeout(() => {
                f.apply(this, args);
            }, delay);
        };
    }

    function createCopyButton(fileElement) {
        const fileActionElement = fileElement.querySelector('.file-actions');
        if (!fileActionElement) {
            return noop;
        }

        const rawButton = fileActionElement.querySelector('a[href*="/raw/"]');
        if (!rawButton) {
            return noop;
        }
        
        const button = document.createElement('button');
        button.className = 'btn-octicon gist-copy-button';
        button.style.marginRight = '5px';

        button.innerHTML = `
        <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-copy">
            <path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25Z"></path><path d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25Zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Z"></path>
        </svg>

        <svg style="display: none;" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" class="gist-spinner">
            <path fill="currentColor" d="M12,1A11,11,0,1,0,23,12,11,11,0,0,0,12,1Zm0,19a8,8,0,1,1,8-8A8,8,0,0,1,12,20Z" opacity="0.25"/>
            <path fill="currentColor" d="M10.14,1.16a11,11,0,0,0-9,8.92A1.59,1.59,0,0,0,2.46,12,1.52,1.52,0,0,0,4.11,10.7a8,8,0,0,1,6.66-6.61A1.42,1.42,0,0,0,12,2.69h0A1.57,1.57,0,0,0,10.14,1.16Z" class="gist-copy-spinner"/>
        </svg>

        <svg style="display: none;" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check color-fg-success">
            <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path>
        </svg>
        `;

        const copyIcon = button.querySelector('.octicon-copy');
        const spinnerIcon = button.querySelector('.gist-spinner');
        const checkIcon = button.querySelector('.octicon-check');

        let timeoutId = null;
        const copyHandler = (e) => {
            if (timeoutId) {
                return;
            }
            e.preventDefault();

            copyIcon.style.display = 'none';
            spinnerIcon.style.display = 'inline-block';

            const rawUrl = rawButton.href;
            const proxiedUrl = `https://api.codetabs.com/v1/proxy/?quest=${encodeURIComponent(rawUrl)}`;
            
            GM_xmlhttpRequest({
                method: 'GET',
                url: proxiedUrl,
                headers: {
                    "Accept": "text/plain, application/json, */*"
                },
                followRedirect: true,
                onload: function(response) {
                    if (response.status === 200) {
                        if (response.responseText.includes("<a href=") && response.responseText.includes("Moved Permanently")) {
                            console.error("Received redirect instead of content:", response.responseText);
                            const match = response.responseText.match(/href="([^"]+)"/);
                            if (match && match[1]) {
                                const redirectUrl = match[1].startsWith("/") 
                                    ? `https://api.codetabs.com${match[1]}`
                                    : match[1];
                                
                                GM_xmlhttpRequest({
                                    method: 'GET',
                                    url: redirectUrl,
                                    headers: {
                                        "Accept": "text/plain, application/json, */*"
                                    },
                                    onload: function(redirectResponse) {
                                        if (redirectResponse.status === 200) {
                                            GM_setClipboard(redirectResponse.responseText, { type: 'text', mimetype: 'text/plain' });
                                            
                                            spinnerIcon.style.display = 'none';
                                            checkIcon.style.display = 'inline-block';
                                            
                                            timeoutId = setTimeout(() => {
                                                checkIcon.style.display = 'none';
                                                copyIcon.style.display = 'inline-block';
                                                timeoutId = null;
                                            }, 500);
                                        } else {
                                            console.error("Failed to follow redirect:", redirectResponse.status);
                                            
                                            spinnerIcon.style.display = 'none';
                                            copyIcon.style.display = 'inline-block';
                                            timeoutId = null;
                                        }
                                    },
                                    onerror: function(error) {
                                        console.error("Error following redirect:", error);
                                        
                                        spinnerIcon.style.display = 'none';
                                        copyIcon.style.display = 'inline-block';
                                        timeoutId = null;
                                    }
                                });
                            } else {
                                spinnerIcon.style.display = 'none';
                                copyIcon.style.display = 'inline-block';
                                timeoutId = null;
                            }
                        } else {
                            GM_setClipboard(response.responseText, { type: 'text', mimetype: 'text/plain' });
                            
                            spinnerIcon.style.display = 'none';
                            checkIcon.style.display = 'inline-block';
                            
                            timeoutId = setTimeout(() => {
                                checkIcon.style.display = 'none';
                                copyIcon.style.display = 'inline-block';
                                timeoutId = null;
                            }, 500);
                        }
                    } else {
                        console.error("Error response status:", response.status);
                        
                        spinnerIcon.style.display = 'none';
                        copyIcon.style.display = 'inline-block';
                        timeoutId = null;
                    }
                },
                onerror: function(error) {
                    console.error('Error fetching gist content:', error);
                    
                    spinnerIcon.style.display = 'none';
                    copyIcon.style.display = 'inline-block';
                    timeoutId = null;
                }
            });
        };

        button.addEventListener('click', copyHandler);
        fileActionElement.insertBefore(button, fileActionElement.firstChild);

        return () => {
            button.removeEventListener('click', copyHandler);
            if (timeoutId) {
                clearTimeout(timeoutId);
            }
            button.remove();
        };
    }

    function runGistCopy() {
        let removeAllListeners = noop;
        
        function tryCreateCopyButtons() {
            removeAllListeners();
            const fileElements = [...document.querySelectorAll('.file')];
            const removeListeners = fileElements.map(createCopyButton);
            removeAllListeners = () => {
                removeListeners.map((f) => f());
                [...document.querySelectorAll('.gist-copy-button')].forEach((el) => {
                    el.remove();
                });
            };
        }

        setTimeout(tryCreateCopyButtons, 300);

        const observer = new MutationObserver(debounce(() => {
            if (document.querySelectorAll('.file').length > 0 &&
                document.querySelectorAll('.gist-copy-button').length === 0) {
                tryCreateCopyButtons();
            }
        }, 100));

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
        
        if (window.onurlchange === null) {
            window.addEventListener('urlchange', debounce(tryCreateCopyButtons, 16));
        }
    }

    runGistCopy();
})();