Benutzer:Codeispoetry/supportFuncs.js

aus Wikipedia, der freien Enzyklopädie

Hinweis: Leere nach dem Veröffentlichen den Browser-Cache, um die Änderungen sehen zu können.

  • Firefox/Safari: Umschalttaste drücken und gleichzeitig Aktualisieren anklicken oder entweder Strg+F5 oder Strg+R (⌘+R auf dem Mac) drücken
  • Google Chrome: Umschalttaste+Strg+R (⌘+Umschalttaste+R auf dem Mac) drücken
  • Internet Explorer/Edge: Strg+F5 drücken oder Strg drücken und gleichzeitig Aktualisieren anklicken
  • Opera: Strg+F5
//  Benutzer:Codeispoetry/supportFuncs.js   ++ PerfektesChaos  2012-09-06

/*global importScript, jsMsg, DOM, UrlParameters, importScriptURI, Cookie, Ajax, XMLUtil, wgScript */
importScript('Benutzer:D/monobook/api.js'); //[[Benutzer:D/monobook/api.js]]

var SimpleUI = {
	ButtonsBoxName: 'promptBoxButtons',

	/**
	create a span containing one checkbox and its label for every input element, separated with a br tag
		inputs[n][0]		contains the id
		inputs[n][1]		contains the title attribute
		inputs[n][2][key]	contains an attribute
		inputs[n][3]		contains a label added to the block's innerHTML

	*/
	CheckboxBox: function (caption, blockid, inputs, buttons, id) {
		var message = document.createElement('div');

		message.appendChild(document.createTextNode(caption));
		var block = document.createElement('span');
		block.id = blockid;
		var	boxes	= [];
		for (var n = 0 ; n < inputs.length ; ++n) {
			block.appendChild(document.createElement('br'));
			var box = document.createElement('input');
			box.id = inputs[n][0];
			box.setAttribute('title', inputs[n][1]);
			box.setAttribute('type', 'checkbox');
			for (var attr in inputs[n][2]) {
				if ((attr === 'checked' || attr === 'disabled') && inputs[n][2][attr] === false) {
					box.attr = inputs[n][2][attr];
				} else {
					box.setAttribute(attr, inputs[n][2][attr]);
				}
			}
			boxes.push(box);
			block.appendChild(box);

			var	label	= document.createElement("span");
			label.innerHTML = (typeof inputs[n][3] !== 'undefined') ? inputs[n][3] : inputs[n][1];
			block.appendChild(label);
		}

		// add a link checking all checkboxes defined above
		var	allSeparator	= document.createElement("br");
		var	allCheck		= document.createElement("a");
		allCheck.textContent	= "Alle deaktivieren";
		allCheck.style.cursor	= "default";
		allCheck.onclick	= function() {
			for (var i=0; i<boxes.length; i++) {
				boxes[i].checked	= false;
			}
		};
		block.appendChild(allSeparator);
		block.appendChild(allCheck);

		for (var i = 0 ; i < boxes.length ; i++) {
			boxes[i].onblur = SimpleUI.OnBlur;
			boxes[i].onfocus = SimpleUI.OnFocus;
		}
		message.appendChild(block);

		message.appendChild(SimpleUI.ButtonBlock(buttons));
		SimpleUI.Box(message, id);

		boxes[0].focus();
	},

	EditBox: function (caption, text, buttons, id) {
		var message = document.createElement('div');

		message.appendChild(document.createTextNode(caption));
		var area = document.createElement('textarea');
		area.setAttribute('cols', '15');
		area.setAttribute('rows', '10');
		area.id = 'simpleEdit';
		area.value = text;
		message.appendChild(area);

		message.appendChild(SimpleUI.ButtonBlock(buttons));
		SimpleUI.Box(message, id);

		document.getElementById('simpleEdit').focus();
	 },

	 EditBoxWithHints: function (caption, text, hintsCaption, hintsText, buttons, id) {
		var message = document.createElement('div');

		message.appendChild(document.createTextNode(caption));

		var area = document.createElement('textarea');
		area.setAttribute('cols', '15');
		area.setAttribute('rows', '10');
		area.id = 'simpleEdit';
		area.value = text;
		message.appendChild(area);

		message.appendChild(document.createTextNode(hintsCaption));

		var area2 = document.createElement('textarea');
		area2.setAttribute('readOnly', true);
		area2.setAttribute('cols', '15');
		area2.setAttribute('rows', '10');
		area2.value = hintsText;
		message.appendChild(area2);

		message.appendChild(SimpleUI.ButtonBlock(buttons));

		SimpleUI.Box(message, id);
		document.getElementById('simpleEdit').focus();
	 },

	 InputBox: function (inputs, buttons, id) {
		var message = document.createElement('div');

		for (var n = 0 ; n < inputs.length ; ++n) {
			var block = document.createElement('div');
			block.appendChild(document.createTextNode(inputs[n][0]));
			block.appendChild(document.createElement('br'));
			var inputelem = document.createElement('input');
			inputelem.id = inputs[n][1];
			inputelem.onblur = SimpleUI.OnBlur;
			inputelem.onfocus = SimpleUI.OnFocus;
			inputelem.setAttribute('type', 'text');
			inputelem.setAttribute('size', inputs[n][2]);
			inputelem.setAttribute('maxlength', inputs[n][3]);
			inputelem.setAttribute('name', inputs[n][1]);
			inputelem.value = inputs[n][4];
			block.appendChild(inputelem);
			message.appendChild(block);
		}

		message.appendChild(SimpleUI.ButtonBlock(buttons));
		SimpleUI.Box(message, id);

		document.getElementById(inputs[0][1]).focus();
	 },

	 AlertBox: function (caption, buttons, id) {
		var message = document.createElement('div');

		message.appendChild(document.createTextNode(caption));

		message.appendChild(SimpleUI.ButtonBlock(buttons));
		SimpleUI.Box(message, id);
	 },

	 Box: function (content, id) {
		var modernbody = document.getElementById('mw_content');
		if (modernbody && !DOM.get('mw-js-message')) {
			var ndiv = document.createElement('div');
			ndiv.id = 'mw-js-message';
			modernbody.insertBefore(ndiv, modernbody.firstChild);
		}
		if (typeof content === 'object') {
			if (SimpleUI.Msg('<div id=\'' + id + '-container\'></div>', id)) {
				document.getElementById(id + '-container').appendChild(content);
				return true;
			} else {
				return false;
			}
		} else {
			return SimpleUI.Msg(content, id);
		}
	 },

    // PerfektesChaos  2012-09-06  >>>>
	 Msg: function (content, id) {
      // Reproduziert das Verhalten von wikibits::jsMsg bis Sommer 2012
      var $msg;
      if ( content ) {
         mw.util.jsMessage( content, id );
         $msg  =  jQuery( "#mw-js-message" );
         if ( $msg.length ) {
            $msg.trigger( "mouseenter" );
            $msg.off();
            $msg.attr( "style",  "position: relative;" +
                                 "left:     1em;"      +
                                 "right:    auto;"     +
                                 "top:      auto;"     +
                                 "width:    auto;" );
         }
      } else {
         mw.util.jsMessage( null, id );
      }
	 },
    // PerfektesChaos  2012-09-06  <<<<

	 ButtonBlock: function(buttons) {
		var block = document.createElement('div');
		block.id = SimpleUI.ButtonsBoxName;
		for (var n = 0 ; n < buttons.length ; ++n) {
			var proceedbutton = document.createElement('a');
			if (typeof buttons[n][1] !== 'function') {
				proceedbutton.setAttribute('onclick', buttons[n][1]);
			}
			proceedbutton.innerHTML = buttons[n][0];
			proceedbutton.style.cursor = 'pointer';
			proceedbutton.style.marginLeft = '1em';
			if (typeof buttons[n][1] === 'function') {
				proceedbutton.onclick = buttons[n][1];
			}
			proceedbutton.onblur = SimpleUI.OnBlur;
			proceedbutton.onfocus = SimpleUI.OnFocus;
			block.appendChild(proceedbutton);
		}
		return block;
	 },

	 OnFocus: function() {
		document.body.onkeypress = function (event) {
			if ( (event.keyCode ? event.keyCode : event.which ? event.which : event.charCode) === 13 ) {
				var b = DOM.fetch(DOM.get(SimpleUI.ButtonsBoxName),'a', null, 0);
				if (b !== null) {
					if (typeof b.onclick === 'function') {
						b.onclick.call(this);
					} else {
						eval(b.onclick);
					}
				}
			}
		};
		var b = DOM.fetch(DOM.get(SimpleUI.ButtonsBoxName),'a', null, 0);
		if (b !== null) {
			b.style.fontWeight = 'bold';
		}
	 },

	 OnBlur: function() {
		document.body.onkeypress = function () {};
		var b = DOM.fetch(DOM.get(SimpleUI.ButtonsBoxName),'a', null, 0);
		if (b !== null) {
			b.style.fontWeight = '';
		}
	 }
};

