Utilisateur:NoFWDaddress/Brouillon/MediaWiki:Gadget-markAdmins.js

Une page de Wikipédia, l'encyclopédie libre.
Note : après avoir enregistré la page, vous devrez forcer le rechargement complet du cache de votre navigateur pour voir les changements.

Mozilla / Firefox / Konqueror / Safari : maintenez la touche Majuscule (Shift) en cliquant sur le bouton Actualiser (Reload) ou pressez Maj-Ctrl-R (Cmd-R sur Apple Mac) ;

Chrome / Internet Explorer / Opera : maintenez la touche Ctrl en cliquant sur le bouton Actualiser ou pressez Ctrl-F5.
/**
*  Flag administrators and special user group members with a letter
*  in parenthesis behind links that go into their user namespace.
*  
* Source: https://commons.wikimedia.org/wiki/MediaWiki:Gadget-markAdmins.js
* 
* @Documentation: https://commons.wikimedia.org/wiki/MediaWiki_talk:Gadget-markAdmins.js
*  E.g. Didym -> Didym (A)
*  
*  @rev 2 (12 août 2018 à 12:39 CEST)
*  Last sync with origin: 12 août 2018 à 12:39 CEST
* 
*  @author Euku, 2005
*  @author PDD
*  @author Littl
*  @author Guandalug
*  @author Didym, 2014
*  @author Rillke <https://blog.rillke.com>, 2014
*  @author NoFWDaddress <https://twitter.com/NoFWDaddress>, 2018 (adaptation frwiki)
*/

// <nowiki>

/*global jQuery:false, mediaWiki:false*/

