MediaWiki:Gadget-watchlist-counter.js

De Wikimedica

Note : après avoir enregistré vos modifications, il se peut que vous deviez forcer le rechargement complet du cache de votre navigateur pour voir les changements.

/* 
 * This gadget displays the number unread changes in a user's watched pages besides the link to the
 * watch list in the top toolbar.
 * Results are cached for 30 minutes to limit requests to the server.
 *
 * Caveat: when a page that is part of the watch list is visited, the counter is not refreshed.
*/

console.log("Loaded watchlist-counter gadget");
	
// Display the counter.
function display(num) 
{
	var str = num > 9 ? '9+': num.toString();
	
	var sel = $('#pt-watchlist a').attr('data-counter-text', str).attr('data-counter-num', str).addClass('pt-watchlist-set');
	sel.attr('title', sel.attr('title') + '(' + str + (num > 1 ? ' nouvelles modifications)': ' nouvelle modification)'));
	
	if(num > 0) { sel.addClass('pt-watchlist-new'); }
}

// Fetch the number of unread changes.
function fetch()
{
	api = new mw.Api();
	api.get( { // Retrieve the number of unread changes.
		action: 'query',
		list: 'watchlist',
		format: 'json',
		wlexcludeuser: mw.user.getName(),
		wllimit: 9,
		wlshow: '!minor|unread',
		wlprop: ''
	} ).done(function(data){
		
		if(data.query.watchlist === null) { return; } // Failed.
		
		num = data.query.watchlist.length;
		num += data.continue ? 1 : 0; // Set the number to 10 to indicate there are more than 9 unread changes.
	
		display(num);
		
		// Cache the result in a cookie.
		$.cookie("watchlist-counter.lastCheck", JSON.stringify({
			lastCheck: Date.now(),
			value: num
		}) , { expires: 7 });
		
	}, 'json');

}

if(!mw.user.isAnon()) // Skip if user is not logged in.
{
	// If there is a cookie caching the last number of unread changes
	if((lastCheck = $.cookie("watchlist-counter.lastCheck")) !== null && 
		mw.config.get('wgTitle') != "Liste de suivi" // Update every time when on the watchlist.
	)
	{
		try 
		{ 
			lastCheck = JSON.parse(lastCheck);
			
			// Check every 30 minutes.
			if(Date.now() - lastCheck.lastCheck < 30 * 60 * 1000)
			{
				display(lastCheck.value);
			}
			else { fetch(); }
			
			// It's been more than 30 minutes, refresh the result.
		}
		catch(e) {} // In case the JSON was tampered with.
	}
	else { fetch(); }
}