MediaWiki:Gadget-blueUsers.js

From Support Wiki
Jump to navigation Jump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
mw.loader.using( [ 'mediawiki.api', 'mediawiki.util' ] ).then( function () {
	// User cache to not check them multiple times.
	var blueUsers = [];
	var missingUsers = [];
	if ( mw.config.get('wgUserName') ) {
		blueUsers.push( mw.util.wikiUrlencode( mw.config.get('wgUserName') ) );
	}
	var api = new mw.Api( {parameters: {
		action: 'query',
		list: 'users',
		formatversion: 2
	} } );
	
	// Run every time content is added
	mw.hook( 'wikipage.content' ).add( makeUsersBlue );
	// Catch links outside the content area
	makeUsersBlue( $('a.new[href^="/wiki/User:"]').not('#mw-content-text a.new').parent() );
	
	function makeUsersBlue( $content ) {
		var users = [];
		var userlinks = $content.find( 'a.new[href^="/wiki/User:"]' ).each( function () {
			var encodedUsername = this.pathname.replace( /^\/wiki\/User:/, '' );
			if ( missingUsers.includes( encodedUsername ) ) return;
			if ( blueUsers.includes( encodedUsername ) ) {
				this.href = this.pathname;
				this.classList.remove( 'new' );
				this.classList.add( 'mw-newuserlink' );
				return;
			}
			var username = decodeURIComponent( encodedUsername );
			if ( users.includes( username ) || username.includes( '/' ) ) return;
			users.push( username );
		} );
		if ( !users.length ) return;
		var apiRequests = [];
		while ( users.length ) {
			apiRequests.push( api.get( {
				ususers: users.splice(0, 50)
			} ).done( function ( data ) {
				data.query.users.forEach( function ( user ) {
					if ( user.missing || user.invalid ) {
						missingUsers.push( mw.util.wikiUrlencode( user.name ) );
						return;
					}
					blueUsers.push( mw.util.wikiUrlencode( user.name ) );
				} );
			} ) );
		}
		Promise.all( apiRequests ).then( function () {
			userlinks.each( function () {
				if ( !blueUsers.includes( this.pathname.replace( /^\/wiki\/User:/, '' ) ) ) return;
				this.href = this.pathname;
				this.classList.remove( 'new' );
				this.classList.add( 'mw-newuserlink' );
			} );
		} );
	}
} );