User:Lunarity/global.js

/*jshint smarttabs:true laxbreak:true laxcomma:true curly:false bitwise:false browser:true devel:true jquery:true es5:true */ /*global importScriptPage mediaWiki */

// polyfill for 'matches' selector function // http://www.w3.org/TR/2012/WD-selectors-api2-20120628/#interface-definitions (function {	"use strict";	var e = document.createElement('div'); // document.body isn't available yet	if (!e.matches) {		var polyfill = e.mozMatchesSelector		   || e.webkitMatchesSelector		    || e.msMatchesSelector //IE9		    || e.oMatchesSelector		    || (e.querySelectorAll && function(aSel) { //IE8 has querySelector[All] but not 'matches' var p = this.parentNode, result = 0, nodes, i;			if (!p) { // Detached node with no parent // There's a minor bug that a selector with 'div' as the last ancestor // will match because of this trick when it shouldn't.				p = e;				p.appendChild(this); result = 8; }			nodes = p.querySelectorAll(aSel); i = nodes.length; while (i--) { if (nodes[i] === this) { result |= 1; break; }			}			if (result & 8) p.removeChild(this); return !!(result & 1); });		if (polyfill) {			// http://msdn.microsoft.com/en-us/library/dd282900(v=vs.85).aspx			window.Element.prototype.matches = polyfill;			if (window.HTMLDocument && !window.HTMLDocument.prototype.matches) {				window.HTMLDocument.prototype.matches = polyfill;			}		}	} });

// Mozilla MDN code. if (!Array.prototype.forEach) Array.prototype.forEach = function(fn, scope) { "use strict"; scope = scope || this; for(var i = 0, l = this.length | 0; i < l; ++i) { fn.call(scope, this[i], i, this); } };

// Block enter key from submitting any and all forms. Forms must be submitted via clicking // Submit button or it will be blocked. This prevents accidental typoing Enter when moving // pages/edit summaries/etc. // TODO: This is on probation, it may need tweaking to avoid glitchery jQuery(function($) {	"use strict";	// Only visible submit buttons will be processed so we don't break anything.	$('input[type="submit"]').filter(':visible').closest('form').not('.WikiaSearch').each(function { // Textareas won't submit on enter so that's fine. $(this).on('keypress', 'input', function(event) {			// This is lighter than :not			if (({submit:1,reset:1,button:1,image:1})[this.type] === 1) return;			if (event.which === 13) event.preventDefault;		}); }); });

// Remove Wikia's keypress handler on the Edit Summary. It's a script that // does form.submit when enter is pressed which defeats the above. if (({edit:1,editredlink:1,submit:1})[mediaWiki.config.get('wgAction')] === 1) { window.GlobalTriggers.bind('WikiaEditorReady', function disableEnterKey {		"use strict";		console.log('HACK: Unbind edit summary keyboard handlers is running');		$('#wpSummary').off('keypress').on('keypress', function(e) { // Cancel event and stop propagation of enter key. return e.which !== 13; });		window.GlobalTriggers.unbind('WikiaEditorReady', disableEnterKey);	}); }

// Boost Oasis width to 1200px. Pairs with HideRail, must come first to be reliable. importScriptPage('OasisWideMode/code.js', 'dev');

// Moved to dev.wikia.org, import from self window.HideRailjs = { showEditPage: true, showMainPage: true }; importScriptPage('HideRail/code.js', 'dev');

importScriptPage('AntiUnicruft/code.js', 'dev');

importScriptPage('DisplayClock/code.js', 'dev');

// Reveal Anonymous Editors importScriptPage('RevealAnonIP/usercode.js', 'dev');

