User:Jgottula/common.js

'use strict';

// NOTE: MediaWiki is retarded and does not support any JS syntax newer than ES5, //      nor provide any mechanism for translating ES6 to ES5 (e.g. Babel), //      probably because their shitty backend is written in PHP (lol) //      https://phabricator.wikimedia.org/T178356

// purpose: rewrite all MediaWiki element URL's: // - if they already have a 'format=' query parameter, leave them alone // - otherwise: add 'format=original' // this ensures that Chrome's fucking stupid 'accept:' header // won't result in MediaWiki converting nice PNG's into ugly WebP's const re_fiximageurl = /^\/deadcells_gamepedia_en\/images\/[0-9a-f]{1}\/[0-9a-f]{2}\/.+$/; function FixImageURL(elem) {   if (elem.tagName.toLowerCase != 'img') return;

try { var before = elem.src;

var url = new URL(elem.src); if (!re_fiximageurl.test(url.pathname)) return;

// get rid of /scale-to-width-down/ URL component if (elem.hasAttribute('width') && elem.hasAttribute('data-file-width')) { var width = elem.getAttribute('width'); var dfwidth = elem.getAttribute('data-file-width'); if (width == dfwidth) { url.pathname = url.pathname.replace('/scale-to-width-down/' + width, ''); }		}

var query = new URLSearchParams(url.search); if (!query.has('format')) { query.append('format', 'original'); url.search = query.toString; }

elem.src = url.toString;

//console.log('FixImageURL: Before: ' + before); //console.log('FixImageURL: After: ' + elem.src); } catch (ex) { return; } }

function FixAllImagesNow {	var elems = document.getElementsByTagName('img'); for (var i = 0; i < elems.length; ++i) { FixImageURL(elems[i]); } }

// immediate fixup for all elements that already exist FixAllImagesNow;

// delayed fixup for all elements existing at the time of DOMContentLoaded event document.addEventListener('DomContentLoaded', FixAllImagesNow);

// ongoing monitoring for any elements that may be added to the DOM later /*let observer = new MutationObserver((mutations, observer) => {   for (const mutation of mutations) {        if (mutation.type === 'childList') {            for (let elem of mutation.addedNodes) {                FixImageURL(elem);            }        } else if (mutation.type === 'attributes') {            if (mutation.target.tagName == 'IMG' && mutation.attributeName == 'src') {                FixImageURL(elem);            }        }    } }); observer.observe(document, {   subtree: true,    childList: true,    attributes: true });*/