function NamespaceObj(canon, loc) {
	this.canonical = canon;
	this.local = loc;
}

NamespaceObj.prototype.createMatch = function() {
	return '(?:' + WikiLinker.createInsensStringMatch(this.canonical) + '|' + WikiLinker.createInsensStringMatch(this.local) + ')';
};

var WikiLinker = {
	LinkSpace: '[ _\\t]*',

	createLinkRegExp: function (target, t_ns, included) {
		var bracket = [];
		if (included) {
		    bracket = ['{'.escapeRE(), '}'.escapeRE()];
		} else {
		    bracket = ['['.escapeRE(), ']'.escapeRE()];
		}
		var brackets = [ bracket[0] + bracket[0], bracket[1] + bracket[1] ];

		var ns = WikiLinker.Namespaces[t_ns.toString()];
		if (ns) {
		    var nsmatch = ns.createMatch() + WikiLinker.LinkSpace + ':';
		    if ((included && t_ns === 10) || (!included && t_ns === 0)) {
			nsmatch = '(?:' + nsmatch + ')?';
		    }
		}
		var text = '[^' + bracket[1] + ']*';
		if ((included && t_ns === 10) || (!included && t_ns === 6)) {
		    text = text + '(?:' + brackets[0] + text + brackets[1] + text + ')*';
		}
		return new RegExp (
			brackets[0] + WikiLinker.LinkSpace +
			nsmatch + WikiLinker.LinkSpace +
			WikiLinker.createFirstCharInsensStringMatch(target) + WikiLinker.LinkSpace +
			'(\\|' + text + ')?' + WikiLinker.LinkSpace +
			brackets[1]
		);
	},

	createInsensStringMatch: function (str) {
		var ret_val = '';
		for ( var n = 0 ; n < str.length ; ++n ) {
		    ret_val +=  WikiLinker.createInsensCharMatch(str[n]);
		}
		return ret_val;
	},

	createFirstCharInsensStringMatch: function (str) {
		if (str === '') {
		    return '';
		}
		var ret_val = WikiLinker.createInsensCharMatch(str[0]);
		if (str.length > 1) {
		    ret_val += WikiLinker.createNormalStringMatch(str.slice(1));
		}
		return ret_val;
	},

	createInsensCharMatch: function (chr) {
		return '[' + chr.toUpperCase().escapeRE() + chr.toLowerCase().escapeRE() + ']';
	},

	createNormalStringMatch: function (str) {
		return str.escapeRE().replace(/[ _]/g, '[ _]');
	},

	Namespaces: {
		0: new NamespaceObj('', ''),
		1: new NamespaceObj('Talk', 'Diskussion'),
		2: new NamespaceObj('User', 'Benutzer'),
		3: new NamespaceObj('User talk', 'Benutzer Diskussion'),
		4: new NamespaceObj('Wikipedia', 'Wikipedia'),
		5: new NamespaceObj('Wikipedia talk', 'Wikipedia Diskussion'),
		6: new NamespaceObj('File', 'Datei'),
		7: new NamespaceObj('File talk', 'Datei Diskussion'),
		8: new NamespaceObj('MediaWiki', 'MediaWiki'),
		9: new NamespaceObj('MediaWiki talk', 'MediaWiki Diskussion'),
		10: new NamespaceObj('Template', 'Vorlage'),
		11: new NamespaceObj('Template talk', 'Vorlage Diskussion'),
		12: new NamespaceObj('Help', 'Hilfe'),
		13: new NamespaceObj('Help talk', 'Hilfe Diskussion'),
		14: new NamespaceObj('Category', 'Kategorie'),
		15: new NamespaceObj('Category talk', 'Kategorie Diskussion'),
		100: new NamespaceObj('Portal', 'Portal'),
		101: new NamespaceObj('Portal talk', 'Portal Diskussion')
	}
};

 function nextItem (category, namespace) {
	var cmstart = UrlParameters.cmstart;
	if (!cmstart) {
		var cookie = Cookie.get('cmstart');
		if (cookie) {
			cookie = cookie.match(/(.+)\/\/(.+)/);
		}
		if (cookie && cookie[1] === category) {
			cmstart = cookie[2];
		}
	}

	var url = '/w/api.php?action=query&list=categorymembers&cmtitle=Category:' + category + '&cmsort=timestamp&cmdir=asc&cmlimit=1&cmprop=title&format=json&callback=gotNextItem';
	if (cmstart) {
		url += '&cmstart=' + cmstart;
	}
	if (typeof namespace !== 'undefined') {
		url += '&cmnamespace=' + namespace;
	}
	Cookie.set('cmstart', category, Cookie.timeout(24 * 60 * 60 * 100));
	mw.loader.load(url);
 }

 function gotNextItem(obj) {
	if(!obj.query || !obj.query.categorymembers || !obj.query.categorymembers[0]) {
		return;
	}
	var url = '/w/index.php?title=' + encodeURIComponent(obj.query.categorymembers[0].title);
	if (obj['query-continue'] && obj['query-continue'].categorymembers) {
		url += '&cmstart=' + encodeURIComponent(obj['query-continue'].categorymembers.cmstart);
	}
	Cookie.set('cmstart', Cookie.get('cmstart') + '//' + obj['query-continue'].categorymembers.cmstart, Cookie.timeout(24 * 60 * 60 * 100));
	location.href = url;
 }

