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

Content deleted Content added
test
Account for {{COI edit}}
 
(7 intermediate revisions by the same user not shown)
Line 29:
{label: "Undo", title: "Undo request", summary: "COI request has been undone", parameter: "D|The requested edit has been undone", response: "ud", icon: "undo", flags: "", text: "Undone: This request has been undone."}
];
var api = new mw.Api();
var editRequests = $('.editrequest');
var COIRequests = [];
Line 38 ⟶ 37:
}
}
 
if (COIRequests.length > 0) {
mw.loader.using(["oojs-ui-core", "oojs-ui-widgets", "oojs-ui-windows"]).done(function() {
mw.loader.load(["oojs-ui.styles.icons-alerts", "oojs-ui.styles.icons-interactions", "oojs-ui.styles.icons-moderation", "oojs-ui.styles.icons-editing-core", "oojs-ui.styles.icons-editing-advanced", "oojs-ui.styles.icons-user"]);
loadCOITool();
//Get page watchers, visitors and user watch status.
let watchStatus = [];
let pageID = mw.config.get("wgArticleId");
new mw.Api().get({
action: "query",
prop: "info",
pageids: pageID,
inprop: "watchers|visitingwatchers|watched",
format: "json"
}).done(function (data) {
data = data.query.pages[pageID];
let watched = data.watched;
let expiry = data.watchlistexpiry;
if (expiry) {
watched = Math.ceil((new Date(expiry).getTime() - Date.now()) / 1000 / 60 / 60 / 24) + " days";
}
watchStatus.push(data.watchers || "less than 30", data.visitingwatchers || "<30", watched);
});
//Increment through all COI requests & add respond button
for (let i = 0; i < COIRequests.length; i++) {
let respondButton = new OO.ui.ButtonWidget({
icon: "edit",
label: "Respond",
flags: "progressive",
title: "Open the response menu for this request"
}).on("click", function() {
loadCOIResponseBox(COIRequests[i], respondButton, watchStatus);
respondButton.setDisabled(true);
});
respondButton.$element[0].style = "margin:5px";
$($('.response-cell')[i]).append(respondButton.$element);
}
});
}
 
async function loadCOITool() {
function loadCOIResponseBox(COIRequest, respondButton, watchStatus) {
// Get page watchers, visitors and user watch status.
let responseBoxHTML = '<table class="response-box" 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;">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 style="color:#808080">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 style="color:#808080">Preview:</div><div></div></td></tr><tr style="display: flex; justify-content: right;"><td class="response-controls"></td></tr></table>';
let watchStatus = [];
let watchQuery = await ApiGetCOI({
action: "query",
prop: "info",
pageids: mw.config.get("wgArticleId"),
inprop: "watchers|visitingwatchers|watched",
format: "json"
});
let watchData = watchQuery.query.pages[mw.config.get("wgArticleId")];
let watched = watchData.watched;
let expiry = watchData.watchlistexpiry;
if (expiry) {
watched = Math.ceil((new Date(expiry).getTime() - Date.now()) / 1000 / 60 / 60 / 24) + " days";
}
if (watched == undefined && typeof(autoWatchRequests) != "undefined" && autoWatchRequests == true) {
watched = '';
}
watchStatus.push(watchData.watchers || "less than 30", watchData.visitingwatchers || "<30", watched);
//Increment through all COI requests & add respond button
for (let i = 0; i < COIRequests.length; i++) {
let respondButton = new OO.ui.ButtonWidget({
icon: "edit",
label: "Respond",
flags: "progressive",
title: "Open the response menu for this request"
}).on("click", function() {
loadCOIResponse(COIRequests[i], respondButton, watchStatus);
respondButton.setDisabled(true);
});
respondButton.$element[0].style = "margin:5px";
$($('.response-cell')[i]).append(respondButton.$element);
}
}
 
function loadCOIResponse(COIRequest, respondButton, watchStatus) {
let responseBoxHTML = '<table class="response-box" 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>';
$(responseBoxHTML).insertAfter(COIRequest, respondButton);
let responseBox = COIRequest.nextElementSibling;
Line 104 ⟶ 109:
invisibleLabel: true
}).on("click", function () {
executeCOIResponsesaveResponseCOI([COIRequest, responseQuick, responsePreview, responseControls], nonResponseCOI[tempVal], "", "nochange", undefined);
});
quickLayout.addItems([tempButton]);
Line 116 ⟶ 121:
title: responseCOI[tempVal].title
}).on("click", function () {
executeCOIResponsesaveResponseCOI([COIRequest, responseQuick, responsePreview, responseControls], responseCOI[tempVal], "", "nochange", undefined);
});
quickLayout.addItems([tempButton]);
Line 123 ⟶ 128:
//Response dropdown
let responseDropdown = new OO.ui.DropdownWidget({
label: "Select reply option - Add additional text below",
menu: {items: []}
}).on("labelChange", function () {
submitButton.setDisabled(false);
peviewCOIResponsepreviewCOI(responseDropdown.menu.findSelectedItem().getData(), responseText.value, responsePreview);
});
for (let i = 0; i < responseCOI.length; i++) {
let tempWidget = new OO.ui.MenuOptionWidget({
Line 144 ⟶ 149:
}).on("change", function () {
if (responseDropdown.menu.findSelectedItem()) {
peviewCOIResponsepreviewCOI(responseDropdown.menu.findSelectedItem().getData(), responseText.value, responsePreview);
}
});
responseText.$element[0].style = "margin:5px auto;";
$(responseCustom).append(responseText.$element);
Line 175 ⟶ 180:
}
let watchlistLayout = new OO.ui.HorizontalLayout();
let watchlistDropdown = new OO.ui.DropdownInputWidget({
value: watchValue,
options: watchOptions,
disabled: (watchStatus[2] == undefined)
});
watchlistLayout.addItems([watchlistDropdown]);
//Watchlist checkbox & label
Line 187 ⟶ 192:
watchlistDropdown.setDisabled(!newStatus);
});
let watchlistLabel = new OO.ui.LabelWidget({label: "Watch this page"}).on("change", function (newStatus) {;
 
});
//Submit Button
let submitButton = new OO.ui.ButtonWidget({
Line 198 ⟶ 201:
disabled: true
}).on("click", function () {
executeCOIResponsesaveResponseCOI([COIRequest, responseQuick, responsePreview, responseControls], responseDropdown.menu.findSelectedItem().getData(), responseText.value, watchlistCheckbox.selected, watchlistDropdown.value);
});
controlsLayout.addItems([cancelButton, watchlistCheckbox, watchlistLabel, watchlistLayout, submitButton]);
}
 
