User:Kxx/fix images.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
(() => {
    const srcRegex =
        /^((?:https?:)?\/\/upload\.wikimedia\.org\/.*)\/thumb(\/.*\/)(\d{14}%21|)(.*\.[Ss][Vv][Gg])\/\d+px-\4\.png$/;
    let observer = new ResizeObserver((entries) => {
        $(entries).each((index, entry) => {
            let obj = $(entry.target);
            let div = obj.parent();
            let scaleX = div.width() / obj.width();
            let scaleY = div.height() / obj.height();
            obj.css({scale: `${scaleX} ${scaleY}`});
        })
    });
    $('img').each((index, elem) => {
        let img = $(elem);
        let matches = srcRegex.exec(img.attr('src'));
        if (matches) {
            let div = $('<div>');
            div.attr('class', img.attr('class'));
            div.css({
                display: 'inline-block',
                overflow: 'clip',
                verticalAlign: img.css('vertical-align')
            });
            div.width(img.width()).height(img.height());
            let obj = $('<object type="image/svg+xml">').appendTo(div);
            obj.css({
                display: 'block',
                transformOrigin: 'top left'
            })
            observer.observe(obj[0]);
            obj.attr('data', matches.slice(1, 5).join(''));
            img.replaceWith(div);
        }
    });
})();