User:Moros y Christianos/common.js

From Wikimedia Commons, the free media repository
Jump to navigation Jump to search
Note: After saving, you have to bypass your browser's cache to see the changes. Internet Explorer: press Ctrl-F5, Mozilla: hold down Shift while clicking Reload (or press Ctrl-Shift-R), Opera/Konqueror: press F5, Safari: hold down Shift + Alt while clicking Reload, Chrome: hold down Shift while clicking Reload.
importScript('User:Rillke/LicenseReview.js');
window.importScript('User:ZooFari/licensereviewer.js');
/**
 * Add buttons to show all Featured pictures, Quality images, or Valued images
 * ina and below the current category.
 * @author [[User:Dschwen]], 2014
 */
/* jshint laxcomma: true, smarttabs: true */
/* global mw,$ */
 
$(function(){
	var url = "fastcci1.wmflabs.org/"  // database backend url
	  , request, e = $('<div>')
	  , ls = ('localStorage' in window) ? window.localStorage : null;
 
	// request the fastcci db over HTTP (no streaming)
	function requestXHR(params, callback) {
		$.get("http://" + url, params)
			.done(function(data) {
			  	var res = data.split("\n");
				for (var i=0; i<res.length; ++i) { callback(res[i]); }
			});
	}
 
	// request the fastcci db over a WebSocket (streaming with progressive status updates)
	function requestSocket(params, callback) {
		ws = new WebSocket("wss://" + url + '?' + $.param(params)); 
		ws.onmessage = function (event) { callback(event.data); }
	}
 
	// determine request method
	request = ('WebSocket' in window) ? requestSocket : requestXHR;
 
	// debug output
	function debug(txt) {
		$('#bodyContent').append($('<pre></pre>').text(txt));
	}
 
	// process result by API call (res is a line returned by the server)
	function processResult(res, callback, append) {
		var ids = res.split('|')  // get ID list
		  , ret = append || [];   // return data
 
		// query all IDs
		$.get(mw.util.wikiScript('api'), { 
			action: 'query', 
			pageids: res,
			format: 'json',
			utf8: true,
			prop: 'imageinfo|info',
			iiprop: 'size|user', inprop: 'url'
		})
		.done(function(data){
			var l=ids.length, p=data.query.pages;
			for (j=0; j<l; ++j) {
				if (ids[j] in p) { 
					ret.push(p[ids[j]]);
				} else {
					ret.push(null);
				}
			}
			callback(ret);
		})
	}
 
	// breadcrumbs (TODO: this breaks if the server returns two result lines. We need a reliable way to aggregate the results)
	function  breadCrumbs(txt) {
		var token = txt.replace(/(\r\n|\n|\r)/gm,"").split(' '), ids, d=300;
		if (token.length!=2 || token[0]!='RESULT') return;
		processResult(token[1],function(trail){
			var l=trail.length, i, bc=[];
			for (i=0;i<l;++i) {
				if ('fullurl' in trail[i] && 'title' in trail[i]) {
					bc.push('<a href="' + trail[i].fullurl + '">' + trail[i].title.replace(/^Category:/,"") + '</a>');
				} else {
					bc.push("???");
				}
			}
			$('#bodyContent').prepend( $('<div>').addClass('fastcci-breadcrumbs').html(bc.join(' &rarr; ')) );
		})
	}
 
	// append to result gallery
	function addToGallery(txt) {
		var token = txt.split(' '), ids, d=300;
		if (token.length<2 || token[0]!='RESULT') return;
 
		// get ID list
		ids = token[1].split('|');
 
		// query all IDs
		$.get(mw.util.wikiScript('api'), { 
			action: 'query', 
			pageids: token[1],
			format: 'json',
			utf8: true,
			prop: 'imageinfo|info',
			iiprop: 'size|user', inprop: 'url'
		})
		.done(function(res){
			console.log(res);
			var l=ids.length, j, ow,oh, w,h, p, i, t;
			for (j=0; j<l; ++j) {
				p = res.query.pages[ids[j]];
				i = p.imageinfo[0];
				ow = i.width;
				oh = i.height;
				if (ow>oh) { w=Math.round(ow*d/oh); h=d;	}
				else { h=Math.round(oh*d/ow); w=d; }
 
				t = new mw.Title(p.title);			
				e.append(
					$('<div></div>')
						.css( {width:d+'px', height:d+'px', overflow:'hidden', display: 'inline-block', position:'relative', margin:'5px', 'box-shadow':'3px 3px 15px rgba(0,0,0,0.3)'} )
						.append(
							$('<a>').attr('href',p.fullurl).append(
								$('<img>')
									.attr('src', '/w/thumb.php?w='+Math.ceil(w)+'&f='+encodeURIComponent(t.getMain()))
									.css( {position:'absolute', left:Math.round(-(w-d)/2)+'px', top:Math.round(-(h-d)/2)+'px'} )
							).on('click', function() {
								// when clicking on an image in the results store the current category
								if (ls) { ls.setItem('fastcci_from',wgArticleId); }
							})
						)
				)
			}
		})
	}
 
	// request wrapper that prepares the gallery
	function fetchGallery(params) {
		e.empty().prependTo('#bodyContent');
		request(params, addToGallery);
	}
 
	// build category FP/QI/VI UI
	function addCatUI() {
		var box = $('<div>').addClass('fastcci-catbox');
 
		$('<a>')
			.append($('<img>').attr('src','//upload.wikimedia.org/wikipedia/commons/thumb/e/e7/Cscr-featured.svg/32px-Cscr-featured.svg.png'))
			.append($('<span>').text('Featured pictures'))
			.on('click',function(){ fetchGallery({c1: wgArticleId, c2: 3943817, d2: 1, s: 100}); })
			.appendTo(box);
		$('<a>')
			.append($('<img>').attr('src','//upload.wikimedia.org/wikipedia/commons/thumb/8/8c/Quality_images_logo.svg/32px-Quality_images_logo.svg.png'))
			.append($('<span>').text('Quality images'))
			.on('click',function(){ fetchGallery({c1: wgArticleId, c2: 3618826, d2: 1, s: 1000}); })
			.appendTo(box);
		$('<a>')
			.append($('<img>').attr('src','//upload.wikimedia.org/wikipedia/commons/thumb/d/d7/Valued_image_seal.svg/32px-Valued_image_seal.svg.png'))
			.append($('<span>').text('Valued images'))
			.on('click',function(){ fetchGallery({c1: wgArticleId, c2: 3862724, d2: 1, s: 1000}); })
			.appendTo(box);
 
		$('#bodyContent').prepend(box);
	}
 
	var ns = mw.config.get('wgNamespaceNumber');
	if (ns==14) addCatUI();
	if (ls) {
		// display breadcrumbs?
		var from = ls.getItem('fastcci_from');
		if (ns==6 && from) {
			request({c1: parseInt(from), c2: wgArticleId, a:'path'}, breadCrumbs);
		}
		ls.removeItem('fastcci_from');
	}
});