Jump to content

User:Kxx/fix images.js

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Kxx (talk | contribs) at 08:29, 25 May 2024. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

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 width = img.width();
            let height = img.height();
            let div = $('<div>');
            div.attr('class', img.attr('class'));
            div.css({
                display: 'inline-block',
                overflow: 'clip',
                verticalAlign: img.css('vertical-align')
            });
            div.width(width).height(height);
            let obj = $('<object type="image/svg+xml">').appendTo(div);
            let scaleX = width / parseFloat(img.attr('data-file-width'));
            let scaleY = height / parseFloat(img.attr('data-file-height'));
            obj.attr('data', matches.slice(1, 5).join('')).css({
                transformOrigin: 'top left',
                scale: `${scaleX} ${scaleY}`
            });
            img.replaceWith(div);
        } 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');
    });
})();