User:Writ Keeper/Scripts/teahouseSectionMover.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.
//<nowiki>

//We only need this to work on the Teahouse page, and only when we're just looking, rather than editing or looking at the history or something
if(mw.config.get("wgPageName") == "Wikipedia:Teahouse/Questions" && mw.config.get("wgAction") == "view")
{
	//This function, called from the onClick event handler on the button, actually moves the section to the top
	function moveSection()
	{
		//TODO: API call to retrieve raw page data, fancy regex to retrieve section content from raw page data, figure out how to strip it (or just make another API 
		//call), another fancy regex to find the top section, figure out how to insert the section at the top, another API call to save
	}

	//This function adds the buttons to each header, next to the normal edit section link.
	function moveSectionSetup()
	{
		//Use JQuery to retrieve all of the headers in the body of the page.
		var sectionHeaders= $("#mw-content-text h2");

		//Iterate over the sections, creating and adding buttons as we go
		sectionHeaders.each(function(index, element)
		{
			var editSectionLink= $(element).children(".editsection")

			//Make sure the section has an edit link (otherwise, it's not a normal section, so we shouldn't touch it)
			if(editSectionLink.length > 0)
			{
				//retrieve DOM element from JQuery wrapper
				editSectionLink = editSectionLink[0];

				//create and initialize button
				var autoCloser = document.createElement("a");
				autoCloser.href = "#";
				$(autoCloser).attr("sectionIndex", index + offset);
				autoCloser.innerHTML = "Move to top";
				var editSectionContents = $(editSectionLink).html();

				//add button with some formatting, to make it look similar
				editSectionLink.innerHTML = "[";
				editSectionLink.appendChild(autoCloser);
				editSectionLink.innerHTML = editSectionLink.innerHTML + "] " + editSectionContents;
			}
		});

		//add click handler (do it separately to ensure that the element has been added to the page already; otherwise, it fails silently and causes no end of heartache
		$("#bodyContent [sectionIndex]").click(moveSection);
 
	}
	//Calls the button adder when the page is done loading
	$(document).ready(moveSectionSetup);
}
//</nowiki>