User:Midleading/common.js

From Wikimedia Commons, the free media repository
Jump to navigation Jump to search
Note: After saving, you have to bypass your browser's cache to see the changes. Internet Explorer: press Ctrl-F5, Mozilla: hold down Shift while clicking Reload (or press Ctrl-Shift-R), Opera/Konqueror: press F5, Safari: hold down Shift + Alt while clicking Reload, Chrome: hold down Shift while clicking Reload.
// Wikidata Infobox toggle, add "X" button to Wikidata Infobox, add "+Wikidata Infobox" menu item when Wikidata Infobox doesn't exist.
(function($, mw) {
	'use strict';
	mw.loader.using([
		'mediawiki.util'
	]).then(function(require) {
		var button;
		if(mw.config.get("wgNamespaceNumber") == 14 && mw.config.get("wgAction") == "view"){
			var caption=$("#wdinfobox");
			if(caption.length){
				// Add "X" button
				button=$("<button style='float:right;'>×</button>");
				button.click(function(e){
					new mw.Api().get({
						"action": "parse",
						"pageid": mw.config.get("wgArticleId"),
						"prop": "wikitext",
						"formatversion": 2
					}).then(function(text){
						return new mw.Api().postWithEditToken({
							"action": "edit",
							"baserevid":mw.config.get("wgRevisionId"),
							"text": text.parse.wikitext.replace("{{Wikidata Infobox}}\n", ""),
							"pageid": mw.config.get("wgArticleId"),
							"summary": "-Wikidata Infobox",
							"minor": 1,
							"bot": 1,
							"assert": "user",
							"nocreate": 1
						});
					}).then(function(json){
						//alert(JSON.stringify(json));
						window.location.reload();
					}).catch(function(){
						alert("ERROR!");
					});
				});
				caption.before(button);
			}else{
				// Add "+Wikidata Infobox" menu item
				button=mw.util.addPortletLink("p-tb","#","+Wikidata Infobox");
				$(button).click(function(e){
					new mw.Api().postWithEditToken({
						"action": "edit",
						"baserevid":mw.config.get("wgRevisionId"),
						"prependtext": "{{Wikidata Infobox}}\n",
						"pageid": mw.config.get("wgArticleId"),
						"summary": "+Wikidata Infobox",
						"minor": 1,
						"bot": 1,
						"assert": "user",
						"nocreate": 1
					}).then(function(json){
						//alert(JSON.stringify(json));
						window.location.reload();
					}).catch(function(){
						alert("ERROR!");
					});
				});
			}
		}
	});
	// Prefetch
	mw.loader.load(['mediawiki.user']);
}(jQuery, mediaWiki));