/** * Fix the MediaWiki diffs (including AJAX ones). * Display the diffs in monospace font with white-space preservation. * We can't just use CSS for this because MediaWiki generates bad diffs; there are * unnecessary new-lines added at the start and end of each modified line in the * diff which obviously end up being shown unless we fix it. * This script strips the unnecessary new-line characters as well as setting * the inline styles to monospace/pre-wrap (Easier to manage all in one place). * * The Edit page fixing only works in browsers with MutationObserver support. * Those are Firefox14+ or Chrome18+. * NOTE: Wikia uses $.showModal to show the edit popups, I can assume that and *  install a hook instead of using the body observer but that doesn't really *  help with the table insertion. I think jQuery's append provides a hook which *  would allow me to replace the popup observer but it's more foolproof just to *   use the browser feature instead. */ jQuery(function {	"use strict";	var w = window,	   document = w.document,	    mwconf = w.mediaWiki.config;

var _selectors = 'td.diff-addedline, td.diff-deletedline, td.diff-context'; _selectors = _selectors.replace(/((?:^|,)\s*)([^,]+)/g, '$1table.diff $2 > div');

// jQuery hard constrains the given selectors to the context. If the selector // references any nodes which are above the context node in the tree then the // selector will always fail. It makes more sense for the CSS selector to	// start from the node and walk up the tree, following the selector right to // left (which is what the standard says) but whatever. // querySelectorAll works that way so we can just use that. //	function fixSingleNode(aNode/*, aIndex, aArray*/) // Array.forEach compatible {		aNode.normalize; // Merge adjacent text nodes to simplify this var n = aNode.firstChild; if (n.nodeType === 3) // n.TEXT_NODE === 3 n.data = n.data.replace(/^\s*\n/, ""); n = aNode.lastChild; if (n.nodeType === 3) n.data = n.data.replace(/\n\s*$/, ""); }	function observeDialog(mutations) {		// mutations is an Array of MutationRecord /*interface MutationRecord { readonly attribute DOMString type; readonly attribute Node target; readonly attribute NodeList? addedNodes; //? means optional readonly attribute NodeList? removedNodes; readonly attribute Node? previousSibling; readonly attribute Node? nextSibling; readonly attribute DOMString? attributeName; readonly attribute DOMString? attributeNamespace; readonly attribute DOMString? oldValue; };*/		// The mutation list only generates mutations for direct changes. Adding // a whole sub-tree only generates one mutation for the root node that // was placed into the DOM (i.e. a node already in the DOM had a new child		// added). This is understandable but it means the mutations aren't very // useful directly, we need to do a full sub-tree search with selectors. var m, n, sel = _selectors; for (var i = mutations.length ; i-- ; ) { m = mutations[i].addedNodes; for (var j = m.length ; j-- ; ) { n = m[j]; // We get non-element nodes like Text and Comment nodes as well, filter if (n.nodeType !== 1) continue; // 1 = ELEMENT_NODE [].forEach.call(n.querySelectorAll(sel), fixSingleNode); // Both jQuery and querySelectorAll will only match children, fix. if (n.matches(sel)) fixSingleNode(n); }		}	}	var _observer, _dialog; function observeBody(/*mutations*/) {		// This is simpler than walking the mutation list, may be faster as well var node = document.getElementById('EditPageDialog'); if (node !== _dialog) { _dialog = node; _observer.disconnect; // Prevent leaking previous DOM sub-tree if (node) { [].forEach.call(node.querySelectorAll(_selectors), fixSingleNode); _observer.observe(node, {					childList: true,					subtree: true // All children of all sub-nodes				}); }		}	}

// Build custom stylesheet. // I could stick this in global.css but then I'd have to keep the selectors in sync // IE doesn't process CSS nodes correctly, you need to set the non-standard 'styleSheet' prop // but I don't use IE so I don't care. var s = document.createElement('style'); s.type = 'text/css'; s.appendChild(document.createTextNode( _selectors + "{" + "font-family: monospace;" + "white-space: pre-wrap;" // Break anywhere, ignore language rules + ((/\.(?:js|css)(?:\/|$)/i).test(mwconf.get('wgPageName')) ? "word-break: break-all;" : '') + "word-wrap: break-word; overflow-wrap: break-word" + "}"		+ 'table.diff { border-spacing: 1px !important }' ));	document.head.appendChild(s); // document.head is HTML5 if (mwconf.get('skin') !== 'oasis') return; // Monobook only needs the CSS

// If we're on a page with diffs then run the fix. // NOTE: Switches are crazy bad in JS (It's just a sugar if/else-if chain) // http://www.mediawiki.org/wiki/Manual:Parameters_to_index.php s = {}; s.view = s.historysubmit = function(action) { // Regex uses look-ahead (?= means "followed by"). The trick is that the line // is not *consumed* by the look-ahead matches so the 2nd (or more) // look-aheads get to walk over the same characters. // 1.19 uses view for history. 1.16 uses historysubmit. if (action !== 'view' || /^(?=.*?[\?&]diff=)(?=.*?[\?&]oldid=)/.test(w.location.search)) { [].forEach.call(document.querySelectorAll(_selectors), fixSingleNode); }	};	s.edit = s.editredlink = s.submit = function { // We use the DOM4 MutationObserver to detect when the pop-up is shown. var Observer = w.MutationObserver || w.WebKitMutationObserver || w.MozMutationObserver; if (!Observer) return;

var bodyObs = new Observer(observeBody); _observer = new Observer(observeDialog); // We observe nodes added to the body *directly*, not any of its // children. This is more efficient since the overlay is always added // to and we won't get events caused by the WYSIWYG editor. bodyObs.observe(document.body, {childList: true}); };	var f = mwconf.get('wgAction'); if (s.hasOwnProperty(f)) try { s[f](f); } catch(e) {} f = s = null; });