if(typeof Ajax === 'undefined') {
	Ajax = function () {
		mw.log.error('Dependency Ajax was not correctly loaded.');
	};
}
 /** simple ajax helper */
var SimpleAjax = {
	/** GET from an URL, calls the okFunc if successful */
	get: function(url, params, okFunc) {
		Ajax.call({url: url, urlParams: params, successFunc: function myOk(client) { client.openedURL = url; okFunc(client); } });
	},

	/** POST to an URL, calls the okFunc if successful */
	post: function(url, params, okFunc) {
		Ajax.call({method: 'POST', url: url, bodyParams: params, successFunc: function myOk(client) { client.openedURL = url; okFunc(client); } });
	},

	/** parse XML and XHTML content */
	parseXML: function(text) {
		return XMLUtil.parseXML(text);
	},

	getResponseXML: function (req) {
		if (!req.responseXML) {
			try {
				var parsed = SimpleAjax.parseXML(req.responseText);
				return parsed;
			} catch (e) {
				prompt("Kaputtes XML übergeben, bitte sag Codeispoetry Bescheid, wo genau das passierte, damit er die MediaWiki-Entwickler nerven kann!", req.openedURL);
				return req.responseText;
			}
		}
		else {
			return req.responseXML;
		}
	}
};

 function getBody (parent) {
	if (typeof parent === 'undefined') {
		parent = document;
	}

	var ids = ['bodyContent', 'mw_contentholder', 'article'];
	for (var n in ids) {
		var obj = parent.getElementById(ids[n]);
		if (obj !== null) {
			return obj;
		}
	}
	return null;
 }

 function getPageContent (parent) {
	if (typeof parent === 'undefined') {
		parent = document;
	}

	var content = document.createElement('div');
	if (typeof parent.getElementById === 'function') {
		var cont_elem = parent.getElementById('jump-to-nav').nextSibling;
		var continueElem = null;
		while (cont_elem !== null && cont_elem.className !== 'printfooter') {
			continueElem = cont_elem.nextSibling;
			content.appendChild(cont_elem);
			cont_elem = continueElem;
		}
	} else {
		content.innerHTML = parent.match(/<!-- start content -->([\s\S]+)<!-- (end content|NewPP limit report)/m)[1];
	}
	return content;
 }

 function displayBoxPage (title) {
	SimpleAjax.get(title, '', function(req) {
		var content = getPageContent(SimpleAjax.getResponseXML(req));
		if (!(content && SimpleUI.Box(content, 'display'))) { // Box bauen, sonst
			getBody(document).parentNode.replaceChild(getBody(content), getBody(document));
		}
	});
 }

 function newActionBar (id) {
	var bar = document.createElement('DIV');
	bar.style.textAlign = 'center';
	bar.style.width = '100%';
	bar.id = id;
	bar.addLink = function (caption, title, href, onclick) {
		var link = document.createElement('a');
		if (href) {
			link.href = href;
		}
		if (typeof onclick !== 'undefined') {
			if (typeof onclick  !== 'function') {
				link.setAttribute('onclick', onclick);
			} else {
				link.onclick = onclick;
			}
			link.style.cursor = 'pointer';
		}
		link.innerHTML = caption;
		link.title = title;
		this.appendChild(link);
		this.appendChild(document.createTextNode(' '));
	};
	return bar;
 }

 /*
  * Stringlänge überprüfen für Zusammenfassungszeile
  */

 function EditCommentLength(str) {
	return (199 - str.length);
 }

 if (typeof UrlParameters === 'undefined') {
		var readparams = function () {
			var asReadInUrlParameter;

			// Get URL parameters
			var asReadInUrlParameters = location.search.substring(1, location.search.length).split("&");
			for (var i =0; i<asReadInUrlParameters.length; i++) {
				asReadInUrlParameter = asReadInUrlParameters[i].split("=");
				UrlParameters[decodeURIComponent(asReadInUrlParameter[0])] = decodeURIComponent(asReadInUrlParameter[1]);
			}
		};

		// get URL parameters (used for page type variables)
		var UrlParameters = [];
		readparams();
 }

