User:Terasail/Edit Request Tool.js: Difference between revisions

Content deleted Content added
Changes to improve section detection & var -> let
Account for Template:Sudo
 
(44 intermediate revisions by 2 users not shown)
Line 1:
//*<nowiki>
Edit Request Tool
var rOS = 9; //Reply options start
Created by: Terasail
var replyERT = {
*/
semi: ["Semi", "semi", "1/1b/", "ESp|"],
var dataERT;
extended: ["Extended", "extended", "8/8c/", "EEp|"],
var userSignauteERT = "";
template: ["Template", "template", "5/53/", "ETp|"],
var editRequestBoxes = $('.editrequest');
full: ["Full", "fully", "4/44/", "EP|"],
var editRequests = [];
"interface": ["Interface", "interface", "2/28/", "EIp|"],
for (let i = 0; i < editRequestBoxes.length; i++) {
"Close": ["", "Close", "Closed edit request"],
if (typeof(editRequestBoxes[i].attributes['data-origlevel']) != 'undefined') {
"Change": ["", "Close", "Changed level of protected edit request"],
if (editRequestBoxes[i].id == "") {
"ChangeTarget": ["", "Close", "Changed target of protected edit request"],
$(editRequestBoxes[i].children[0].children[0].children[0]).append('<div class="response-cell-ert" style="text-align:center;"></div>');
"Remove": ["", "Remove", "Removed edit request"],
} else {
"Comment (No template)": ["", "speechBubbleAdd", "Comment"],
$(editRequestBoxes[i].children[0]).append('<tr><td colspan="2" class="response-cell-ert" style="text-align:center;"></td></tr>');
"Done": ["d", "checkAll", "Done"],
}
"Partly done:": ["pd", "check", "Partly done"],
editRequests.push(editRequestBoxes[i]);
"Already Done": ["a", "clock", "Already Done"],
}
"In progress: An editor is implementing the requested edit.": ["prog", "clock", "In progress"],
}
"Note:": ["note", "ellipsis", "Note"],
"Question:": ["q", "helpNotice", "Question"],
"Not done:": ["n", "notice", "Not done"],
"Not done for now:": ["nfn", "notice", "Not done for now"],
"Not done: it's not clear what changes you want to be made. Please mention the specific changes in a 'change X to Y' format and provide a reliable source if appropriate.": ["xy", "helpNotice", "Not done - Unclear request"],
"Not done: please provide reliable sources that support the change you want to be made.": ["rs", "link", "Not done - Needs reliable sources"],
"Not done for now: please establish a consensus for this alteration before using the edit protected template.": ["c", "userGroup", "Not done - Needs consensus"],
"Not done: please make your requested changes to the template's sandbox first; see WP:TESTCASES.": ["sb", "linkExternal", "Not done - Use sandbox first"],
"Not done: this is the talk page for the page. Please make your request at the talk page for the article concerned.": ["mis", "ongoingConversation", "Not done - Misplaced"],
"Not done: this is the talk page for discussing improvements to the page. If possible, please make your request at the talk page for the article concerned.": ["tp", "ongoingConversation", "Not done - Misplaced"],
"Not done: According to the page's protection level you should be able to edit the page yourself. If you seem to be unable to, please reopen the request with further details.": ["hr", "unLock", "Not done - User can edit page"],
"Not done: The page's protection level has changed since this request was placed. You should now be able to edit the page yourself...": ["nlp", "unLock", "Not done - Page protection has changed"],
"Not done: {{Edit protected}} is usually not required for edits to the documentation or categories of templates using a documentation subpage.": ["doc", "code", "Not done"],
"Not done: requests for increases to the page protection level should be made at Wikipedia:Requests for page protection.": ["r", "editLock", "Not done - Use [[WP:RPP]]"],
"Not done: requests for decreases to the page protection level should be directed to the protecting admin or to Wikipedia:Requests for page protection.": ["ru", "editLock", "Not done - Use [[WP:RPP]]"],
"Not done: requests for recreating deleted pages protected against creation should be made at Wikipedia:Deletion review.": ["drv", "articleAdd", "Not done - Use [[WP:DRV]]"],
"Not done: page move requests should be made at Wikipedia:Requested moves.": ["m", "tableMoveColumnAfter", "Not done - Use [[WP:RM]]"],
"Not done: Please make your request for a new image to be uploaded to Files For Upload. Once the file has been properly uploaded, feel free to reactivate this request.": ["ffu", "imageLayoutFrameless", "Not done - Use [[WP:FFU]]"],
"Not done: this is not the right page to request additional user rights. You may reopen this request with the specific changes to be made and someone will add them for you.": ["p", "userAdd", "Not done - Use [[WP:RFPERM]]"],
"Partially undone: This request has been partially undone.": ["pud","undo", "Partly undone"],
"Undone: This request has been undone.": ["ud", "undo", "Undone"]
};
 
