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 05:12, 5 June 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(.*)$/;
    let observer = new ResizeObserver((entries) => {
        $(entries).each((index, entry) => {
            observer.unobserve(entry.target);
            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 && /\.svg$/i.test(matches[4]) && matches[6] === '.png') {
            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);
        }
    });
})();