MediaWiki:Gadget-GoogleImagesTineye.js

/*global mw, $*/


$(function (imgURL) {
'use strict';
if (mw.config.get('wgNamespaceNumber') !== 6 || mw.config.get('wgAction') !== "view" || !document.getElementById('file'))
	return;

var img = document.querySelectorAll('#mw-imagepage-section-filehistory img,#mw-imagepage-section-filehistory .mw-tmh-player video')[0];

if ( !img ) {
	return; // No thumbs, e.g. for large PNGs and audio files
}
if ( img.tagName == 'VIDEO') {
	imgURL = img.poster;
} else {
	imgURL = img.src;
}

imgURL = imgURL.replace(/\?.*/,'');

if ( ! imgURL.match('/thumb/') ) { //the image is SO small that the original is used in the file history
	imgURL = imgURL.replace(/\?.*/,'').replace('/wikipedia/commons/','/wikipedia/commons/thumb/').replace(/\/([^\/]*$)/,'/$1/500px-$1');
}

imgURL = imgURL.replace(/\/([0-9])+px[\-]+([^\/]*)$/,'/500px-$2'); //upgrade thumb to 500px. video poster thumbnails have two dashes, change to one

var portletLink = mw.util.addPortletLink('p-cactions', 'https://lens.google.com/uploadbyurl?url=' + encodeURIComponent(imgURL), 'Google Lens', 'ca-googleimages', null);
if(portletLink && portletLink.children[0]) portletLink.children[0].target = '_blank';

portletLink = mw.util.addPortletLink('p-cactions', 'https://tineye.com/search?url=' + encodeURIComponent(imgURL) + '&sort=size&order=desc', 'TinEye', 'ca-tineye', null);
if(portletLink && portletLink.children[0]) portletLink.children[0].target = '_blank';

portletLink = mw.util.addPortletLink('p-cactions', 'https://yandex.com/images/search?rpt=imageview&url=' + encodeURIComponent(imgURL), 'Yandex', 'ca-yandex', null);
if(portletLink && portletLink.children[0]) portletLink.children[0].target = '_blank';

var preload500px = function(){ //load the 500px thumbnail when user interacts or moves over the reverse image search links. This prevents Google/etc from having to wait too long or hitting a 429 if the 500px thumb didn't exist yet (see T413570 and similar tasks)
	if ( ! document.getElementById('preload500pxthumb') ) {
		var preload500pxthumb = document.createElement('img');
		preload500pxthumb.src = imgURL;
		preload500pxthumb.style.display = 'none';
		preload500pxthumb.id = 'preload500pxthumb';
		document.body.append(preload500pxthumb);
}
};
$('#ca-googleimages,#ca-tineye,#ca-yandex').on('mouseover click touchstart touchmove touchend', function(){preload500px()});

});