(function( mw, $ ) {
'use strict';

var markAdmins = mw.libs.markAdmins = {
	nodes: [], // for reInit
	config: {},
	defaults: {
		groups: {
			sysop: {
				label: 'A',
				legacyName: 'sysop',
				legacyLabelId: 'atxt',
				enabled: true
			},
			oversight: {
				label: 'OS',
				legacyName: 'oversight',
				legacyLabelId: 'oversighttxt',
				enabled: true
			},
			checkuser: {
				label: 'CU',
				legacyName: 'checkuser',
				legacyLabelId: 'checkusertxt',
				enabled: true
			},
			bureaucrat: {
				label: 'B',
				legacyName: 'bureaucrat',
				legacyLabelId: 'bureautxt',
				enabled: true
			},
			steward: {
				label: 'S',
				legacyName: 'steward',
				legacyLabelId: 'stewtxt',
				enabled: true
			},
			'otrs-member': {
				label: 'O',
				legacyName: 'otrs',
				legacyLabelId: 'otrstxt',
				enabled: true
			}
		},
		runOn: ['Spécial', 'Utilisateur', 'Projet', 'Aide', 'Wikipédia'],
		runOnHistory: true,
		runOnTalk: true,
		runOnDiff: true
	},
	init: function ( users ) {
		markAdmins.users = users;
	// Wait for user configuration through their .js
	// Not adding as a gadget dependency because user .js
	// is sometimes invalid and fails loading and
	// gadget dependencies do not offer failed/error options
		mw.loader.using( 'user', markAdmins.mergeConfig, markAdmins.mergeConfig );
	},
	mergeConfig: function () {
		// Merge new configuration
		var optionsConfig = mw.user.options.get('markAdminCfg');
		var cfg = $.extend(
				true,
				markAdmins.config,
				markAdmins.defaults,
				window.markAdminCfg || {},
				optionsConfig ? JSON.parse(optionsConfig) : {}
			);

		cfg.markSubpages = !!window.marksubpages;
		cfg.dontMarkMyself = window.dontmarkmyself ? mw.config.get('wgUserName') : false;

		// Hook-up content loading
		mw.hook('wikipage.content').add( function ($c) { markAdmins.addLabels($c); } );
	},
	destroy: function () {
		$.each(markAdmins.nodes, function (i, n) {
			$(n).remove();
		});
	},
	reInit: function () {
		markAdmins.destroy();
		markAdmins.mergeConfig();
	},

	addLabels: function ( $content ) {
		var content = document.getElementById('mw-content-text') || document.getElementById('bodyContent') || $content[0];
		// Right, the configuration evaluation is here
		// It might be possible to use Ajax for page
		// navigation in future.
		var canNs         = mw.config.get('wgCanonicalNamespace'),
			isSubpageL    = !!({'Prefixindex': 1, 'Allpages': 1})[mw.config.get('wgCanonicalSpecialPageName')],
			ns            = mw.config.get('wgNamespaceNumber'),
			isUserpage    = ns === 2 || ns === 3,
			isHistory     = mw.config.get('wgAction') === 'history',
			isTalk        = ns % 2,
			isDiff        = !!mw.util.getParamValue( 'diff' ),
			reUserpage    = /^\/wiki\/(Discussion[ _])?[Uu]tilisateur:(.+)/,
			cfg           = this.config,
			nsCondition   = cfg.runOn.indexOf(canNs) !== -1,
			enabledGroups = {},
			marker        = {},
			previousUser, anchors;

		// Namespace run conditions
		if ( !( nsCondition ||
				isHistory && cfg.runOnHistory ||
				isTalk && cfg.runOnTalk ||
				isDiff && cfg.runOnDiff ) ) return;

		// Filter enabled groups
		// Do it here and not later on each anchor
		$.each( cfg.groups, function( g, grpCfg ) {
			if ( grpCfg.enabled ) enabledGroups[g] = grpCfg;
		} );

		if (isUserpage) { // Add also the userpage link!?
			anchors = $content.find('a');
			anchors.push($('#ca-nstab-user').find('a')[0]);
		} else
			anchors = content.getElementsByTagName('a');

		var node = document.createElement('b');
		node.className = 'adminMark';
		
		for (var i = 0, lenAnchors = anchors.length; i < lenAnchors; ++i) {
			var a = anchors[i];
			var href = a && a.getAttribute( 'href' ); // Extract link
			if ( !href ) continue;
			// Extract user page ( /wiki/User_talk:Foo/subpage -> Foo/subpage )
			var m = href.match( reUserpage );
			if ( !m || !m[2] ) continue;
			var userpage = m[2];
			// Extract user
			var user = userpage.replace( /[\/\#].*/, '' );
			var isMainUserpageLink = (user === userpage);
			var isUsertalkLink     = !!m[1];
			// Polish user name
			user = decodeURIComponent( user ).replace( /_/g, ' ' );
			// Two consecutive links to the same user? Don't mark followups!
			previousUser = (previousUser === user && isUsertalkLink);
			if (previousUser) continue;// only once

			var userM = marker[user];
			if (userM === undefined) {
				// User groups of selected user
				userM = '';
				var userGroups = this.users[user];
				if ( !userGroups ) continue;
				
				for (var g = 0; g < userGroups.length; g++) {
					var grpCfg = enabledGroups[userGroups[g]];
						if ( !grpCfg ) break;
					// String concatenation is oftentimes faster in modern browsers,
					// so using Arrays and joining them finally seems advantage.
					// But we would need an additional IF, so there is no gain.
					if ( userM ) userM += '/';
					userM += grpCfg.label;
				}
				marker[user] = userM ? [userM] : userM;
			}
			// Are there markers at all?
			if ( !userM ) continue;
			// Don't mark certain pages, except link to user main page.
			// Does the link go to the main user page or, if linking subpages is enabled,
			// is it not a page that is just listing subpages?
			if (!(isMainUserpageLink || cfg.markSubpages && !isSubpageL)) continue;
			if (cfg.dontMarkMyself && user === cfg.dontMarkMyself) continue;
			// Check finished, now append node
			marker[user][1] = this.markUser(marker[user], a, node);
			// Required for consecutive user link check
			previousUser = user;
		} // end loop
	},
	markUser: function (mark, a, node) {
		if (mark[1]) {
			node = mark[1].cloneNode(1);
		} else {
			node = node.cloneNode(1);
			node.appendChild(document.createTextNode('\u00A0(' + mark[0] + ')'));
		}
		a.appendChild(node);
		this.nodes.push(node);  // for reInit
		return node;
	}

};
mw.hook( 'userjs.script-loaded.markadmins' ).add( markAdmins.init );
}( mediaWiki, jQuery ));