Jump to content

User:Theki/utilbox.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
const UtilBox = {};
UtilBox.VERSION = "1.5.1";
UtilBox._options = [
	{
		icon: "update",
		name: "Recent changes",
		link: "Special:RecentChanges"
	},
	{
		icon: "update",
		name: "Real-time recent changes",
		link: "Special:BlankPage/RTRC"
	},
	{
		icon: "live_help",
		name: "Help desk",
		link: "Wikipedia:Help_desk"
	},
	{
		icon: "report",
		name: "AIV",
		link: "Wikipedia:Administrator_intervention_against_vandalism"
	},
	{
		icon: "person",
		name: "Userpage",
		link: "User:Theki"
	},
	{
		icon: "edit_note",
		name: "Sandbox",
		link: "User:Theki/sandbox"
	},
	{
		icon: "code",
		name: "UtilBox v" + UtilBox.VERSION,
		link: "User:Theki/utilbox.js",
		id:   "utilbox-footer"
	}
];

UtilBox.Option = function(icon, name, link, id) {
	// Create a link in the box with the specified icon (uses material icons).
	const el = document.createElement("a");
	el.classList.add("link");
	el.innerHTML = "<span class='material-icons'>"+icon+"</span><span class='utilbox-linkcon'>"+name+"</span>";
	if (link) el.href = link;
	if (id) el.id = id;
	return el;
};
//===============================//
UtilBox.init = function() {
	var fgCol = "";
	var bgCol = "";
	var bgColName = "";
	// set up the root element
	const el = document.createElement("div");
	el.id = "utilbox";
	const linkContainer = document.createElement("div");
	// make the close button
	const closeBtn = document.createElement("a");
	closeBtn.innerHTML = "close";
	closeBtn.id = "utilbox-close";
	closeBtn.onclick = function() {
		const c = closeBtn.innerHTML === "close";
		linkContainer.classList.toggle("hide");
		closeBtn.innerHTML = c ? "open" : "close";
	};
	el.appendChild(closeBtn);
	el.appendChild(linkContainer);
	// setup colour
	bgCol = Array(6).fill("").map(function(e){return Math.floor(Math.random() * 16).toString(16)}).join("");
	fetch("https://www.thecolorapi.com/id?hex="+bgCol).then(function(r) {
		r.json().then(function(j) {
			bgColName = j.name.value;
			fgCol = j.contrast.value;
			linkContainer.style.color = fgCol;
			linkContainer.style.backgroundColor = "#" + bgCol;
			document.querySelector("#utilbox-footer > .utilbox-linkcon").innerHTML = "UtilBox v"+UtilBox.VERSION+" ("+bgColName+")";
		});
	}).catch(function(e) {alert("Error occured while obtaining UtilBox colours, resorting to default. Error details:\n\n"+e)});
	// add all of the options
	UtilBox._options.forEach(function(option) {
		linkContainer.appendChild(UtilBox.Option(option.icon, option.name, option.link ? "https://en.wikipedia.org/w/index.php?title=" + option.link : option.absolute_link, option.id));
	});
	document.body.appendChild(el);
};

UtilBox.init();