User:Nikki/LowercaseLabels.js

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
/**
 * This script adds a button when editing labels to change the text to lowercase.
 * 
 * To use it, add the following to your common.js:
 * mw.loader.load("//www.wikidata.org/w/index.php?title=User:Nikki/LowercaseLabels.js&action=raw&ctype=text/javascript");
 * 
 * @license CC0-1.0
 */
/* jshint esnext: false, esversion: 8 */

(async function () {
	"use strict";

	await mw.loader.using(["jquery.i18n", "mediawiki.api"]);
	let translations = new mw.Title("User:Nikki/translations.json").getUrl() +
		"?action=raw&ctype=application/json";
	await $.i18n().load(translations);

	mw.util.addCSS(`
		.wikibase-entitytermsforlanguageview:not(.wb-edit) .n-lowercase-labels {
			display: none;
		}
		.wb-edit .wikibase-labelview-container {
			margin-right: 3em;
		}
		.n-lowercase-labels {
			cursor: pointer;
			float: right;
		}
		.n-lowercase-labels img {
			height: 18px;
			width: 18px;
			opacity: 0.5;
		}
	`);

	var qid = mw.config.get("wbEntityId");
	if (!qid)
		return;

	function add_buttons() {
		for (let e of document.querySelectorAll(".wikibase-entitytermsforlanguageview-label .wikibase-labelview")) {
			if (e.querySelector(".n-lowercase-labels"))
				continue;

			const img = document.createElement("img");
			img.src = "https://upload.wikimedia.org/wikipedia/commons/e/ee/Icon_-_To_lower_case.svg";
			img.alt = $.i18n("lowercase-alt");
	
			const button = document.createElement("button");
			button.type = "button";
			button.title = $.i18n("lowercase-title");
			button.appendChild(img);
			button.onclick = function () {
				const tx = this.parentNode.parentNode.querySelector(".wikibase-labelview-input");
				tx.value = tx.value.toLowerCase();
				tx.focus();
				tx.dispatchEvent(new Event("input"));
			};
	
			const span = document.createElement("span");
			span.className = "n-lowercase-labels";
			span.appendChild(button);
	
			e.insertAdjacentElement("afterbegin", span);
		}
	}

	mw.hook("termbox-language-added").add(add_buttons);

	mw.hook("wikibase.entityPage.entityView.rendered").add(function () {
		const menu = mw.util.addPortletLink("p-cactions", "#", "Lowercase labels", "n-lowercase-labels", "Add the buttons for lowercasing labels if they are not already there");
		menu.onclick = add_buttons;
		add_buttons();
		$(".wikibase-entitytermsforlanguagelistview-more a").click(function () { add_buttons(); });
	});
})();