User:Erutuon/scripts/sidebar.js

From Wiktionary, the free dictionary
Jump to navigation Jump to search

Note – after saving, you may have to bypass your browser’s cache to see the changes.

  • Mozilla / Firefox / Safari: hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (Command-R on a Macintosh);
  • Konqueror and Chrome: click Reload or press F5;
  • Opera: clear the cache in Tools → Preferences;
  • Internet Explorer: hold Ctrl while clicking Refresh, or press Ctrl-F5.

/* jshint eqeqeq: true, esversion: 5, undef: true, unused: true */
/* globals $, mw */

(function sidebarIIFE() {
"use strict";

function modifySidebar() {
	var pageName = mw.config.get("wgPageName");
	var canonicalNamespace = mw.config.get("wgCanonicalNamespace");
	
	var prefix = {
		"p-tb": "t", "p-navigation": "n",
	};
	
	function portlet(toolbarId, url, text, tooltip) {
		return mw.util.addPortletLink(toolbarId, url, text,
			(prefix[toolbarId] ? prefix[toolbarId] + "-" : "")
				+ text.toLowerCase().replace(/\W+/g, ""),
			tooltip);
	}
	
	portlet("p-tb",
		mw.util.getUrl("Special:CategoryTree",
			canonicalNamespace === "Category"
				? { target: pageName.replace(/_/g, " ") }
				: null),
		"CategoryTree", "See category contents as a tree structure");
	
	// Show "pages linked from" if namespace is "Category", else "pages linking to".
	portlet("p-navigation",
		mw.util.getUrl("Special:RecentChangesLinked", {
			target: pageName, showlinkedto: Number(canonicalNamespace !== "Category"),
		}),
		"Related changes", "A list of changes on pages related to this one");
	
	if (canonicalNamespace !== "Special") {
		portlet("p-navigation", mw.util.getUrl(
				"Special:PrefixIndex/" + pageName + "/", { stripprefix: 1 }),
			"Subpages", "List of subpages of this page");
		
		var compareWith = portlet("p-tb", "", "Compare with",
			"Compare the wikitext of this page with another");
		
		var titleInputWidget;
		$(compareWith).click(function () {
			mw.loader.using("mediawiki.widgets", function () {
				if (!titleInputWidget) {
					titleInputWidget = new mw.widgets.TitleInputWidget();
					window.titleInputWidget = titleInputWidget;
					
					var enterKey = 0x0D;
					titleInputWidget.$element.keydown(function (event) {
						if (event.which !== enterKey)
							return;
						
						var input = titleInputWidget.value;
						if (input === "" || input === pageName)
							return;
						
						location.href = mw.util.getUrl(
							"Special:ComparePages",
							{ page1: pageName, page2: input });
						
						return false;
					});
					
					$(compareWith).append(titleInputWidget.$element);
				}
				
				titleInputWidget.focus();
			});
			
			return false;
		});
		
		// new mw.Api().get({ action: 'opensearch', search: 'Mediawiki:gadget-' }).then((data) => console.log(data))
	}
}

mw.loader.using("mediawiki.util", function () {
	$(modifySidebar);
});

})();