function peviewCOIResponsepreviewCOI(responseOption, responseText, tableCell) {
let restTransform = "https://en.wikipedia.org/api/rest_v1/transform/wikitext/to/html/" + encodeURI(mw.config.get("wgPageName"));
if (responseOption.response != "") {
Line 211 ⟶ 214:
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'});
responseText = responseText + nickname + " " + timeNow + ", " + dateNow + " (UTC)";
responseText = responseText.replaceAll(/{{subst:/gi, "{{");
responseText = responseText.replaceAll(/\s*~~~~\s*/g, "");
$.post(restTransform, 'wikitext=' + encodeURIComponent(responseText) + '&body_only=true',
function (html) {
tableCell.style = "padding:8px 1em 2px;";
tableCell.children[1].innerHTML = html;
}
}
);
);
} else {
tableCell.style = "display:none;";
}
}
}
 
async function executeCOIResponsesaveResponseCOI(requestBox, responseOption, responseText, 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();
//Create label box & remove quick actions
} else {
requestBox[1].innerHTML = "";
return;
requestBox[3].remove();
}});
let statusMessage = new OO.ui.MessageWidget({
});
icon: 'pageSettings',
//Create label box & remove quick actions
type: 'notice',
requestBox[1].innerHTML = "";
label: 'Processing request — Edit request starting, getting section data to edit.'
requestBox[3].remove();
});
let statusMessage.$element[0].style = "margin:5pxnew 0; max-width:50em";OO.ui.MessageWidget({
icon: 'pageSettings',
$(requestBox[1]).append(statusMessage.$element);
type: 'notice',
//Create progress bar
label: 'Processing request — Edit request starting, getting section data to edit.'
let progressBar = new OO.ui.ProgressBarWidget({
});
progress: false
statusMessage.$element[0].style = "margin:5px 0; max-width:50em";
});
$(requestBox[1]).append(progressBarstatusMessage.$element);
//Create progress bar
//Set preview for output
let progressBar = new OO.ui.ProgressBarWidget({
peviewCOIResponse(responseOption, responseText, requestBox[2]);
progress: false
//Find header
});
let header = "";
let tempElement = $(requestBox[01]).append(progressBar.$element);
//Set preview for output
do {
previewCOI(responseOption, responseText, requestBox[2]);
tempElement = tempElement.previousElementSibling;
// Find header
if (tempElement.getElementsByClassName("mw-headline").length == 1) {
let header = "";
header = tempElement.getElementsByClassName("mw-headline")[0].id;
let sectionIndex = 0;
}
let tempElement = requestBox[0];
}
let sectionQuery = await ApiGetCOI({
while (header == "");
action: "parse",
let editSummary = "/* " + header.replaceAll("_", " ") + " */ " + responseOption.summary + " ([[User:Terasail/COI_Request_Tool|COI Request Tool]])";
page: mw.config.get("wgPageName"),
api.get({
actionprop: "parsesections",
});
page: mw.config.get("wgPageName"),
let sections = sectionQuery.parse.sections;
prop: "sections"
do {
}).done(function (data) {
tempElement = tempElement.previousElementSibling;
let sections = data.parse.sections;
if (tempElement.classList.contains("mw-heading")) {
let sectionIndex = 0;
if (tempElement.parentElement.tagName == "SECTION") { //Need to support both while new parser is being implemented
statusMessage.setLabel("Processing request — Making changes to the edit request");
header = $(tempElement).find("h1,h2,h3,h4,h5,h6")[0].id;
for (let i = 0; i < sections.length; i++) {
sectionIndex = parseInt(tempElement.parentElement.dataset.mwSectionId);
if (sections[i].anchor == header) {
} else {
sectionIndex = parseInt(sections[i].index);
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) {
api.get({
sectionIndex = parseInt(sections[i].index);
action: "parse",
}
page: mw.config.get("wgPageName"),
section: sectionIndex,
prop: "wikitext|revid"
}).done(function (data) {
let wikitext = data.parse.wikitext["*"];
let latestRevision = data.parse.revid;
if (responseOption.parameter != "") {
let template = "{{Edit COI|" + responseOption.parameter + "}}";
wikitext = wikitext.replace(/{{ *(Edit[ _])?COI(-protected|([ _](edit|request)){2})?( *\| *([=A-Z])*)* *}}/i, template);
}
}
if (responseOption.response != "") {
}
wikitext += "\n:{{subst:ECOI|" + responseOption.response + "}}";
}
wikitext += responseText.replaceAll(/\s*~~~~\s*/g, "") + " ~~~~";
while (header == "");
}
statusMessage.setLabel("Processing request — Making changes to the edit request");
if (responseOption.label == "Remove") {
let editSummary = "/* " + header.replaceAll("_", " ") + " */ " + responseOption.summary + " ([[User:Terasail/COI_Request_Tool|COI Request Tool]])";
wikitext = "";
let wikitextQuery = await ApiGetCOI({
editSummary = editSummary.replace(/[^]+\*\/ /, "");
action: "parse",
}
page: mw.config.get("wgPageName"),
statusMessage.setType("success");
section: sectionIndex,
statusMessage.setLabel("Processing request — Saving changes to the talk page.");
prop: "wikitext|revid"
if (latestRevision == mw.config.values.wgRevisionId) {
});
postCOIResponse(wikitext, editSummary, sectionIndex, watchPage, watchValue);
let wikitext = wikitextQuery.parse.wikitext["*"];
} else {
let latestRevision = wikitextQuery.parse.revid;
OO.ui.confirm("There has been a new revision to the page, do you wish to continue?").done(function (revisionConfirm) {
if (responseOption.parameter != "") {
if (revisionConfirm) {
let template = "{{Edit COI|" + responseOption.parameter + "}}";
postCOIResponse(wikitext, editSummary, sectionIndex, watchPage, watchValue);
wikitext = wikitext.replace(/{{ *(Edit[ _])?COI(-protected|([ _](edit|request)){1,2})?( *\| *([=A-Z])*)* *}}/i, template);
}
}
});
if (responseOption.response != "") {
}
wikitext += "\n:{{subst:ECOI|" + responseOption.response + "}}";
});
wikitext += responseText.replaceAll(/\s*~~~~\s*/g, "") + " ~~~~";
}
if (responseOption.label == "Remove") {
wikitext = "";
editSummary = editSummary.replace(/[^]+\*\/ /, "");
}
statusMessage.setType("success");
statusMessage.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;
}});
});
}});
}
 
function postCOIResponse(wikitext, editSummary, sectionIndex, watchPage, watchValue) {
if (watchPage) {
if (watchValuewatchPage =!= "nochange") {
watchPage = "nochange";
} else {
watchPage = "watch";
}
Line 326 ⟶ 336:
}
let apiParams = {
action: 'edit',
title: mw.config.get("wgPageName"),
text: wikitext,
section: sectionIndex,
summary: editSummary,
watchlist: watchPage
};
if (watchPage == "watch") {
apiParams.watchlistexpiry = watchValue;
}
}
let reloadURL = "/w/index.php?title=" + encodeURI(mw.config.get("wgPageName")) + "&type=revision&diff=cur&oldid=prev";
new apimw.Api().postWithEditToken(apiParams).done(function () {
window.___location = reloadURL;
});
}
 
function ApiGetCOI(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]]