SuhEugene / GitHub Blob DMI Images

// ==UserScript==
// @name         GitHub Blob DMI Images
// @namespace    ru.suheugene.github-blob-dmi
// @version      2024-07-11
// @description  Replaces "View raw" links with images for .dmi GitHub blob pages
// @author       SuhEugene
// @match        https://github.com/**
// @icon         https://www.google.com/s2/favicons?sz=64&domain=github.com
// @grant        none
// @license MIT
// @copyright 2024, SuhEugene (https://suheugene.ru)
// ==/UserScript==

const NO_RESIZE = 0;
const MIN_128PX = 1;
const BIG_IMAGES = 2;

const RESIZE_IMAGES = MIN_128PX;

(function() {
    'use strict';
    console.log("[DMI script] Loaded");

    window.addEventListener("load", replaceData);

    console.log("[DMI script] Using interval");
    setInterval(replaceData, 1000);

    function replaceData() {
        const currentPageUrl = window.location.href;
        if (!currentPageUrl.includes("blob") || !currentPageUrl.endsWith(".dmi")) return;

        const links = document.querySelectorAll('a');
        for (const link of links) {
            if (link.innerText !== "View raw" && !link.dataset.dmiscripted) continue;
            if (!link.href) continue;

            if (link.children.length && link.children[0].tagName == "IMG") {
                const img = link.children[0];
                img.src = link.href;
                return;
            }

            const img = document.createElement('img');
            img.src = link.href;

            link.style.display = 'block';
            link.dataset.dmiscripted = true;

            link.innerHTML = '';
            link.appendChild(img);

            if (!RESIZE_IMAGES) return;

            img.style.objectFit = 'contain';
            img.style.imageRendering = 'pixelated';
            img.style.maxHeight = '80vh';

            if (RESIZE_IMAGES === BIG_IMAGES) {
                img.style.width = '100%';
                return;
            }
            if (RESIZE_IMAGES === MIN_128PX) {
                img.style.minWidth = "128px";
                img.style.minHeight = "128px";
            }
        }
    }
})();