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

Content deleted Content added
Change how warn works
Account for Template:Sudo
 
(16 intermediate revisions by 2 users not shown)
Line 1:
//*<nowiki>
Edit Request Tool
/*jshint esversion: 6*/
Created by: Terasail
var editRequestBoxes = document.getElementsByClassName("plainlinks tmbox tmbox-notice editrequest");
*/
var pageWatchers = "There are currently ";
var watchStatus;
var dataERT;
var apiuserSignauteERT = new mw.Api()"";
var editRequestBoxes = $('.editrequest');
var pageNameERT = mw.config.values.wgPageName;
var editRequests = [];
var encodePageName = encodeURIComponent(pageNameERT);
for (let i = 0; i < editRequestBoxes.length; i++) {
 
if (typeof(editRequestBoxes[i].attributes['data-origlevel']) != 'undefined') {
function postEdit(wikitext, editSummary, secIndx, changeWatch, watchlist) {
if (editRequestBoxes[i].id == "") {
let apiParams = {
$(editRequestBoxes[i].children[0].children[0].children[0]).append('<div class="response-cell-ert" style="text-align:center;"></div>');
action: 'edit',
} else {
title: pageNameERT,
$(editRequestBoxes[i].children[0]).append('<tr><td colspan="2" class="response-cell-ert" style="text-align:center;"></td></tr>');
text: wikitext,
}
section: secIndx,
editRequests.push(editRequestBoxes[i]);
summary: editSummary,
watchlist: changeWatch
};
let reloadURL = "/w/index.php?title=" + encodePageName + "&type=revision&diff=cur&oldid=prev";
if (changeWatch == "watch") {
apiParams.watchlistexpiry = watchlist;
}
api.postWithEditToken(apiParams).done(function(result) { window.___location = reloadURL; });
}
 
if (editRequests.length > 0) {
function execute(responseTable, replyOption, inputText, answered, boxType, targets, changeWatch, watchlist) {
mw.loader.using(["oojs-ui-core", "oojs-ui-widgets", "oojs-ui-windows"]).done(function() {
OO.ui.confirm("Confirm in order to reply to this edit request.").done(function(confirmed) {
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"]);
if (confirmed) {
loadERTool();
//Create label box & remove action buttons
$.getJSON("https://en.wikipedia.org/w/index.php?title=User:Terasail/Edit_Request_Tool.json&action=raw&ctype=text/json", function (newData) {
let firstRow = responseTable.children[1].children[0];
firstRow.innerHTMLdataERT = ""newData;
});
responseTable.children[5].children[0].remove();
ApiGetERT({
let infoBox = new OO.ui.MessageWidget( {
iconaction: 'pageSettings'"parse",
title: mw.config.get("wgPageName"),
type: 'notice',
text: "~~~~",
label: 'Processing request — Edit request starting, getting section data to edit.'
pst: "true",
});
disablelimitreport: "true",
infoBox.$element[0].style = "margin:5px 0; max-width:50em";
disableeditsection: "true",
$(firstRow).append(infoBox.$element);
preview: "true"
//Create loading bar
}).then(function(data){
let progressBar = new OO.ui.ProgressBarWidget( {
userSignauteERT = data.parse.text["*"].replaceAll(/([^]+(?=<p>)<p>|<\/div>)/g, " ");
progress: false
});
});
$(firstRow).append(progressBar.$element);
}
//Set preview for output
 
if (replyOption[0] != "") {//Don't preview a non-response
async function loadERTool() {
showOutput(inputText, replyOption, responseTable.children[4].children[0], boxType);
// Get page watchers, visitors and user watch status.
}
let watchStatus = [];
//Find header
let watchQuery = await ApiGetERT({
let header = "";
action: "query",
let curElement = responseTable.parentNode;
prop: "info",
do {
pageids: mw.config.get("wgArticleId"),
curElement = curElement.previousElementSibling;
inprop: "watchers|visitingwatchers|watched",
if (curElement.getElementsByClassName("mw-headline").length == 1) {
format: "json"
header = curElement.getElementsByClassName("mw-headline")[0].id;
});
}
let watchData = watchQuery.query.pages[mw.config.get("wgArticleId")];
}
let watched = watchData.watched;
while (header == "");
let expiry = watchData.watchlistexpiry;
api.get( {
if (expiry) {
action: "parse",
watched = Math.ceil((new Date(expiry).getTime() - Date.now()) / 1000 / 60 / 60 / 24) + " days";
page: pageNameERT,
}
prop: "sections"
watchStatus.push(watchData.watchers || "less than 30", watchData.visitingwatchers || "<30", watched);
}).done(function(data) {
//Increment through all edit requests & add respond button
infoBox.setLabel("Processing request — Making changes to the edit request");
for (let i = 0; i < editRequests.length; i++) {
let editTemplate = "{{Edit " + boxType + "-protected";
let responseCell = $('.response-cell-ert')[i];
if (answered) { answered = "yes"; } else { answered = "no"; }
let smallButton = false;
for (let c3 = 0; c3 < targets.length; c3++) {
if (responseCell.tagName == "DIV") {
editTemplate += "|" + targets[c3];
smallButton = true;
}
editTemplate += "|answered=" + answered;
let sections = data.parse.sections;
let secIndx = sections[0];
for (let j = 0; j < sections.length; j++) {
if (sections[j].anchor == header) {
secIndx = parseInt(sections[j].index);
}
}
api.get( {
action: "parse",
page: pageNameERT,
section: secIndx,
prop: "wikitext|revid"
}).done(function(data) {
let wikitext = data.parse.wikitext["*"];
let newRev = data.parse.revid;
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") {
wikitext = wikitext.trim() + "\n:";
if (replyOption[0] != "") { wikitext += "{{subst:" + dataERT.protections[boxType][1] + replyOption[0] + "}} "; }
if (inputText != "") { wikitext += inputText.replaceAll(/\s*~~~~\s*/g, "") + " "; }
wikitext += "~~~~";
if (replyOption[1] == "Remove") {
wikitext = "";
if (inputText == "EmptyNotice") {
let commentERT = document.getElementById(header).dataset.mwComment;
if (typeof(commentERT) != 'undefined' && commentERT.search(/-(?=[0-9]{14}","type)/) != -1) {
let commenter = commentERT.slice(commentERT.indexOf('"name"') + 10, commentERT.search(/-(?=[0-9]{14}","type)/));
let talkParams = dataERT.emptyNotice;
talkParams.title = "User talk:" + commenter;
talkParams.sectiontitle += pageNameERT;
talkParams.text = talkParams.text.replace("```", pageNameERT);
talkParams.summary = talkParams.summary.replace("```", pageNameERT);
console.log(talkParams);
api.postWithEditToken(talkParams).done(function(result) {
//Do something here?
});
}
}
editSummary = editSummary.replace(/[^]+\*\/ /, "");
}
}
infoBox.setType("success");
infoBox.setLabel("Processing request — Saving changes to the talk page.");
if (newRev == mw.config.values.wgRevisionId) {
postEdit(wikitext, editSummary, secIndx, changeWatch, watchlist);
} 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, secIndx, changeWatch, watchlist); }
});
}
});
});
}
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 addButtonsloadERTResponse(currentBoxeditRequest, replyButtonrespondButton, watchStatus) {
let boxType = currentBox.parentElementeditRequest.dataset.origlevel;
boxType = boxType.replace("full", "fully");
$('<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 tableElem = currentBox.parentElement;
let responseBox = editRequest.nextElementSibling;
$('<table style="border:1px solid #A2A9B1; border-radius:2px; padding:10px 16px 0; margin:auto; max-width:55em; width:100%; clear:both;"><tr><td style="color:#808080"><div style="font-style:italic; margin-left:1em;">' + pageWatchers + '</div><div>Quick options:</div></td></tr><tr style="display: flex; justify-content: center;"><td></td></tr><tr><td style="color:#808080">Custom response:</td></tr><tr style="text-align:center;"><td></td></tr><tr style="background:#F6F6F6;"><td style="display:none;"><div style="color:#808080">Preview:</div><div></div></td></tr><tr style="display: flex; justify-content: right;"><td></td></tr></table>').insertAfter(tableElem);
let responseQuick = $(responseBox).find('.response-quick')[0];
let responseTable = tableElem.nextElementSibling.children[0];
let responseCustom = $(responseBox).find('.response-custom')[0];
let firstRow = responseTable.children[1].children[0];
let responsePreview = $(responseBox).find('.response-preview')[0];
let secondRow = responseTable.children[3].children[0];
let responseControls = $(responseBox).find('.response-controls')[0];
let thirdRow = responseTable.children[4].children[0];
let fourthRow = responseTable.children[5].children[0];
let protections = Object.entries(dataERT.protections);
let responses = Object.entries(dataERT.response);
Line 146 ⟶ 96:
tcOptions.push({data: protections[i][0], label: protections[i][1][0]});
}
let typeChange = new OO.ui.DropdownInputWidget( {
value: boxType,
options: tcOptions
});
typeChange.on("change", function () {
submitB.setDisabled(false);
});
typeChange.$element[0].style = "text-align:left; margin:auto";
$(secondRowresponseCustom).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 = pageNameERTmw.config.get("wgPageName").replace(/(_talk|Talk:)/, "").replaceAll("_", " ");
}
}
let targetPages = new OO.ui.TagMultiselectWidget( {
placeholder: 'Target Pages',
allowArbitrary: true,
selected: pageLinkspageTargets
});
targetPages.on("change", function () {
submitB.setDisabled(false);
});
targetPages.$element[0].style = "text-align:left; margin:5px auto";
$(secondRowresponseCustom).append(targetPages.$element);
//Create dropdown menu
let dropMenu = new OO.ui.DropdownWidget( {
label: "Select reply option - Add additional text below",
menu: {items: []}
Line 197 ⟶ 147:
responses = dataERT.response;
dropMenu.$element[0].style = "text-align:left; margin:0px";
$(secondRowresponseCustom).append(dropMenu.$element);
dropMenu.on("labelChange", function () {
submitB.setDisabled(false);
showOutputpreviewERT(inputText, responses[dropMenu.getLabel()], thirdRowresponsePreview, typeChange.value);
});
//Create input box
let inputText = new OO.ui.MultilineTextInputWidget({autosize: true, rows: 4, label: "Additional text"});
inputText.$element[0].style = "margin:5px auto";
$(secondRowresponseCustom).append(inputText.$element);
inputText.on("change", function (newText) {
showOutputpreviewERT(inputText, responses[dropMenu.getLabel()], thirdRowresponsePreview, typeChange.value);
});
//Create top horizontal layout
Line 213 ⟶ 163:
//Create firstrow fieldset
let fieldsetT = new OO.ui.FieldsetLayout();
fieldsetT.addItems([new OO.ui.FieldLayout(new OO.ui.Widget({content: [hzLayoutT]}), {align: 'top' })]);
$(firstRowresponseQuick).append(fieldsetT.$element);
//Remove button
let remove = new OO.ui.ButtonWidget( {
icon: "trash",
flags: ["primary", "destructive"],
Line 222 ⟶ 172:
title: "Remove the section!"
});
remove.on("click", function () {
$(responseBox).find("tr").each(function(_, row) {
secondRow.style = "display:none";
if ($(row).find('.response-quick').length == 0) {
thirdRow.style = "display:none";
row.remove();
fourthRow.style = "display:none";
}
responseTable.children[2].children[0].style = "display:none";
});
submitB.$element.remove();
hzLayoutT.clearItems();
//Create deletion options
let remSec = new OO.ui.ButtonWidget( {//RemoveSection
icon: "trash",
flags: ["primary", "destructive"],
Line 236 ⟶ 186:
title: "Remove the entire section!"
});
remSec.on("click", function () {
saveResponseERT([editRequest, responseQuick, responsePreview, responseControls], nonResponses.Remove, "", null, typeChange.defaultValue, targetPages.getValue(), "nochange", "");
if (toggleESN.selected) {
execute(responseTable, nonResponses.Remove, "EmptyNotice", null, typeChange.defaultValue, targetPages.getValue(), "nochange", "");
} else {
execute(responseTable, nonResponses.Remove, "", null, typeChange.defaultValue, targetPages.getValue(), "nochange", "");
}
});
hzLayoutT.addItems([remSec]);
let toggleESN = new OO.ui.CheckboxInputWidget({selected: false});
hzLayoutT.addItems([toggleESN, new OO.ui.LabelWidget({label: "Give the user an empty section notice"})]);
hzLayoutT.addItems([cancelB]);
});
hzLayoutT.addItems([remove]);
//Open & Close button
if (currentBox.parentElementeditRequest.attributes[2].localName != "data-origlevel") {
let closeB = new OO.ui.ButtonWidget( {
icon: "unFlag",
invisibleLabel: true,
title: "Mark as answered"
});
closeB.on("click", function () {
executesaveResponseERT(responseTable[editRequest, responseQuick, responsePreview, responseControls], nonResponses.Close, "", true, typeChange.defaultValue, targetPages.getValue(), "nochange", "");
});
hzLayoutT.addItems([closeB]);
} else {
let openB = new OO.ui.ButtonWidget( {
icon: "flag",
invisibleLabel: true,
title: "Mark as unanswered"
});
openB.on("click", function () {
executesaveResponseERT(responseTable[editRequest, responseQuick, responsePreview, responseControls], nonResponses.Open, "", false, typeChange.defaultValue, targetPages.getValue(), "nochange", "");
});
hzLayoutT.addItems([openB]);
Line 278 ⟶ 222:
title: quickResponses[i][1][2]
});
newButton.on("click", function () {
executesaveResponseERT(responseTable[editRequest, responseQuick, responsePreview, responseControls], responses[quickResponses[i][0]], "", toggleAns.selected, typeChange.defaultValue, targetPages.getValue(), "nochange", "");
});
hzLayoutT.addItems([newButton]);
Line 290 ⟶ 234:
//Create lastrow fieldset
let fieldsetB = new OO.ui.FieldsetLayout();
fieldsetB.addItems([new OO.ui.FieldLayout(new OO.ui.Widget({content: [hzLayoutB]}), {align: 'top' })]);
$(fourthRowresponseControls).append(fieldsetB.$element);
//Cancel response button
let cancelB = new OO.ui.ButtonWidget( {
icon: "cancel",
flags: ["destructive"],
Line 300 ⟶ 244:
title: "Cancel the response & close menu"
});
cancelB.on("click", function () {
replyButtonrespondButton.setDisabled(false);
responseTable.parentElementresponseBox.remove();
});
hzLayoutB.addItems([cancelB]);
let isWatched = (typeof(watchStatus[0]) != "undefined");
//Watch list//Toggle answer button
let toggleWL = new OO.ui.CheckboxInputWidget({selected: isWatched});
let toggleWLLable = new OO.ui.LabelWidget({label: "Watch this page"});
toggleWL.on("change", function(newStatus) {
watchDropdown.setDisabled(!newStatus);
});
toggleWLLable.$element[0].style = "white-space: nowrap;";
hzLayoutB.addItems([toggleWL, toggleWLLable]);
let watchValue = "never";
let watchOptions = [{data: "never", 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 wlExpiry = watchStatus[1];
if (typeof(wlExpiry) != "undefined") {
let daysDif = Math.ceil((new Date(wlExpiry).getTime() - Date.now())/1000/60/60/24);
watchOptions.unshift({data: "nochange", label: daysDif + " days"});
watchValue = wlExpiry;
}
//Create WLDropdown horizontal layout
let hzLayoutWLD = new OO.ui.HorizontalLayout();
hzLayoutB.addItems([hzLayoutWLD]);
//Watchlist dropdown
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 watchDropdown = new OO.ui.DropdownInputWidget( {
let watchValue = "infinite";
if (!!watchStatus[2]) {
watchOptions.unshift({data: "nochange", label: watchStatus[2]});
watchValue = "nochange";
}
let watchlistLayout = new OO.ui.HorizontalLayout();
let watchlistDropdown = new OO.ui.DropdownInputWidget({
value: watchValue,
options: watchOptions,
disabled: !isWatched(watchStatus[2] == undefined)
});
watchlistLayout.addItems([watchlistDropdown]);
//Watchlist checkbox & label
let watchlistCheckbox = new OO.ui.CheckboxInputWidget({
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) {
 
});
hzLayoutB.addItems([watchlistCheckbox, watchlistLabel, watchlistLayout]);
hzLayoutWLD.addItems([watchDropdown]);
//Submit response button
let submitB = new OO.ui.ButtonWidget( {
icon: "checkAll",
flags: ["primary", "progressive"],
Line 340 ⟶ 281:
disabled: true
});
submitB.on("click", function () {
let newResponse = responses[dropMenu.getLabel()];
let newText = inputText.value;
if (typeof(newResponse) == "undefined") {
let isAns = toggleAns.selected;
newText = "";
let newType = typeChange.value;
newResponse = nonResponses.ChangeLevel; //Assume that it is a template change
let newTargets = targetPages.getValue();
let targetsnewPageTargets = targetPages.items[];
targetPages.items.forEach(function(item) {
let targetChange = false;
newPageTargets.push(item.label);
let wlChange = toggleWL.selected;
});
let wlVals = watchDropdown.value;
if (pageTargets.toString() != newPageTargets.toString()) { //Check if the page targets were changed instead
if (wlChange) {
newResponse = nonResponses.ChangeTarget;
wlChange = "watch";
if (wlVals == "nochange") {
wlChange = "nochange";
}
} else {
wlChange = "unwatch";
}
if (typeof(newResponse) != "undefined") {
execute(responseTable, newResponse, newText, isAns, newType, newTargets, wlChange, wlVals);
} else if (typeChange.value != typeChange.defaultValue) {
execute(responseTable, nonResponses.ChangeLevel, "", isAns, newType, newTargets, wlChange, wlVals);
}
if (targets.length == pageLinks.length) {
for(let item = 0; item < targets.length; item++) {
if (targets[item].data != pageLinks[item]) { targetChange = true; }
}
} else {
targetChange = true;
}
if (targetChange) {
execute(responseTable, nonResponses.ChangeTarget, "", isAns, newType, newTargets, wlChange, wlVals);
}
saveResponseERT([editRequest, responseQuick, responsePreview, responseControls], newResponse, newText, toggleAns.selected, typeChange.value, targetPages.getValue(), watchlistCheckbox.selected, watchlistDropdown.value);
});
hzLayoutB.addItems([submitB]);
}
 
function showOutputpreviewERT(inputText, replyOption, tableRow, template) {
var restTransform = "https://en.wikipedia.org/api/rest_v1/transform/wikitext/to/html/" + encodePageNameencodeURIComponent(mw.config.get('wgPageName'));
let preview = ""inputText.value;
let newText = inputText.value;
if (typeof(inputText) == 'string') {
newText = inputText;
}
template = dataERT.protections[template][1];
if (typeof (replyOption) != "undefined") {
preview += "{{" + template + replyOption[0] + "}} " + preview;
}
if (newText != "" && typeof(newText) != "undefined") { preview += newText + " "; }
if (preview != "") {
let nickname = " " + mw.user.options.values.nickname;
if (nickname == " ") {//Create default signature if no nickname
nickname = mw.user.getName();
nickname = " [[User:" + nickname + "|" + nickname + "]] ([[User talk:" + nickname + "|talk]])";
}
let dateObj = new Date();
let dateNow = dateObj.toLocaleDateString('en-GB', { timeZone: 'UTC', year: 'numeric', month: 'long', day: 'numeric'});
let timeNow = dateObj.toLocaleTimeString('en-GB', { timeZone: 'UTC', hour: '2-digit', minute: '2-digit' });
preview += nickname + " " + timeNow + ", " + dateNow + " (UTC)";
preview = preview.replaceAll(/{{subst:/gi, "{{");
$.post(restTransform, 'wikitext=' + encodeURIComponent(preview) + '&body_only=true',
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);
}
}
Line 413 ⟶ 322:
}
 
async function saveResponseERT(requestBox, responseOption, responseText, answered, requestType, targets, watchPage, watchValue) {
if (editRequestBoxes.length != 0) {
await new Promise(function(resolve) {
let pageID = mw.config.values.wgArticleId;
OO.ui.confirm("Confirm in order to reply to this edit request.").done(function(confirmed) { if (confirmed) {
api.get({
resolve();
action: "query",
prop: "info",
pageids: pageID,
inprop: "watchers|visitingwatchers|watched",
format: "json"
}).done(function(data) {
data = data.query.pages[pageID];
let watchers = data.watchers;
let visiting = data.visitingwatchers;
watchStatus = [data.watched, data.watchlistexpiry];
if (typeof(watchers) == "undefined") {
pageWatchers += "less than 30";
} else {
return;
pageWatchers += watchers;
}});
});
//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) {
pageWatchers += " users watching this page (";
editTemplate += "|answered=yes";
if (typeof(visiting) == "undefined") {
pageWatchers += "0";
} else {
pageWatcherseditTemplate += visiting"|answered=no";
}
wikitext = wikitext.replace(/{{ *([SETFI]PER|Edit([ -]?[A-Z]+[ -]?|[- ])Protected|Sudo)\s*[^}}]*/i, editTemplate);
pageWatchers += " have viewed recent edits).";
if (responseOption[1] != "Close") {
});
wikitext = wikitext.trim() + "\n:";
var jsonERTURL = "https://en.wikipedia.org/w/index.php?title=User:Terasail/Edit_Request_Tool.json&action=raw&ctype=text/json";
if (responseOption[0] != "") {
$.getJSON(jsonERTURL, function(newData) {
wikitext += "{{subst:" + dataERT.protections[requestType][1] + responseOption[0] + "}} ";
dataERT = newData;
mw.loader.load(["oojs-ui-core", "oojs-ui-widgets", "oojs-ui-windows"]);
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"]);
});
for (let i = 0; i < editRequestBoxes.length; i++) {
let currentBox = editRequestBoxes[i].children[0]; //The tbody tag for the box
if (typeof(currentBox.parentElement.dataset.origlevel) != "undefined") {
let isSmall = false;
if (editRequestBoxes[i].id == "") {
isSmall = true;
}
if (responseText != "") {
let replyButton = new OO.ui.ButtonWidget( {
wikitext += responseText.replaceAll(/\s*~~~~\s*/g, "") + " ";
icon: "edit",
flags: ["progressive"],
label: "Respond",
invisibleLabel: isSmall,
title: "Respond to the edit request."
});
replyButton.on("click", function() {
addButtons(currentBox, replyButton);
replyButton.setDisabled(true);
});
replyButton.$element[0].style = "margin:2px 0";
if (isSmall) {
$(currentBox.children[0].children[0]).append(replyButton.$element);
} else {
$(currentBox).append('<tr><td colspan=2><div style="display: flex; justify-content: center;"></div></td></tr>');
$(currentBox.children[1].children[0].children[0]).append(replyButton.$element);
}
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);});
});
}
//</nowiki>[[Category:Wikipedia scripts]]