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|)(.*)\/(\d+)px-\4(.*)$/;
    $('img').each((index, elem) => {
        let img = $(elem);
        let matches = srcRegex.exec(img.attr('src'));
        if (!matches) {
            return;
        }
        if (/\.svg$/i.test(matches[4]) && matches[6] === '.png') {
            let div = $('<div>').insertAfter(img);
            div.attr('class', img.attr('class'));
            div.css({
                display: 'inline-block',
                overflow: 'clip',
                verticalAlign: img.css('vertical-align')
            });
            div.width(0).height(0);
            let obj = $('<object type="image/svg+xml">').appendTo(div);
            obj.attr('data', matches.slice(1, 5).join(''));
            let img2 = $('<img>').appendTo(div);
            img2.on('load', () => {
                div.width(img.width()).height(img.height());
                let scaleX = img.width() / img2.width();
                let scaleY = img.height() / img2.height();
                obj.css({
                    display: 'block',
                    transformOrigin: 'top left',
                    scale: `${scaleX} ${scaleY}`
                });
                obj.width(img2.width()).height(img2.height());
                img.remove();
                img2.remove();
            });
            img2.attr('src', matches.slice(1, 5).join(''));
        } else if (matches[6] === '' && devicePixelRatio !== 1) {
            let width = Math.round(img.width() * devicePixelRatio);
            img.attr('src', `${matches[1]}/thumb${matches.slice(2, 5).join('')}/${width}px-${matches[4]}`);
            img.on('error', () => {
                img.attr('src', matches.slice(1, 5).join(''));
                img.off('error');
            });
        }
        img.removeAttr('srcset');
    });
})();