Jump to content

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$/;
    $('img').each((index, elem) => {
        let img = $(elem);
        let matches = srcRegex.exec(img.attr('src'));
        if (matches) {
            let src = matches.slice(1, 5).join('');
            $.get(src).done((data) => {
                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);
                let width = parseFloat(img.attr('data-file-width'));
                let height = parseFloat(img.attr('data-file-height'));
                let scaleX = img.width() / width;
                let scaleY = img.height() / height;
                obj.css({
                    display: 'block',
                    transformOrigin: 'top left',
                    scale: `${scaleX} ${scaleY}`
                })
                obj.width(width).height(height);
                obj.attr('src', src);
                if (typeof data !== 'string') {
                    data = new XMLSerializer().serializeToString(data);
                }
                obj.attr('data', `data:image/svg+xml,${encodeURIComponent(data)}`)
                img.replaceWith(div);
            });
        }
    });
})();