User:JJPMaster/talkback.js

// <nowiki>
$(() => {
	var porty;
	$("#bodyContent").append(`
	<div id="tbDialog">
		Which talkback template would you like to add?
		<select name="tbName" id="tbName">
			<option>Select the template</option>
			<option id="Talkback">Talkback</option>
			<option id="You've got mail">You've got mail</option>
	    </select><br />
	    <button type="button" id="tbUser">Add talkback</button></div>
	`);
	(async () => {
		if (await waitForPreferences()) {
			for (var [i, j] of Object.entries(Luna.myPreferences.tb)) {
			    $("#tbName").append(`<option id="${i}">${j}</option>`);
			}
		}
		else {
		    console.error("Luna: Preferences never fully loaded.");
		}
	})();
	$("#tbDialog").hide();
	if (mw.config.get("wgRelevantUserName") !== null) {
		porty = mw.util.addPortletLink('luna-actions', '#', 'Talkback', 'luna-tb', 'Add a talkback template');
	}
	else return;
	$(porty).click(() => $("#tbDialog").dialog({ title: "Add talkback"} ));
	$("#tbUser").click(function() {
		var mySelect = document.getElementById("tbName");
		var critValue = mySelect.options[tbName.selectedIndex].id;
		
		if (!critValue) alert("You must select a template.");
		else {
			if (critValue == "Talkback") {
				var talkPage = prompt("What is the name of the page with the new messages? Note: If you don't include the namespace, it will assume that the page is a user talk page.");
				if (!talkPage) return;
				var section = prompt("What is the section with the new messages?");
				var params = {
					action: 'edit',
					appendtext: `\n== Talkback ==\n{{${critValue}|${talkPage}|${!!section ? section : ``}}} ~~~~\n`,
					title: `User_talk:${mw.config.get("wgRelevantUserName")}`,
					summary: `Adding {{${critValue}}}`,
					tags: "Luna",
					format: 'json'
				},
				api = new mw.Api();
			
				api.postWithToken( 'csrf', params ).done( function ( data ) {
					console.log( data );
				} );
			}
			else {
				params = {
					action: 'edit',
					appendtext: `\n== You've got mail! ==\n{{${critValue}|sig=~~~~}}\n`,
					title: `User_talk:${mw.config.get("wgRelevantUserName")}`,
					summary: `Adding {{${critValue}}}`,
					tags: "Luna",
					format: 'json'
				},
				api = new mw.Api();
			
				api.postWithToken( 'csrf', params ).done( function ( data ) {
					console.log( data );
				} );
			}
			mw.notify("Luna:\nThe talkback has been added. Redirecting to the user's talk page...");
			setTimeout(() => {
				if (mw.config.get("wgPageName") == `User_talk:${mw.config.get("wgRelevantUserName")}`) window.location.reload();
				else window.location.href = window.location.href.replace(mw.config.get("wgPageName"), `User_talk:${mw.config.get("wgRelevantUserName")}`);
			}, 2000);
		}
	});
});
// </nowiki>