function copySlotsRecursively (target, source) {
	if (typeof source === 'undefined') {
		return target;
	}
	if (typeof source === 'object' && source.slotCopy !== false && typeof target !== 'undefined' ) {
		for (var key in source) {
			if (source.hasOwnProperty(key)) { /* hat source wirklich etwas unter diesem key? */
				if (typeof source[key] === 'object' && source[key].slotCopy !== false && typeof target[key] !== 'undefined') { /* sieht source ein slotcopy vor? */
					copySlotsRecursively (target[key], source[key]); /* dann slotcopy */
				} else {
					target[key] = source[key]; /* sonst einfach rüber */
				}
			}
		}
	} else {
		target = source; /* sonst einfach rüber */
	}
	return target;
}

function Join(finalfunc, to_go) {
	this.target = finalfunc;
	this.total = to_go;
	this.allStarted = false;
	this.done = 0;
}

Join.prototype = {
	check: function () {
		this.done++;
		this.checkIfDone();
	},

	finalize: function () {
		this.allStarted = true;
		this.checkIfDone();
	},

	checkIfDone: function () {
		if (this.done === this.total && this.allStarted === true) {
			this.target();
		}
	}
};

function TaskManager(n_tasks, back) {
	this.tasks = n_tasks;
	this.back = back;
	this.buildSelection();
}

