Difference between revisions of "MediaWiki:Common.js"

From RationalWiki
Jump to navigation Jump to search
m
m (to screenshot)
Line 440: Line 440:
  
 
//Toggle indentation
 
//Toggle indentation
randomcpindent = true;
+
//randomcpindent = true;
  
 
importScript("User:Nx/Scripts/RandomCP.js");
 
importScript("User:Nx/Scripts/RandomCP.js");

Revision as of 05:28, 9 April 2009

/* Any JavaScript here will be loaded for all users on every page load. */

// Adds a tab allowing you to edit the 0th section of a page (the top area usually used as an introduction).
//

addOnloadHook(function () {
    var x;
    if (!(x = document.getElementById('ca-edit') )) return;
    var url;
    if (!(url = x.getElementsByTagName('a')[0] )) return;
    if (!(url = url.href )) return;
    var y = addPortletLink('p-cactions', url+"&section=0", '0', 'ca-edit-0',
                           'Edit the lead section of this page', '0', x.nextSibling);

    y.className = x.className;  // steal classes from the the edit tab...
    x.className = 'istalk';     // ...and make the edit tab have no right margin

    // exception: don't steal the "selected" class unless actually editing section 0:
    if (/(^| )selected( |$)/.test(y.className)) {
        if (!document.editform || !document.editform.wpSection
            || document.editform.wpSection.value != "0") {
            y.className = y.className.replace(/(^| )selected( |$)/g, "$1");
            x.className += ' selected';
        }
    }
});

/* Test if an element has a certain class **************************************
 *
 * Description: Uses regular expressions and caching for better performance.
 * Maintainers: [[User:Mike Dillon]], [[User:R. Koot]], [[User:SG]]
 */
 
var hasClass = (function () {
    var reCache = {};
    return function (element, className) {
        return (reCache[className] ? reCache[className] : (reCache[className] = new RegExp("(?:\\s|^)" + className + "(?:\\s|$)"))).test(element.className);
    };
})();

/** Collapsible tables *********************************************************
 *
 *  Description: Allows tables to be collapsed, showing only the header. See
 *               [[Wikipedia:NavFrame]].
 *  Maintainers: [[User:R. Koot]]
 */
 
var autoCollapse = 2;
var collapseCaption = "hide";
var expandCaption = "show";
 
function collapseTable( tableIndex )
{
    var Button = document.getElementById( "collapseButton" + tableIndex );
    var Table = document.getElementById( "collapsibleTable" + tableIndex );
 
    if ( !Table || !Button ) {
        return false;
    }
 
    var Rows = Table.rows;
 
    if ( Button.firstChild.data == collapseCaption ) {
        for ( var i = 1; i < Rows.length; i++ ) {
            Rows[i].style.display = "none";
        }
        Button.firstChild.data = expandCaption;
    } else {
        for ( var i = 1; i < Rows.length; i++ ) {
            Rows[i].style.display = Rows[0].style.display;
        }
        Button.firstChild.data = collapseCaption;
    }
}
 
function createCollapseButtons()
{
    var tableIndex = 0;
    var NavigationBoxes = new Object();
    var Tables = document.getElementsByTagName( "table" );
 
    for ( var i = 0; i < Tables.length; i++ ) {
        if ( hasClass( Tables[i], "collapsible" ) ) {
 
            /* only add button and increment count if there is a header row to work with */
            var HeaderRow = Tables[i].getElementsByTagName( "tr" )[0];
            if (!HeaderRow) continue;
            var Header = HeaderRow.getElementsByTagName( "th" )[0];
            if (!Header) continue;
 
            NavigationBoxes[ tableIndex ] = Tables[i];
            Tables[i].setAttribute( "id", "collapsibleTable" + tableIndex );
 
            var Button     = document.createElement( "span" );
            var ButtonLink = document.createElement( "a" );
            var ButtonText = document.createTextNode( collapseCaption );
 
            Button.style.styleFloat = "right";
            Button.style.cssFloat = "right";
            Button.style.fontWeight = "normal";
            Button.style.textAlign = "right";
            Button.style.width = "6em";
 
            ButtonLink.style.color = Header.style.color;
            ButtonLink.setAttribute( "id", "collapseButton" + tableIndex );
            ButtonLink.setAttribute( "href", "javascript:collapseTable(" + tableIndex + ");" );
            ButtonLink.appendChild( ButtonText );
 
            Button.appendChild( document.createTextNode( "[" ) );
            Button.appendChild( ButtonLink );
            Button.appendChild( document.createTextNode( "]" ) );
 
            Header.insertBefore( Button, Header.childNodes[0] );
            tableIndex++;
        }
    }
 
    for ( var i = 0;  i < tableIndex; i++ ) {
        if ( hasClass( NavigationBoxes[i], "collapsed" ) || ( tableIndex >= autoCollapse && hasClass( NavigationBoxes[i], "autocollapse" ) ) ) {
            collapseTable( i );
        }
    }
}
 
addOnloadHook( createCollapseButtons );