if (editRequests.length > 0) {
function postEdit(wikitext, editSummary, pageName, secIdx) {
mw.loader.using(["oojs-ui-core", "oojs-ui-widgets", "oojs-ui-windows"]).done(function() {
let api = new mw.Api();
mw.loader.load(["oojs-ui.styles.icons-interactions", "oojs-ui.styles.icons-moderation", "oojs-ui.styles.icons-user", "oojs-ui.styles.icons-content", "oojs-ui.styles.icons-editing-core", "oojs-ui.styles.icons-editing-advanced"]);
api.postWithEditToken({
loadERTool();
action: 'edit',
$.getJSON("https://en.wikipedia.org/w/index.php?title=User:Terasail/Edit_Request_Tool.json&action=raw&ctype=text/json", function (newData) {
title: pageName,
dataERT = newData;
text: wikitext,
});
section: secIdx,
ApiGetERT({
summary: editSummary
action: "parse",
}).done(function(result) {
title: mw.config.get("wgPageName"),
window.___location = "/w/index.php?title=" + pageName + "&type=revision&diff=cur&oldid=prev";
text: "~~~~",
pst: "true",
disablelimitreport: "true",
disableeditsection: "true",
preview: "true"
}).then(function(data){
userSignauteERT = data.parse.text["*"].replaceAll(/([^]+(?=<p>)<p>|<\/div>)/g, " ");
});
});
}
 
async function loadERTool() {
function execute(currentBox, replyOption, inputText, answered, boxType, targets) {
// Get page watchers, visitors and user watch status.
OO.ui.confirm("Confirm in order to reply to this edit request.").done(function(confirmed) {
let watchStatus = [];
if (confirmed) {
let watchQuery = await ApiGetERT({
//Change buttons to label box + loading bar
action: "query",
let leftOOUI = currentBox.getElementsByClassName('mbox-image')[0].getElementsByClassName('oo-ui-widget');
prop: "info",
if (leftOOUI.length > 1) {
pageids: mw.config.get("wgArticleId"),
leftOOUI[0].remove();
inprop: "watchers|visitingwatchers|watched",
}
format: "json"
leftOOUI[0].remove();
});
currentBox.children[2].remove();
let watchData = watchQuery.query.pages[mw.config.get("wgArticleId")];
let infoBox = new OO.ui.MessageWidget( {
let watched = watchData.watched;
icon: 'pageSettings',
let expiry = watchData.watchlistexpiry;
type: 'notice',
if (expiry) {
label: 'Processing request — Edit request starting, getting section data to edit.'
watched = Math.ceil((new Date(expiry).getTime() - Date.now()) / 1000 / 60 / 60 / 24) + " days";
});
}
let firstRow = currentBox.getElementsByTagName('tr')[1].children[0];
watchStatus.push(watchData.watchers || "less than 30", watchData.visitingwatchers || "<30", watched);
firstRow.style = "padding-bottom:10px";
//Increment through all edit requests & add respond button
firstRow.innerHTML = "";
for (let i = 0; i < editRequests.length; i++) {
let progressBar = new OO.ui.ProgressBarWidget( {
let responseCell = $('.response-cell-ert')[i];
progress: false
let smallButton = false;
});
if (responseCell.tagName == "DIV") {
$(firstRow).append(progressBar.$element);
smallButton = true;
$(firstRow).append(infoBox.$element);
progressBar.$element[0].style = "margin:auto";
infoBox.$element[0].style = "margin:10px auto 0px; max-width:50em";
//Find header
let header = "";
let curElement = currentBox.parentNode;
do {
curElement = curElement.previousElementSibling;
if (curElement.getElementsByClassName("mw-headline").length == 1) {
header = curElement.getElementsByClassName("mw-headline")[0].id;
}
}
while (header == "");
let pageName = mw.config.values.wgPageName;
let api = new mw.Api();
api.get( {
action: "parse",
page: pageName,
prop: "sections|wikitext|revid"
}).done(function(data) {
infoBox.setLabel("Processing request — Making changes to the edit request");
boxType = replyERT[boxType];
let editTemplate = "{{Edit " + boxType[1] + "-protected";
if (answered) { answered = "yes"; } else { answered = "no"; }
for (let c3 = 0; c3 < targets.length; c3++) {
editTemplate += "|" + targets[c3];
}
editTemplate += "|answered=" + answered;
let sections = data.parse.sections;
let wikitext = data.parse.wikitext["*"];
let newRev = data.parse.revid;
let secIndx = sections[0], endIndx = -1;
for (let j = 0; j < sections.length; j++) {
let tempSec = sections[j];
if (tempSec.anchor == header && !isNaN(Number(tempSec.index))) {
secIndx = tempSec;
endIndx = j + 1;
} else if (tempSec.number.slice(0, secIndx.number.length) == (secIndx.number)) { //Get any subsections
endIndx = j + 1;
}
}
secIndx = secIndx.index;
let headings = [...wikitext.matchAll(/==[^\n]+==/g)];
headings[headings.length] = wikitext.length;
wikitext = wikitext.slice(headings[secIndx - 1].index, headings[endIndx].index);
wikitext = wikitext.replace(/{{ *([SETFI]PER|Edit[ -]?[A-Z]+[ -]?Protected)\s*[^}}]*/i, editTemplate);
let editSummary = "/* " + header.replaceAll("_", " ") + " */ " + replyOption[2] + " ([[User:Terasail/Edit_Request_Tool|Edit Request Tool]])";
if (replyOption[1] != "Close") {
let lastMsg = wikitext.lastIndexOf("\n", wikitext.lastIndexOf("(UTC)")) + 1;
wikitext = wikitext.trim() + "\n:";
while(lastMsg == wikitext.indexOf(":", lastMsg)) {
lastMsg++;
wikitext += ":";
}
if (replyOption[0] != "") { wikitext += "{{subst:" + boxType[3] + replyOption[0] + "}} "; }
if (inputText != "") { wikitext += inputText.replaceAll(/\s*~~~~\s*/g, "") + " "; }
wikitext += "~~~~";
if (replyOption[1] == "Remove") {
wikitext = "";
editSummary = editSummary.replace(/[^]+\*\/ /, "");
}
}
infoBox.setType("success");
infoBox.setLabel("Processing '" + replyOption[2] + "' request — Saving changes to the talk page.");
if (newRev == mw.config.values.wgRevisionId) {
postEdit(wikitext, editSummary, pageName, secIndx);
} else {
OO.ui.confirm("There has been a new revision to the page, do you wish to continue?").done(function(revCon) {
if (revCon) { postEdit(wikitext, editSummary, pageName, secIndx); }
});
}
});
}
let respondButton = new OO.ui.ButtonWidget({
});
icon: "edit",
label: "Respond",
flags: "progressive",
title: "Open the response menu for this request",
invisibleLabel: smallButton,
}).on("click", function() {
loadERTResponse(editRequests[i], respondButton, watchStatus);
respondButton.setDisabled(true);
});
respondButton.$element[0].style = "margin:5px";
$(responseCell).append(respondButton.$element);
}
}
 
function loadERTResponse(editRequest, respondButton, watchStatus) {
function addButtons(currentBox) {
let boxType = currentBox.parentElementeditRequest.dataset.origlevel;
boxType = boxType.replace("full", "fully");
let replyList = Object.entries(replyERT);
$('<table style="border:1px solid #A2A9B1; border-radius:2px; padding:10px 16px 0; margin:auto; max-width:55em; width:100%; clear:both;"><tr><td><div style="font-style:italic; margin-left:1em;">There are currently ' + watchStatus[0] + ' users watching this page (' + watchStatus[1] + ' have viewed recent edits).</div><div>Quick options:</div></td></tr><tr style="display: flex; justify-content: center;"><td class="response-quick"></td></tr><tr><td>Custom response:</td></tr><tr style="text-align:center;"><td class="response-custom"></td></tr><tr style="background:#F6F6F6;"><td class="response-preview" style="display:none;"><div>Preview:</div><div></div></td></tr><tr style="display: flex; justify-content: right;"><td class="response-controls"></td></tr></table>').insertAfter(editRequest);
let mainResponse = [[replyList[rOS + 9][1], "Unclear: X-Y", "Unclear request"], [replyList[rOS + 10][1], "WP:Reliable", "Needs reliable sources"], [replyList[rOS + 11][1], "WP:Consensus", "Change needs consensus"]];
let responseBox = editRequest.nextElementSibling;
$(currentBox).append('<tr><td colspan="2"><div style="display: flex; justify-content: center;"></div></td></tr><tr style="display:none;"><td colspan=2 style="padding-bottom:10px; text-align:center"><div style="display: flex; justify-content: center;"></div></td></tr>');
let responseQuick = $(responseBox).find('.response-quick')[0];
let firstRow = currentBox.children[1].children[0].children[0];
let responseCustom = $(responseBox).find('.response-custom')[0];
let responsePreview = $(responseBox).find('.response-preview')[0];
let responseControls = $(responseBox).find('.response-controls')[0];
let protections = Object.entries(dataERT.protections);
let responses = Object.entries(dataERT.response);
let quickResponses = Object.entries(dataERT.quickResponse);
let nonResponses = dataERT.nonResponse;
//Create type change dropdown
let tcOptions = [];
let typeChange = new OO.ui.DropdownInputWidget( {
for (let i = 0; i < protections.length; i++) {
tcOptions.push({data: protections[i][0], label: protections[i][1][0]});
}
let typeChange = new OO.ui.DropdownInputWidget({
value: boxType,
options: [tcOptions
});
{data:"semi", label:"Semi protected edit request"},
typeChange.on("change", function () {
{data:"extended", label:"Extended confirmed protected edit request"},
submitB.setDisabled(false);
{data:"template", label:"Template protected edit request"},
{data:"full", label:"Fully protected edit request"},
{data:"interface", label:"Interface protected edit request"}
]
});
typeChange.$element[0].style = "text-align:left; margin:auto";
$(currentBox.children[2].children[0]responseCustom).append(typeChange.$element);
//Create target page list
let boxLinks = currentBoxeditRequest.getElementsByClassName("mbox-text")[0].getElementsByClassName("external text");
let pageLinkspageTargets = [];
if (boxLinks.length > 0) {//Open request
for (let c1 = 0; c1 < boxLinks.length; c1++) {
if (boxLinks[c1].parentElement.tagName == "LI" || boxLinks[c1].parentElement.tagName == "B") {
pageLinkspageTargets[pageLinkspageTargets.length] = boxLinks[c1].innerHTML;
}
}
} else {//Closed request
boxLinks = currentBoxeditRequest.getElementsByClassName("mbox-text")[0].getElementsByTagName("A");
for (let c2 = 1; c2 < boxLinks.length; c2++) {
pageLinkspageTargets[pageLinkspageTargets.length] = boxLinks[c2].title;
}
if (pageLinkspageTargets.length == 0) {
pageLinkspageTargets = mw.config.values.get("wgPageName").replace(/(_talk|Talk:)/, "").replaceAll("_", " ");
}
}
let targetPages = new OO.ui.TagMultiselectWidget( {
placeholder: 'Target Pages',
allowArbitrary: true,
selected: pageLinkspageTargets
});
targetPages.$element[0].style = on("text-align:left;change", margin:5pxfunction auto() 5px auto";{
submitB.setDisabled(false);
$(currentBox.children[2].children[0]).append(targetPages.$element);
});
targetPages.$element[0].style = "text-align:left; margin:5px auto";
$(responseCustom).append(targetPages.$element);
//Create dropdown menu
let dropMenu = new OO.ui.DropdownWidget( {
label: "Select reply option - Add additional text below",
menu: {items: []}
});
for (let count = 90; count < replyListresponses.length; count++) {
let newOption = new OO.ui.MenuOptionWidget({
label: replyListresponses[count][0],
icon: replyListresponses[count][1][1]
});
dropMenu.menu.addItems([newOption]);
}
responses = dataERT.response;
dropMenu.$element[0].style = "text-align:left; margin:0px";
$(currentBox.children[2].children[0]responseCustom).append(dropMenu.$element);
dropMenu.on("labelChange", function () {
submitB.setDisabled(false);
previewERT(inputText, responses[dropMenu.getLabel()], responsePreview, typeChange.value);
});
//Create input box
let inputText = new OO.ui.MultilineTextInputWidget({autosize: true, rows: 4, label: "AutomaticallyAdditional signedtext"});
inputText.$element[0].style = "margin:5px auto";
$(currentBox.children[2].children[0]responseCustom).append(inputText.$element);
inputText.on("change", function (newText) {
previewERT(inputText, responses[dropMenu.getLabel()], responsePreview, typeChange.value);
});
//Create top horizontal layout
let hzLayoutT = new OO.ui.HorizontalLayout();
//Create firstrow fieldset
//Done
let doneBfieldsetT = new OO.ui.ButtonWidgetFieldsetLayout( {);
fieldsetT.addItems([new OO.ui.FieldLayout(new OO.ui.Widget({content: [hzLayoutT]}), {align: 'top'})]);
icon: "checkAll",
$(responseQuick).append(fieldsetT.$element);
label: "Done",
//Remove button
flags: ["primary", "progressive"],
let remove = new OO.ui.ButtonWidget({
title: "Mark as done"
icon: "trash",
flags: ["primary", "destructive"],
invisibleLabel: true,
title: "Remove the section!"
});
doneBremove.on("click", function () {
$(responseBox).find("tr").each(function(_, row) {
if (doneB.getLabel() == "Submit") {
if (typeof$(replyERT[dropMenurow).getLabelfind('.response-quick')]).length !== "undefined"0) {
row.remove();
execute(currentBox, replyERT[dropMenu.getLabel()], inputText.value, toggleAns.selected, typeChange.value, targetPages.getValue());
} else if (typeChange.value != typeChange.defaultValue) {
execute(currentBox, replyERT.Change, "", false, typeChange.value, targetPages.getValue());
}
let newTargets = false;
let targets = targetPages.items;
if (targets.length == pageLinks.length) {
for(let item = 0; item < targets.length; item++) {
if (targets[item].data != pageLinks[item]) { newTargets = true; }
}
} else {
newTargets = true;
}
if (newTargets) {
execute(currentBox, replyERT.ChangeTarget, "", false, typeChange.value, targetPages.getValue());
}
} else {
execute(currentBox, replyERT.Done, "", toggleAns.selected, typeChange.defaultValue, targetPages.getValue());
}
});
hzLayoutT.addItems([doneB]);
mainResponse.forEach(function(item) {
item[3] = new OO.ui.ButtonWidget({
label: item[1],
title: item[2]
});
hzLayoutT.clearItems();
item[3].on("click", function() {
//Create deletion options
execute(currentBox, item[0], "", toggleAns.selected, typeChange.defaultValue, targetPages.getValue());
let remSec = new OO.ui.ButtonWidget({//RemoveSection
icon: "trash",
flags: ["primary", "destructive"],
label: "Remove section",
title: "Remove the entire section!"
});
remSec.on("click", function () {
hzLayoutT.addItems([item[3]]);
saveResponseERT([editRequest, responseQuick, responsePreview, responseControls], nonResponses.Remove, "", null, typeChange.defaultValue, targetPages.getValue(), "nochange", "");
});
});
//Respond
hzLayoutT.addItems([remSec]);
let respondB = new OO.ui.ButtonWidget( {
hzLayoutT.addItems([cancelB]);
icon: "add",
label: "More",
title: "Extra response options"
});
hzLayoutT.addItems([remove]);
respondB.on("click", function() {
//Open & Close button
if (respondB.getIcon() == "add") {
if (editRequest.attributes[2].localName != "data-origlevel") {
currentBox.children[2].style = "";
let closeB = new OO.ui.ButtonWidget({
doneB.setLabel("Submit");
icon: "unFlag",
doneB.setTitle("Submit response");
invisibleLabel: true,
respondB.setIcon("subtract");
title: "Mark as answered"
respondB.setLabel("Less");
} else {);
closeB.on("click", function () {
currentBox.children[2].style = "display:none";
saveResponseERT([editRequest, responseQuick, responsePreview, responseControls], nonResponses.Close, "", true, typeChange.defaultValue, targetPages.getValue(), "nochange", "");
inputText = "";
});
doneB.setLabel("Done");
hzLayoutT.addItems([closeB]);
doneB.setTitle("Mark as done");
} else {
respondB.setIcon("add");
let openB = new OO.ui.ButtonWidget({
respondB.setLabel("More");
icon: "flag",
}
invisibleLabel: true,
});
title: "Mark as unanswered"
hzLayoutT.addItems([respondB]);
});
openB.on("click", function () {
saveResponseERT([editRequest, responseQuick, responsePreview, responseControls], nonResponses.Open, "", false, typeChange.defaultValue, targetPages.getValue(), "nochange", "");
});
hzLayoutT.addItems([openB]);
}
//Create quick response buttons
for (let i = 0; i < quickResponses.length; i++) {
let newButton = new OO.ui.ButtonWidget({
label: quickResponses[i][1][0],
flags: quickResponses[i][1][1],
title: quickResponses[i][1][2]
});
newButton.on("click", function () {
saveResponseERT([editRequest, responseQuick, responsePreview, responseControls], responses[quickResponses[i][0]], "", toggleAns.selected, typeChange.defaultValue, targetPages.getValue(), "nochange", "");
});
hzLayoutT.addItems([newButton]);
}
//Toggle answer button
let toggleAns = new OO.ui.CheckboxInputWidget({selected: true});
hzLayoutT.addItems([toggleAns, new OO.ui.LabelWidget({label: "Answered"})]);
//Create firstrowlastrow fieldsethorizontal layout
let fieldsetThzLayoutB = new OO.ui.FieldsetLayoutHorizontalLayout();
//Create lastrow fieldset
// Add an horizontal field layout
let fieldsetB = new OO.ui.FieldsetLayout();
fieldsetT.addItems( [
fieldsetB.addItems([new OO.ui.FieldLayout(new OO.ui.Widget({content: [hzLayoutB]}), {align: 'top'})]);
$(responseControls).append(fieldsetB.$element);
new OO.ui.Widget( {
//Cancel response button
content: [hzLayoutT]
let cancelB = new OO.ui.ButtonWidget({
} )
icon: "cancel",
)
flags: ["destructive"],
] );
label: "Cancel",
$(firstRow).append(fieldsetT.$element);
framed: false,
//Close request
title: "Cancel the response & close menu"
let closeB = new OO.ui.ButtonWidget( {
icon: "unFlag",
invisibleLabel: true,
title: "Mark as closed"
});
cancelB.on("click", function () {
closeB.$element[0].style = "margin:10px 10px 0px";
respondButton.setDisabled(false);
closeB.on("click", function() {
responseBox.remove();
execute(currentBox, replyERT.Close, "", true, typeChange.defaultValue, targetPages.getValue());
});
hzLayoutB.addItems([cancelB]);
if (currentBox.parentElement.attributes[2].localName != "data-origlevel") {
//Watchlist dropdown
$(currentBox.children[0].children[0]).append(closeB.$element);
let watchOptions = [{data: "infinite", label: "Permanent"}, {data: "1 day", label: "1 day"}, {data: "3 days", label: "3 days"}, {data: "1 week", label: "1 week"}, {data: "1 month", label: "1 month"}];
let watchValue = "infinite";
if (!!watchStatus[2]) {
watchOptions.unshift({data: "nochange", label: watchStatus[2]});
watchValue = "nochange";
}
let watchlistLayout = new OO.ui.HorizontalLayout();
//Remove request
let removewatchlistDropdown = new OO.ui.ButtonWidgetDropdownInputWidget( {
iconvalue: "trash"watchValue,
options: watchOptions,
flags: ["primary", "destructive"],
disabled: (watchStatus[2] == undefined)
invisibleLabel: true,
title: "Delete entire section!"
});
watchlistLayout.addItems([watchlistDropdown]);
remove.$element[0].style = "margin:10px";
//Watchlist checkbox & label
remove.on("click", function() {
let watchlistCheckbox = new OO.ui.CheckboxInputWidget({
execute(currentBox, replyERT.Remove, "", null, typeChange.defaultValue, targetPages.getValue());
selected: (watchStatus[2] != undefined)
}).on("change", function (newStatus) {
watchlistDropdown.setDisabled(!newStatus);
});
let watchlistLabel = new OO.ui.LabelWidget({label: "Watch this page"}).on("change", function (newStatus) {
$(currentBox.children[0].children[0]).append(remove.$element);
}
 
function addRButton(currentBox) {
let boxType = replyERT[currentBox.parentElement.dataset.origlevel];
let openB = new OO.ui.ButtonWidget( {
icon: "edit",
flags: "progressive",
invisibleLabel: true,
title: "Add response / reopen"
});
hzLayoutB.addItems([watchlistCheckbox, watchlistLabel, watchlistLayout]);
openB.$element[0].style = "margin-top:2px";
//Submit response button
openB.on("click", function() {
let submitB = new OO.ui.ButtonWidget({
openB.$element.remove();
icon: "checkAll",
currentBox.parentElement.className = "plainlinks tmbox tmbox-notice editrequest";
flags: ["primary", "progressive"],
let imgSrc = boxType[0] + "-protection-shackle.svg";
label: "Submit",
let origImg = currentBox.getElementsByTagName("img")[0];
title: "Submit the response",
let img = origImg.outerHTML.slice(0, origImg.outerHTML.match(/\d\//).index);
disabled: true
img += boxType[2] + imgSrc + "/60px-" + imgSrc + '.png" height="60" width="60" style="margin-top:5px">';
origImg.outerHTML = img;
let mboxText = currentBox.children[0].children[1];
mboxText.style = "font-size:120%; text-align:center;";
mboxText.innerHTML = mboxText.innerHTML.replace(/ Set.*\/b>/i, '<br/>Uncheck the "answered" checkbox and use a reply option');
addButtons(currentBox);
});
submitB.on("click", function () {
$(currentBox.children[0].children[0]).append(openB.$element);
let newResponse = responses[dropMenu.getLabel()];
let newText = inputText.value;
if (typeof(newResponse) == "undefined") {
newText = "";
newResponse = nonResponses.ChangeLevel; //Assume that it is a template change
let newPageTargets = [];
targetPages.items.forEach(function(item) {
newPageTargets.push(item.label);
});
if (pageTargets.toString() != newPageTargets.toString()) { //Check if the page targets were changed instead
newResponse = nonResponses.ChangeTarget;
}
}
saveResponseERT([editRequest, responseQuick, responsePreview, responseControls], newResponse, newText, toggleAns.selected, typeChange.value, targetPages.getValue(), watchlistCheckbox.selected, watchlistDropdown.value);
});
hzLayoutB.addItems([submitB]);
}
 
function previewERT(inputText, replyOption, tableRow, template) {
var editRequestBoxes = document.getElementsByClassName("plainlinks tmbox tmbox-notice editrequest");
var restTransform = "https://en.wikipedia.org/api/rest_v1/transform/wikitext/to/html/" + encodeURIComponent(mw.config.get('wgPageName'));
if (editRequestBoxes.length != 0) {
let preview = inputText.value;
mw.loader.using(["oojs-ui-core", "oojs-ui-widgets", "oojs-ui-windows"]).done(function() {
template = dataERT.protections[template][1];
mw.loader.load(["oojs-ui.styles.icons-alerts", "oojs-ui.styles.icons-interactions", "oojs-ui.styles.icons-moderation", "oojs-ui.styles.icons-user", "oojs-ui.styles.icons-content", "oojs-ui.styles.icons-editing-core", "oojs-ui.styles.icons-editing-advanced"]);
if (typeof (replyOption) != "undefined") {
for (let i = 0; i < editRequestBoxes.length; i++) {
preview = "{{" + template + replyOption[0] + "}} " + preview;
let currentBox = editRequestBoxes[i].children[0]; //The tbody tag for the box
}
if (editRequestBoxes[i].id != "") {
if (preview != "") {
addButtons(currentBox);
preview = preview.replaceAll(/{{subst:/gi, "{{");
} else if (currentBox.getElementsByTagName("code").length == 2) { //Check that it is a closed protected edit request
$.post(restTransform, 'wikitext=' + encodeURIComponent(preview) + '&body_only=true',
addRButton(currentBox);
function (html) {
if (inputText.value != "" || typeof (replyOption) != "undefined") {//Stops preview appearing with empty input box
tableRow.style = "padding:8px 1em 2px;";
tableRow.children[1].innerHTML = html.replace("</p>", userSignauteERT);
}
}
);
} else {
tableRow.style = "display:none;";
}
}
 
async function saveResponseERT(requestBox, responseOption, responseText, answered, requestType, targets, watchPage, watchValue) {
await new Promise(function(resolve) {
OO.ui.confirm("Confirm in order to reply to this edit request.").done(function(confirmed) { if (confirmed) {
resolve();
} else {
return;
}});
});
//Create label box & remove action buttons
requestBox[1].innerHTML = "";
requestBox[3].remove();
let infoBox = new OO.ui.MessageWidget({
icon: 'pageSettings',
type: 'notice',
label: 'Processing request — Edit request starting, getting section data to edit.'
});
infoBox.$element[0].style = "margin:5px 0; max-width:50em";
$(requestBox[1]).append(infoBox.$element);
//Create loading bar
let progressBar = new OO.ui.ProgressBarWidget({
progress: false
});
$(requestBox[1]).append(progressBar.$element);
//Set preview for output
if (responseOption[0] != "") {//Don't preview a non-response
let tempValue = {value:responseText};
previewERT(tempValue, responseOption, requestBox[2], requestType);
}
//Find header
let header = "";
let sectionIndex = 0;
let tempElement = requestBox[0];
let sectionQuery = await ApiGetERT({
action: "parse",
page: mw.config.get("wgPageName"),
prop: "sections"
});
let sections = sectionQuery.parse.sections;
do {
tempElement = tempElement.previousElementSibling;
if (tempElement.classList.contains("mw-heading")) {
if (tempElement.parentElement.tagName == "SECTION") { //Need to support both while new parser is being implemented
header = $(tempElement).find("h1,h2,h3,h4,h5,h6")[0].id;
sectionIndex = parseInt(tempElement.parentElement.dataset.mwSectionId);
} else {
if (tempElement.getElementsByClassName("mw-headline").length > 0) { //Vector 2022
header = tempElement.getElementsByClassName("mw-headline")[0].id;
} else { //Vector Legacy
header = $(tempElement).find("h1,h2,h3,h4,h5,h6")[0].id;
}
for (let i = 0; i < sections.length; i++) {
if (sections[i].anchor == header) {
sectionIndex = parseInt(sections[i].index);
}
}
}
}
}
while (header == "");
infoBox.setLabel("Processing request — Making changes to the edit request");
let editSummary = "/* " + header.replaceAll("_", " ") + " */ " + responseOption[2] + " ([[User:Terasail/Edit_Request_Tool|Edit Request Tool]])";
let wikitextQuery = await ApiGetERT({
action: "parse",
page: mw.config.get("wgPageName"),
section: sectionIndex,
prop: "wikitext|revid"
});
let wikitext = wikitextQuery.parse.wikitext["*"];
let latestRevision = wikitextQuery.parse.revid;
if (responseOption[1] != "Remove") {
let editTemplate = "{{Edit " + requestType + "-protected";
for (let c3 = 0; c3 < targets.length; c3++) {
editTemplate += "|" + targets[c3];
}
if (answered) {
editTemplate += "|answered=yes";
} else {
editTemplate += "|answered=no";
}
wikitext = wikitext.replace(/{{ *([SETFI]PER|Edit([ -]?[A-Z]+[ -]?|[- ])Protected|Sudo)\s*[^}}]*/i, editTemplate);
if (responseOption[1] != "Close") {
wikitext = wikitext.trim() + "\n:";
if (responseOption[0] != "") {
wikitext += "{{subst:" + dataERT.protections[requestType][1] + responseOption[0] + "}} ";
}
if (responseText != "") {
wikitext += responseText.replaceAll(/\s*~~~~\s*/g, "") + " ";
}
wikitext += "~~~~";
}
} else {
wikitext = "";
editSummary = editSummary.replace(/[^]+\*\/ /, "");
}
infoBox.setType("success");
infoBox.setLabel("Processing request — Saving changes to the talk page.");
if (latestRevision != mw.config.values.wgRevisionId) {
await new Promise(function(resolve) {
OO.ui.confirm("There has been a new revision to the page, do you wish to continue?").done(function(confirmed) { if (confirmed) {
resolve();
} else {
return;
}});
});
}
if (watchPage) {
if (watchPage != "nochange") {
watchPage = "watch";
}
} else {
watchPage = "unwatch";
}
let apiParams = {
action: 'edit',
title: mw.config.get("wgPageName"),
text: wikitext,
section: sectionIndex,
summary: editSummary,
watchlist: watchPage
};
if (watchPage == "watch") {
apiParams.watchlistexpiry = watchValue;
}
new mw.Api().postWithEditToken(apiParams).done(function () {
window.___location = "/w/index.php?title=" + encodeURI(mw.config.get("wgPageName")) + "&type=revision&diff=cur&oldid=prev";
});
}
 
function ApiGetERT(params) {
return new Promise(function(resolve) {
new mw.Api().get(params)
.done(function (data) {resolve(data);})
.fail(function (data) {console.error(data);});
});
}