TaskManager.prototype = {

	// baut eine liste aller tasks, aus denen der benutzer auswählen kann
	buildSelection: function() {
		var checks = [];
		for (var n = 0 ; n < this.tasks.length ; ++n) {
			checks.push([this.tasks[n].name, this.tasks[n].checkbox, this.tasks[n].params]);
		}

		SimpleUI.CheckboxBox('Durchzuführende Aktionen auswählen:', 'actions', checks,
			[
				['Weiter', this.startTasks.bind(this)],
				['Zurück', this.back]
			],
			'duep');
	},

	startTasks: function() {
		for (var n = 0 ; n < this.tasks.length ; ++n) {
			// ob der job durchlaufen soll wird gleich in seine eigenschaften reingeschrieben.
			// dadurch ist die auswahl beim zurückgehen noch genau wie sie getätigt wurde
			this.tasks[n].params.checked = DOM.get(this.tasks[n].name).checked;
		}
		this.currentTask = -1;
		this.nextTask();
	},

	nextTask: function () {
		this.otherTask(1);
	},

	prevTask: function () {
		this.otherTask(-1);
	},

	otherTask: function(diff) {
		this.currentTask += diff;
		if (this.currentTask < 0) {
			// wir waren grad schon beim ersten job, daher muss jetzt wieder die jobauswahl dargestellt werden
			this.buildSelection();
		} else if (this.currentTask < this.tasks.length) {
			// check, ob der job überhaupt aktiv ist. dann seine phase1, sonst gleich zum nächsten
			if (this.tasks[this.currentTask].params.checked === true) {
				this.tasks[this.currentTask].phase1(this.prevTask.bind(this), this.nextTask.bind(this));
			} else {
				this.otherTask(diff);
			}
		} else {
			// die phase1 aller jobs ist durch, jetzt alle phase2 durchführen
			SimpleUI.Box('Aufgaben werden durchgeführt &hellip;', 'duep');
			var taskjoin = new Join(function() {SimpleUI.Box('Alle Aufgaben abgeschlossen.', 'duep');}, 0);
			for (var n = 0 ; n < this.tasks.length ; ++n) {
				if (this.tasks[n].params.checked === true) {
					taskjoin.total += this.tasks[n].phase2(taskjoin.check.bind(taskjoin));
				}
			}
			taskjoin.finalize();
		}
	}
};

var SimpleWiki = {
	getTalkpage: function () {
		if (DOM.get('ca-talk').className != 'new') {
			if (mw.config.get('wgNamespaceNumber') > 0) {
				return mw.config.get('wgPageName').replace(/^([^:]+):$/, "$1 Diskussion:");
			} else {
				return 'Diskussion:' + mw.config.get('wgPageName');
			}
		} else {
			return false;
		}
	}
}