function collapsedCommentLinkClickHandler(e) {
	e = e || window.event;
	var eventSource = e.target || e.srcElement;
	
	// firstly, collapse all tables
	var tableIndex = 0;
	var collapsibleButton = document.getElementById("collapseButton" + tableIndex);	

	while (collapsibleButton) {
		if (collapsibleButton.firstChild.data == collapseCaption) {
			collapseTable(tableIndex);
		}
		collapsibleButton = document.getElementById("collapseButton" + ++tableIndex);
	}

	// now, see if we can find the table to which this anchor refers
	var anchorIndex = eventSource.href.indexOf('#');
	if (anchorIndex != -1) {
		var anchorName = eventSource.href.substring(anchorIndex+1);
		var tableDiv = document.getElementById(anchorName);
		if (tableDiv) {
			// look for a collapsible table nested in this div, and expand it
			var tables = tableDiv.getElementsByTagName("table");
			for (var i = 0; i < tables.length; ++i) {
				if (hasClass(tables[i], "collapsible") && tables[i].id.substring(0, 16) == "collapsibleTable") {
					tableIndex = tables[i].id.substring(16);
					collapseTable(tableIndex);
				} 
			}
		}
	}	
}

function addOnclickEventsToCollapsedCommentLinks() {
	var spans = document.getElementsByTagName("span");
	
	for (var i = 0; i < spans.length; ++i) {
		if (spans[i].hasChildNodes() && hasClass(spans[i], "collapsed_comment_link")) {
			// look for links amongst this element's daughter elements
			var daughters = spans[i].getElementsByTagName("a");
			
			for (var j = 0; j < daughters.length; ++j) {
				// add an onclick handler to this anchor
				daughters[j].onclick = collapsedCommentLinkClickHandler;
			}
		}
	}
}

addOnloadHook(addOnclickEventsToCollapsedCommentLinks);

/*
  Inserts random block reasons from RationalWiki:Random_Block_Reasons and per-user block reasons from user's CustomBlockReasons subpage
*/
function insertAdditionalBlockReasons() {
	var blockReasonList = document.getElementById("wpBlockReasonList"); 
	if (null != blockReasonList) {

		// attempt to get a XmlHTTPRequest object
		var req = false;
		if (window.XMLHttpRequest) {
			// for sane browsers
			req = new XMLHttpRequest();
		}
		else if (window.ActiveXObject) {
			// oh dear, here's a nickel kid, get yourself a better browser.
			req = new ActiveXObject("Microsoft.XMLHTTP");
		}
	
		if (req) {
			var reasonsArray;
			var reasonOption;

			req.open("GET", "http://rationalwiki.com/wiki/index.php?title=RationalWiki:Random_Block_Reasons&action=raw&ctype=text/javascript", false);
			req.send(null);

			if (req.status == 200 && req.responseText != "/* Empty */" ) {
				// split lines in to an array
				reasonsArray = req.responseText.split("\n");
				reason = reasonsArray[Math.floor(Math.random() * reasonsArray.length)];
				var randomOptGroup = document.createElement('optgroup');
				randomOptGroup.label = "Random block reason";
				reasonOption = document.createElement("option");
				reasonOption.value = reason;
				if (typeof(reasonOption.innerText) != "undefined") {
					reasonOption.innerText = reason;
				}
				else {
					reasonOption.text = reason;
				}
				randomOptGroup.appendChild(reasonOption);
				blockReasonList.appendChild(randomOptGroup);
			}		

			req.open("GET", "http://rationalwiki.com/wiki/index.php?title=User:" +wgUserName+ "/CustomBlockReasons&action=raw&ctype=text/javascript", false);
			req.send(null);

			if (req.status == 200 && req.responseText != "/* Empty */") {
				// split lines in to an array
				reasonsArray = req.responseText.split("\n");
				var customOptGroup = document.createElement('optgroup');
				customOptGroup.label = "Custom block reasons";
				var i;
				for (i=0;i<reasonsArray.length;++i)
				{
					reason = reasonsArray[i];
					reasonOption = document.createElement("option");
					reasonOption.value = reason;
					if (typeof(reasonOption.innerText) != "undefined") {
						reasonOption.innerText = reason;
					}
					else {
						reasonOption.text = reason;
					}
					customOptGroup.appendChild(reasonOption);

				}	
				blockReasonList.appendChild(customOptGroup);

			}
		}
	}
}

addOnloadHook(insertAdditionalBlockReasons);


function insertMyName() {
	var nameSpan = document.getElementById("myName");
	if (nameSpan && wgUserName) {
		nameSpan.innerHTML = wgUserName;
	}
}

addOnloadHook(insertMyName);


/*
addsectionbottom
  Add a new section link to the bottom of discussion pages
*/

function addsectionbottom() {
  var caplus;
  if (!(caplus = document.getElementById("ca-addsection"))) return;
  var addsection = document.createElement("span");
  addsection.innerHTML = "<h3> <a " + "href=\"" + caplus.childNodes[0].getAttribute("href") + 
                         "\" title=\"" + caplus.childNodes[0].getAttribute("title") +
                         "\" accesskey=\"" + caplus.childNodes[0].getAttribute("accesskey") + 
                         "\" > <span> Add new section</span> </a> </h3>"
  addsection.className = "noprint";
  addsection.id = "addsectionbottom";
  var content;
  if (!(content = document.getElementById("bodyContent"))) return;
  var catlinks = document.getElementById("catlinks");
  if (catlinks == null)
  {
    content.appendChild(addsection);
  } else {
    content.insertBefore(addsection, catlinks);
  }
}

