Jump to content

User:Andy M. Wang/closeRM.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.
// <syntaxhighlight lang="javascript">
// closeRM by [[User:Andy M. Wang]]
// 1.0.2016.1008b
// based on [[User:Armbrust/closemrv.js]]

$(document).ready(function() {
	"use strict";
	// Add only when editing section
	// Assumes Requested move has a level 2 header, ends at end of section
	if ((document.title.indexOf("Editing ") === -1)
			|| (document.title.indexOf("(section)") === -1)) {
		return;
	}
	
	function rmClick(e) {
		e.preventDefault();
		var closeStr = prompt("Closing statement for requested move:");
		if (closeStr === null || closeStr === '') {
			alert("Invalid closing statement. Aborted.");
			return;
		}

		var editform = document.editform, t = editform.wpTextbox1;
		var lines = t.value.split('\n');

		var inReqMoveTemplate = false;
		var foundReqMoveTemplate = false;
		var acc = '';
		for (var idx in lines) {
			if (lines[idx].toLowerCase().includes("{{requested move/dated")) {
				acc += '{{subst:RM top|' + closeStr + "}}";
				inReqMoveTemplate = !lines[idx].includes("}}");
				foundReqMoveTemplate = true;
			} else if (foundReqMoveTemplate && inReqMoveTemplate) {
				inReqMoveTemplate = !lines[idx].includes("}}");
			} else {
				acc += lines[idx] + '\n';
			}
		}

		if (!foundReqMoveTemplate) {
			alert("{{requested move/dated}} NOT FOUND. Wikitext not updated\n\n"
				+ "Possible reasons:\n"
				+ "1. This edited section is not a requested move discussion.\n"
				+ "2. The discussion was answered by another editor earlier.");
			return;
		}

		t.value = acc + "{{subst:" + "RM bottom" + "}}";
		editform.wpSummary.value += "Closing RM: " + closeStr.replace(
				/\{\{subst\:rmnac\}\}|\'\'\'/gi,'').substring(0, 140)
			+ (closeStr.length > 140 ? ' ...' : '')
			+ ' ([[User:Andy M. Wang/closeRM|closeRM]])';
	}
	
	mw.loader.using( 'mediawiki.util' ).then( function(){
		var portletLink = mw.util.addPortletLink("p-cactions", "#", "RM close",
			"ca-rmclose", "Close a requested move discussion section");
		$( portletLink ).click( rmClick );
	} );

});
// </syntaxhighlight>