Cologler
6/27/2018 - 12:31 AM

gist: Raw (Newest) button

add 'Raw (Newest)' button to gist.

// ==UserScript==
// @name               gist: Raw (Newest) button
// @namespace          https://github.com/cologler/
// @version            0.2.0
// @description        add 'Raw (Newest)' button to gist.
// @author             Cologler
// @match              https://gist.github.com/*/*
// @connect            gist.githubusercontent.com
// @noframes
// @license            MIT
// @require            https://cdn.jsdelivr.net/gh/Cologler/monkey-in-zoo-javascript@0.2.1/dist/dom.js
// ==/UserScript==

(function() {
    'use strict';

    function getRawNewestUrl(url) {
        let m = url.match(/\/raw\/[0-9a-f]{40}\//);
        return url.replace(m[0], '/raw/');
    }

    function addNewestRawButton(cloneSrc, url) {
        const newBtn = cloneSrc.cloneNode(true);
        newBtn.style.marginRight = '6px';
        const a = newBtn.querySelector('a');
        a.textContent = 'Raw (Newest)';
        a.href = getRawNewestUrl(url);

        cloneSrc.parentElement.insertBefore(newBtn, cloneSrc.nextSibling);
    }

    function main() {
        if (location.hostname === 'gist.github.com') {
            Dom.on('div.file-actions', z => {
                for (const link of z.querySelectorAll('a')) {
                    if (link && link.textContent?.trim() === 'Raw') {
                        const url = link.href;
                        addNewestRawButton(z, url);
                        break;
                    }
                }
            });
        }
    }

    main();
})();