Jump to content

User:Writ Keeper/Scripts/autoCloser.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>
if (mw.config.get("wgCanonicalNamespace") == "Project" || mw.config.get("wgCanonicalNamespace") == "Project_talk" || mw.config.get("wgPageName") == "User:Writ_Keeper/sandbox")
{

	function autoClose()
	{
		editLink = $(this).siblings("a.sectionEditLink")[0];
		if (typeof editLink !== "undefined")
		{
			var regexResults = /title=([^&]+).*&section=[\D]*(\d+)/.exec(editLink.href);
			if(regexResults === null)
			{
				return false;
			}
			var pageTitle = regexResults[1];
			var sectionIndex = regexResults[2];
			var rationale = prompt("Please enter your rationale.");
			if (rationale == null || rationale.length <= 0)
			{
				alert("You didn't enter a rationale.");
				return false;
			}

			var requestData =
			{
				action: 'raw',
				title: pageTitle,
				section: sectionIndex,
			};
			$.post("/w/index.php", requestData, function (responseText)
			{
				var sectionRegex = /(==+)([^=]+)\1/.exec(responseText);
				var sectionTitle = sectionRegex[2];
				var newContent = sectionRegex[0] + "\n{{archive top|" + rationale + " ~~~~}}\n" + responseText.substr(sectionRegex[0].length) + "\n{{archive bottom}}";
				var replyData =
				{
					format: 'json',
					action: 'edit',
					notminor: true,
					title: pageTitle,
					text: newContent,
					section: sectionIndex,
					summary: "Closing section: " + sectionTitle,
					token: mw.user.tokens.get('csrfToken')
				};
				$.post("/w/api.php", replyData)
				.done(function ()
				{
					alert("Section closed.");
					window.location.assign("/w/index.php?title=" + mw.config.get("wgPageName") + "#" + sectionTitle);
				})
				.fail(function ()
				{
					alert("Section close failed.");
				});
			});
		}
		return false;
	}

	function autoCloserSetup()
	{
		var sectionHeaders = $(".mw-editsection");
		sectionHeaders.each(function (index, element)
		{
			var editLink = $(element).children("a")[0];
			if (typeof editLink !== "undefined" && /&section=[\D]*(\d+)/.exec(editLink.href))
			{
				$(editLink).addClass("sectionEditLink");
				var autoCloser = document.createElement("a");
				$(autoCloser).addClass("autoCloserButton");
				autoCloser.innerHTML = "Close section";
				var editSectionContents = $(element).html();
				element.innerHTML = "[ ";
				element.appendChild(autoCloser);
				element.innerHTML = element.innerHTML + " ] " + editSectionContents;
			}
		}
		);
		$(".autoCloserButton").click(autoClose);

	}

	$(document).ready(autoCloserSetup());
}
//</nowiki>