Jump to content

User:PhantomTech/Scripts/IRCNick.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// Intended to be used to make IRC help links use a default nick that's much
// easier to work with
// Author: PhantomTech
$( document ).ready( function ( $, mw ) {
	var userNick;
	var $ircLink = $( '#ircLink' );

	/**
	 * Pick a random nick.
	 *
	 * Uses a randomly selected color to get a "user-friendly" nick.
	 * Nicks are given in the format [color]-WP[number] where [color] is
	 * the random color and [number] is a random number between 100 and 999.
	 *
	 * @return {string} Nick
	 */
	function getRandomNick() {
		// Might not be a bad idea to have some more colors
		var nickOptions = [ 'red', 'pink', 'orange', 'yellow', 'green', 'cyan', 'blue', 'purple' ];
		return nickOptions[ Math.floor( Math.random() * 7 ) ] +
			'-WP' + Math.floor( Math.random() * 900 + 100 ).toString();
	}

	/**
	 * Pick a random nick based on user's username.
	 *
	 * Uses the user's username to get a "user-friendly" nick. Nicks are
	 * given in the format [username]-WP[number] where [username] is the
	 * username with non-alphanumeric characters replaced with an underscore
	 * and [number] is a random number between 10 and 99.
	 *
	 * @return {string} Nick
	 */
	function getUsernameNick() {
		return mw.user.getName().substring( 0, 11 ).replace( /\W/g, '_' ) +
			'-WP' + Math.floor( Math.random() * 90 + 10 ).toString();
	}

	// 'User:PhantomTech/sandbox/IRC_Disclaimer' will be replaced
	if ( mw.config.get( 'wgPageName' ) === 'User:PhantomTech/sandbox/IRC_Disclaimer' ) {
		// Check to make sure the link exists, then set the nick
		if ( $ircLink.length ) {
			if ( mw.user.isAnon() ) {
				userNick = getRandomNick();
			} else {
				userNick = getUsernameNick();
				var underscoreCount = 0;
				for ( var i = 0; i < userNick.length; i++ ) {
					if ( userNick.charAt( i ) === '_' ) {
						underscoreCount++;
					}
				}
				// If nick has so many underscores that it probably isn't useful
				if ( underscoreCount > 4 ) {
					userNick = getRandomNick();
				}
			}

			$ircLink.html( $ircLink.html().replace( /WPhelp\?/, userNick ) );
		}
	}
}( jQuery, mediaWiki ) );