addOnloadHook(addsectionbottom);

// 
//

/*
  importScript and importStylesheet
    allows easy sharing of js and css
    part of wikibits.js in newer MediaWiki versions
*/

function importScript(page) {
	var uri = wgScript + '?title=' +
		encodeURIComponent(page.replace(/ /g,'_')).replace('%2F','/').replace('%3A',':') +
		'&action=raw&ctype=text/javascript';
	return importScriptURI(uri);
}
 
var loadedScripts = {}; // included-scripts tracker
function importScriptURI(url) {
	if (loadedScripts[url]) {
		return null;
	}
	loadedScripts[url] = true;
	var s = document.createElement('script');
	s.setAttribute('src',url);
	s.setAttribute('type','text/javascript');
	document.getElementsByTagName('head')[0].appendChild(s);
	return s;
}
 
function importStylesheet(page) {
	return importStylesheetURI(wgScript + '?action=raw&ctype=text/css&title=' + encodeURIComponent(page.replace(/ /g,'_')));
}
 
function importStylesheetURI(url) {
	return document.createStyleSheet ? document.createStyleSheet(url) : appendCSS('@import "' + url + '";');
}
 
function appendCSS(text) {
	var s = document.createElement('style');
	s.type = 'text/css';
	s.rel = 'stylesheet';
	if (s.styleSheet) s.styleSheet.cssText = text //IE
	else s.appendChild(document.createTextNode(text + '')) //Safari sometimes borks on null
	document.getElementsByTagName('head')[0].appendChild(s);
	return s;
}

/*
  insertMyName2
    uses class instead of id, allows more than one replacement per page
*/

function insertMyName2() {
  if (!wgUserName) return;
  var nameSpans = getElementsByClassName(document.getElementById("bodyContent"),"*","myName");
  for (var i=0;i<nameSpans.length;++i)
  {
    nameSpans[i].innerHTML = wgUserName;
  }
}

addOnloadHook(insertMyName2);

/*
  More advanced collapsible objects
*/

function showhide(targetid, showcaption, hidecaption, button)
{
  var targets = getElementsByClassName(button.parentNode.parentNode,"*",targetid);
  if (button.innerHTML == showcaption) {
    button.innerHTML = hidecaption;
  } else if (button.innerHTML == hidecaption) {
    button.innerHTML = showcaption;
  }
  for (var i = 0; i< targets.length; ++i)
  {
    if (targets[i].className.indexOf('collapsetarget') >= 0) {
      if (targets[i].style) {
        if (targets[i].style.display == 'none') {
          var cr = targets[i].className.match(/(.*)__olddisp:(.*);/);
          targets[i].className = cr[1];
          targets[i].style.display = cr[2];
        } else {
          targets[i].className += " __olddisp:" + targets[i].style.display + ";";
          targets[i].style.display = 'none';
        }
      }
    }
  }
}

function bindbutton(button,target,showcaption,hidecaption,button) {
    button.onclick = function() {
                       showhide(target,showcaption,hidecaption,button);
                     };
}

function createShowHideButtons(Collapsers)
{
  for (var i = 0; i < Collapsers.length; ++i )
  {
    var dataraw = Collapsers[i].className.match(/collapsedata:(.+)/)[1];
    var targetr = dataraw.match(/target:([^;]*);/);
    var target;
    if (targetr && targetr[1])
    {
      target = targetr[1];
    } else {
      continue;
    }
    var initialr = dataraw.match(/initial:(shown|hidden);/);
    initial = (initialr && initialr[1] && initialr[1] == 'hidden') ? false : true;
    var hidecaptionr = dataraw.match(/hidecaption:([^;]*);/);
    var hidecaption = 'hide';
    if (hidecaptionr && hidecaptionr[1])
    {
      hidecaption = hidecaptionr[1];
    }
    var showcaptionr = dataraw.match(/showcaption:([^;]*);/);
    var showcaption = 'show';
    if (showcaptionr && showcaptionr[1])
    {
      showcaption = showcaptionr[1];
    }
    var button = document.createElement('a');
    button.className = 'collapseButton';
    button.innerHTML = hidecaption;
    bindbutton(button,target,showcaption,hidecaption,button);
    button.style.cursor = "pointer";
    Collapsers[i].appendChild(button);
    if (!initial) {
      showhide(target,showcaption,hidecaption, button);
    }
  }
}

function setupCollapse()
{
   var Collapsers = getElementsByClassName(document.getElementById("bodyContent"),"*","collapser");
   if (Collapsers.length > 0) {createShowHideButtons(Collapsers)};
}

addOnloadHook(setupCollapse);

/*
  Random CP page [[User:Nx]] 01:24, 9 April 2009 (EDT)
*/

//Toggle indentation
//randomcpindent = true;

importScript("User:Nx/Scripts/RandomCP.js");