MediaWiki:AFC-submit-wizard.js: Difference between revisions

Content deleted Content added
update
m SD0001 moved page User:SD0001/AFC-submit-wizard.js to MediaWiki:AFC-submit-wizard.js: move to MediaWiki namespace so that it doesn't need to load the script from userspace
 
(30 intermediate revisions by 2 users not shown)
Line 1:
/**
* MediaWiki:AFCAfC-submit-wizard.js
*
* JavaScript used for submitting drafts to AfC.
* Used on [[Wikipedia:Articles for creation/Submitting]].
* Loaded via [[mw:Snippets/Load JS and CSS by URL]].
*
* Edits can be proposed via GitHub (https://github.com/wikimedia-gadgets/afc-submit-wizard)
* or a talk page request.
*
* Author: [[User:SD0001]]
Line 13 ⟶ 16:
/* globals mw, $, OO */
/* <nowiki> */
 
(function () {
 
$.when(
$.ready,
mw.loader.using([
'mediawiki.util', 'mediawiki.api', 'mediawiki.Title',
'mediawiki.widgets', 'oojs-ui-core', 'oojs-ui-widgets'
])
).then(function () {
if (mw.config.get('wgPageName') !== 'Wikipedia:Articles_for_creation/Submitting' ||
 
if ( mw.config.get('wgPageNamewgAction') !== 'Wikipedia:Articles_for_creation/Submittingview') {
return;
}
init();
});
if (mw.util.getParamValue('withJS') !== 'MediaWiki:AFC-submit-wizard.js') {
 
return;
var afc = {}, ui = {};
window.afc = afc;
afc.ui = ui;
 
var config = {
allowedNamespaces: [2, 118, 5], // User, Draft, WT
debounceDelay: 500,
redirectionDelay: 1000,
defaultAfcTopic: 'other'
};
 
// TODO: move to a separate JSON subpage, would be feasible once [[phab:T198758]] is resolved
var messages = {
"document-title": "Submitting your draft ...",
"page-title": "Submitting your draft ...",
"fieldset-label": "Submit your draft for review at Articles for Creation (AfC)",
"title-label": "Draft title",
"title-placeholder": "Enter the draft page name, usually begins with \"Draft:\"",
"title-helptip": "This should be pre-filled if you clicked the link while on the draft page",
"rawclass-label": "Choose the most appropriate category",
"rawclass-helptip": "For biographies about scholars, choose one of the two biography categories rather than one associated to their field",
"shortdesc-placeholder": "Briefly describe the subject in 2–5 words (eg. \"British astronomer\", \"Cricket stadium in India\")",
"shortdesc-label": "Short description",
"shortdesc-helptip": "Try not to exceed 40 characters",
"talktags-placeholder": "Start typing to search for tags ...",
"talktags-label": "WikiProject classification tags",
"talktags-helptip": "Adding the 1–4 most applicable WikiProjects is plenty. For example, if you add the Physics tag, you do not need to also add the Science tag.",
"orestopic-placeholder": "Start typing to search for topics ...",
"orestopic-label": "Topic classifiers",
"orestopic-helptip": "Pick the topic areas that are relevant",
"submit-label": "Submit",
"footer-text": "<small>If you are not sure about what to enter in a field, you can skip it. If you need help, you can ask at the <b>[[WP:AFCHD|AfC help desk]]</b> or get live help via <b>[[WP:IRCHELP|IRC]]</b> or <b>[[WP:DISCORD|Discord]]</b>.<br>Facing some issues in using this form? <b>[/w/index.php?title=Wikipedia_talk:WikiProject_Articles_for_creation/Submission_wizard&action=edit&section=new&preloadtitle=Issue%20with%20submission%20form&editintro=Wikipedia_talk:WikiProject_Articles_for_creation/Submission_wizard/editintro Report it]</b>.</small>",
"submitting-as": "Submitting as User:$1",
"validation-notitle": "Please enter the draft page name",
"validation-invalidtitle": "Please check draft title. This title is invalid.",
"validation-missingtitle": "Please check draft title. No such draft exists.",
"validation-wrongns": "Please check draft title – it should begin with \"Draft:\" or \"User:\"",
"warning-norefs": "This draft doesn't appear to contain any references. Please add references, without which it is likely to be declined. See [[Help:Introduction to referencing with Wiki Markup/2|help on adding references]].",
"status-processing": "Processing ...",
"status-saving": "Saving draft page ...",
"editsummary-main": "Submitting using [[WP:AFCSW|AfC-submit-wizard]]",
"status-redirecting": "Submission succeeded. Redirecting you to the draft page ...",
"captcha-label": "Please enter the letters appearing in the box below",
"captcha-placeholder": "Enter the letters here",
"captcha-helptip": "CAPTCHA security check. Click \"Submit\" again when done.",
"error-saving-main": "An error occurred ($1). Please try again or refer to the help desk.",
"status-saving-talk": "Saving draft talk page ...",
"editsummary-talk": "Adding WikiProject tags using [[WP:AFCSW|AfC-submit-wizard]]",
"status-talk-success": "Successfully added WikiProject tags to talk page",
"error-saving-talk": "An error occurred in editing the talk page ($1).",
"error-main": "An error occurred ($1). Please try again or refer to the help desk."
};
 
function init() {
for (var key in messages) {
mw.messages.set('afcsw-' + key, messages[key]);
}
 
document.title = msg('document-title');
$('#firstHeading').text('Submitting your draft ...');
$('#firstHeading').text(msg('page-title'));
document.title = 'Submitting your draft ...';
mw.util.addCSS(
// CSS adjustments for vector-2022: hide prominent page controls which are
// irrelevant and confusing while using the wizard
'.vector-page-toolbar { display: none } ' +
'.vector-page-titlebar #p-lang-btn { display: none } ' +
// Hide categories as well, prevents accidental HotCat usage
'#catlinks { display: none } '
);
 
var apiOptions = {
Line 47 ⟶ 118:
// Two different API objects so that aborts on the lookupApi don't stop the final
// evaluate process
var lookupApiafc.api = new mw.Api(apiOptions),;
submitApi afc.lookupApi = new mw.Api(apiOptions);
 
constructUI();
var draftLayout, talkTagsLayout, shortdescLayout, topicsLayout, submitLayout, draftInput, talkTagsInput, shortdescInput, topicsInput, submitButton, mainStatusLayout, mainStatusArea, talkStatusLayout, talkStatusArea, rawClassLayout, rawClass;
}
 
function constructUI() {
// global
var pagetext, talktext, oresTopics;
 
ui.fieldset = new OO.ui.FieldsetLayout({
// Create the UI
label: msg('fieldset-label'),
var fieldset = new OO.ui.FieldsetLayout({
classes: [ 'container' ],
label: 'Submit your draft for review at Articles for Creation (AfC)',
classes: ['container'],
items: [
draftLayoutui.titleLayout = new OO.ui.FieldLayout(draftInputui.titleInput = new mw.widgets.TitleInputWidget({
value: (mw.util.getParamValue('draftpage') || '').replace(/_/g, ' '),
placeholder: msg('Enter the draft title, begins with "Draft:" or "User:"-placeholder'),
}), {
label: msg('Draft title-label'),
align: 'top',
help: msg('title-helptip'),
help: 'This should be pre-filled if you clicked the link while on the draft page',
helpInline: true
}),
 
rawClassLayoutui.afcTopicLayout = new OO.ui.FieldLayout(rawClassui.afcTopicInput = new OO.ui.RadioSelectInputWidget(), {
label: msg('Choose the most appropriate categoryrawclass-label'),
help: msg('rawclass-helptip'),
help: 'For biographies about scholars, choose one of the two biography categories rather than one associated to their field',
align: 'inline',
}),
 
ui.shortdescLayout = new OO.ui.FieldLayout(ui.shortdescInput = new OO.ui.TextInputWidget({
placeholder: msg('shortdesc-placeholder'),
placeholder: 'Briefly describe the subject in 2–5 words (eg. "British astronomer", "Cricket stadium in India")',
maxLength: 100
}), {
label: msg('Short descriptionshortdesc-label'),
align: 'top',
help: msg('Try not to exceed 40 charactersshortdesc-helptip'),
helpInline: true,
}),
 
ui.talkTagsLayout = new OO.ui.FieldLayout(ui.talkTagsInput = new OO.ui.MenuTagMultiselectWidget({
placeholder: msg('Start typing to search for tags ...talktags-placeholder'),
tagLimit: 10,
autocomplete: false,
Line 95 ⟶ 165:
}).appendTo('body')
}), {
label: msg('WikiProject classification tagstalktags-label'),
align: 'top',
help: msg('talktags-helptip'),
help: 'Adding the 1–4 most applicable WikiProjects is plenty. For example, if you add the Physics tag, you do not need to also add the Science tag.',
helpInline: true,
}),
 
// This is shown only if the ORES topic lookup fails, or is inconclusive
topicsLayoutui.oresTopicLayout = new OO.ui.FieldLayout(topicsInputui.oresTopicInput = new OO.ui.MenuTagMultiselectWidget({
placeholder: msg('Start typing to search for topics ...orestopic-placeholder'),
tagLimit: 10,
autocomplete: false, // XXX: doesn't seem to work
options: [ "biography", "women", "food-and-drink", "internet-culture", "linguistics", "literature", "books", "entertainment", "films", "media", "music", "radio", "software", "television", "video-games", "performing-arts", "philosophy-and-religion", "sports", "architecture", "comics-and-anime", "fashion", "visual-arts", "geographical", "africa", "central-africa", "eastern-africa", "northern-africa", "southern-africa", "western-africa", "central-america", "north-america", "south-america", "asia", "central-asia", "east-asia", "north-asia", "south-asia", "southeast-asia", "west-asia", "eastern-europe", "europe", "northern-europe", "southern-europe", "western-europe", "oceania", "business-and-economics", "education", "history", "military-and-warfare", "politics-and-government", "society", "transportation", "biology", "chemistry", "computing", "earth-and-environment", "engineering", "libraries-and-information", "mathematics", "medicine-and-health", "physics", "stem", "space", "technology" ].map(function (e) {
return {
data: e,
Line 113 ⟶ 183:
})
}), {
label: msg('Topic classifiersorestopic-label'),
align: 'top',
help: msg('Pick the topic areas that are relevantorestopic-helptip'),
helpInline: true
}),
 
ui.submitLayout = new OO.ui.FieldLayout(ui.submitButton = new OO.ui.ButtonWidget({
label: msg('Submitsubmit-label'),
flags: [ 'progressive', 'primary' ],
})),
 
]
});
 
ui.footerLayout = new OO.ui.FieldLayout(new OO.ui.LabelWidget({
// Load a JSON page from the wiki
label: $('<div>')
function getJSONPage(page) {
.append(linkify(msg('footer-text')))
return $.getJSON('https://en.wikipedia.org/w/index.php?title=' + encodeURIComponent(page) + '&action=raw&ctype=text/json');
}), {
align: 'top'
});
 
afc.topicOptionsLoaded = getJSONPage('Wikipedia:WikiProject Articles for creation/AfC topic map.json').then(function (optionsJson) {
var topicOptionsLoaded = $.Deferred();
getJSONPage('Wikipedia:WikiProject Articles for creation/AFC topic map.json').then(function(optionsJson) {
var options = [];
$.each(optionsJson, function (code, info) {
options.push({
label: info.label,
Line 141 ⟶ 211:
});
});
rawClassui.afcTopicInput.setOptions(options);
rawClassui.afcTopicInput.setValue('o'config.defaultAfcTopic);
 
// putresolve promise with allowed option codes in promise resolution:
topicOptionsLoaded.resolve(return options.map(function (op) {
return op.data;
}));
});
 
topicsLayoutui.oresTopicLayout.toggle(false);
 
var asUser = mw.util.getParamValue('username');
if (asUser && asUser !== mw.config.get('wgUserName')) {
ui.fieldset.addItems([
new OO.ui.FieldLayout(new OO.ui.MessageWidget({
type: 'notice',
inline: true,
label: msg('Submitting submitting-as User:' +, asUser)
}))
], /* position */ 65); // just before submit button
}
 
// Attach
$('.mw-ui-button').parent().replaceWith(fieldset.$element);
$('#afc-submit-wizard-container').empty().append(ui.fieldset.$element, ui.footerLayout.$element);
mw.track('counter.gadget_afcsw.opened');
 
// populatePopulate talk page tags for multi-select widget
afc.talkTagOptionsLoaded = getJSONPage('Wikipedia:WikiProject Articles for creation/WikiProject templates.json').then(function (data) {
var talkTagOptionsLoaded = $.Deferred();
ui.talkTagsInput.addOptions(Object.keys(data).map(function (k) {
getJSONPage('Wikipedia:WikiProject Articles for creation/WikiProject templates.json').then(function (data) {
talkTagsInput.addOptions(Object.keys(data).map(function (k) {
return {
data: data[k],
Line 174 ⟶ 246:
};
}));
talkTagOptionsLoaded.resolve();
});
 
ui.clearTalkTags = function () {
afc.talkTagOptionsLoaded.then(function () {
ui.talkTagsInput.setValue([]);
});
};
ui.addTalkTags = function (tags) {
afc.talkTagOptionsLoaded.then(function () {
ui.talkTagsInput.setValue(ui.talkTagsInput.getValue().concat(tags));
});
};
 
// Get mapping of infoboxes with relevant WikiProjects
afc.ibxmapLoaded = getJSONPage('Wikipedia:WikiProject Articles for creation/Infobox WikiProject map.json');
var ibxmapLoaded = $.Deferred();
getJSONPage('Wikipedia:WikiProject Articles for creation/Infobox WikiProject map.json').then(function (data) {
ibxmapLoaded.resolve(data);
});
 
submitButtonui.$elementsubmitButton.on('click', evaluatehandleSubmit);
draftInputui.titleInput.on('change', mw.util.debounce(config.debounceDelay, onDraftInputChange));
 
if (mw.util.getParamValue('draftpage')) {
onDraftInputChange();
}
Line 193 ⟶ 272:
mw.util.addCSS('.skin-modern .projectTagOverlay, .skin-monobook .projectTagOverlay { font-size: 130%; }');
 
afc.beforeUnload = function onDraftInputChange(e) {
e.preventDefault();
lookupApi.abort(); // abort older API requests
e.returnValue = '';
return '';
};
$(window).on('beforeunload', afc.beforeUnload);
}
 
function onDraftInputChange() {
var drafttitle = draftInput.getValue().trim();
afc.lookupApi.abort(); // abort older API requests
if (!drafttitle) { // empty
return;
}
 
console.log('draft var inputdrafttitle changed:= "' + draftInputui.titleInput.getValue() + '"'.trim();
if (!drafttitle) { // empty
return;
}
debug('draft input changed: "' + ui.titleInput.getValue() + '"');
 
// re-initialize
draftLayout ui.titleLayout.setErrors([]);
draftLayout ui.titleLayout.setWarnings([]);
afc.oresTopics = null;
afc.talktext = null;
afc.pagetext = null;
ui.clearTalkTags();
 
afc.lookupApi.get({
talkTagOptionsLoaded.then(function () {
"action": "query",
talkTagsInput.setValue([]);
"prop": "revisions|description|info",
});
"titles": drafttitle,
"rvprop": "content",
"rvslots": "main"
}).then(setPrefillsFromPageData);
 
var titleObj = mw.Title.newFromText(drafttitle);
lookupApi.get({
if (!titleObj || titleObj.isTalkPage()) {
"action": "query",
return;
"prop": "revisions|description|info",
}
"titles": drafttitle,
var talkpagename = titleObj.getTalkPage().toText();
"rvprop": "content",
afc.lookupApi.get({
"rvslots": "main"
"action": "query",
}).then(function (json) {
"prop": "revisions",
console.log(json);
"titles": talkpagename,
var page = json.query.pages[0];
"rvprop": "content",
var preNormalizedTitle = json.query.normalized && json.query.normalized[0] &&
"rvslots": "main",
json.query.normalized[0].from;
}).then(setPrefillsFromTalkPageData);
console.log('page.title: "' + page.title + '"');
if (draftInput.getValue() !== (preNormalizedTitle || page.title)) {
return; // user must have changed the title already
}
if (!page || page.invalid) {
draftLayout.setErrors(['Please check draft title. This title is invalid.']);
return;
}
if (page.missing) {
draftLayout.setErrors(['Please check draft title. No such draft exists.']);
return;
}
pagetext = page.revisions[0].slots.main.content;
 
}
// Show no refs warning
 
if (!/<ref>/.test(pagetext) && !/\{\{[Ss]fn\}\}/.test(pagetext)) {
function setPrefillsFromPageData(json) {
draftLayout.setWarnings([
debug('page fetch query', json);
new OO.ui.HtmlSnippet('This draft doesn\'t appear to contain any references. Please add references, without this it will almost certainly be declined. See <a href="/wiki/Help:Introduction_to_referencing_with_Wiki_Markup/2" target="_blank">help on adding references</a>.')
var page = json.query.pages[0];
]);
var preNormalizedTitle = json.query.normalized && json.query.normalized[0] &&
}
json.query.normalized[0].from;
debug('page.title: "' + page.title + '"');
// set main category
if (ui.titleInput.getValue() !== (preNormalizedTitle || page.title)) {
var topicMatch = pagetext.match(/\{\{AFC topic\|(.*?)\}\}/);
return; // user must have changed the title already
if (topicMatch) {
}
topicOptionsLoaded.then(function(allowedCodes) {
var errors = errorsFromPageData(page);
var topic = topicMatch[1];
if (errors.length) {
console.log(topic);
ui.titleLayout.setErrors(errors);
console.log(allowedCodes);
return;
// if the code found in the template is an invalid one, keep the default to "other",
}
// rather than the first item in the list
ui.titleLayout.setWarnings(warningsFromPageData(page));
if (allowedCodes.indexOf(topic) !== -1) {
 
rawClass.setValue(topic);
afc.pagetext = page.revisions[0].slots.main.content;
} else {
 
rawClass.setValue('o');
// Set AfC topic category
}
var topicMatch = afc.pagetext.match(/\{\{AfC topic\|(.*?)\}\}/);
});
if (topicMatch) {
afc.topicOptionsLoaded.then(function(allowedCodes) {
var topic = topicMatch[1];
debug("Allowed topic codes fetched:", allowedCodes);
debug("AfC topic found:", topic);
// if the code found in the template is an invalid one, keep the default to "other",
// rather than the first item in the list
if (allowedCodes.indexOf(topic) !== -1) {
ui.afcTopicInput.setValue(topic);
} else {
rawClassui.afcTopicInput.setValue('o'config.defaultAfcTopic);
}
});
} else {
ui.afcTopicInput.setValue(config.defaultAfcTopic);
}
 
// setSet shortdescshort description in form
ui.shortdescInput.setValue(page.description || '');
 
// guessGuess wikiprojectWikiProject tags from infoboxes on the page
$ afc.when(ibxmapLoaded, talkTagOptionsLoaded).then(function (ibxmap) {
var infoboxRgx = /\{\{([Ii]nfobox [^|}]*)/g,
wikiprojects = [],
match;
while (match = infoboxRgx.exec(afc.pagetext)) { // jshint ignore:line
var ibx = match[1].trim();
ibx = ibx[0].toUpperCase() + ibx.slice(1);
if (ibxmap[ibx]) {
if (ibxmap[ibx]) {
wikiprojects = wikiprojects.concat(ibxmap[ibx]);
}
}
debug('wikiprojects from infobox: ', wikiprojects);
ui.addTalkTags(wikiprojects);
});
 
// Fill ORES topics
getOresTopics(page.lastrevid).then(function (topics) {
debug('ORES topics: ', topics);
if (!topics || !topics.length) { // unexpected API response or API returns unsorted
ui.oresTopicLayout.toggle(true);
} else {
ui.oresTopicLayout.toggle(false);
afc.oresTopics = topics;
}
}, function () {
ui.oresTopicLayout.toggle(true);
});
}
 
function setPrefillsFromTalkPageData (json) {
var talkpage = json.query.pages[0];
if (!talkpage || talkpage.missing) {
return;
}
afc.talktext = talkpage.revisions[0].slots.main.content;
debug(afc.talktext);
 
var existingWikiProjects = extractWikiProjectTagsFromText(afc.talktext);
var existingTags = existingWikiProjects.map(function (e) {
return e.name;
});
debug(existingTags);
ui.addTalkTags(existingTags);
}
 
/**
* @param {Object} page - from query API response
* @returns {string[]}
*/
function errorsFromPageData(page) {
if (!page || page.invalid) {
return [msg('validation-invalidtitle')];
}
if (page.missing) {
return [msg('validation-missingtitle')];
}
if (config.allowedNamespaces.indexOf(page.ns) === -1) {
return [msg('validation-wrongns')];
}
return [];
}
 
/**
* @param {Object} page - from query API response
* @returns {string[]}
*/
function warningsFromPageData(page) {
var pagetext = page.revisions[0].slots.main.content;
 
var warnings = [];
 
// Show no refs warning
if (!/<ref/i.test(pagetext) && !/\{\{([Ss]fn|[Hh]arv)/.test(pagetext)) {
warnings.push('warning-norefs');
}
 
// TODO: Show warning for use of deprecated/unreliable sources
// TODO: Show tip for avoiding peacock words or promotional language?
 
return warnings.map(function (warning) {
return new OO.ui.HtmlSnippet(linkify(msg(warning)));
});
}
 
/**
* @param {number} revid
* @returns {jQuery.Promise<string[]>}
*/
function getOresTopics(revid) {
return $.get('https://ores.wikimedia.org/v3/scores/enwiki/?models=drafttopic&revids=' + revid).then(function (json) {
 
// null is returned if at any point something in the API output is unexpected
// ES2020 has optional chaining, but of course on MediaWiki we're still stuck with ES5
return json &&
json.enwiki &&
json.enwiki.scores &&
json.enwiki.scores[revid] &&
json.enwiki.scores[revid].drafttopic &&
json.enwiki.scores[revid].drafttopic.score &&
(json.enwiki.scores[revid].drafttopic.score.prediction instanceof Array) &&
json.enwiki.scores[revid].drafttopic.score.prediction.map(function (topic, idx, topics) {
// Remove Asia.Asia* if Asia.South-Asia is present (example)
if (topic.slice(-1) === '*') {
var metatopic = topic.split('.').slice(0, -1).join('.');
for (var i = 0; i < topics.length; i++) {
if (topics[i] !== topic && topics[i].startsWith(metatopic)) {
return;
}
}
return metatopic.split('.').pop();
}
return topic.split('.').pop();
console.log('wikiprojects from infobox: ', wikiprojects);
})
console.log('setValue1:', talkTagsInput.getValue().concat(wikiprojects));
.filter(function (e) {
talkTagsInput.setValue(talkTagsInput.getValue().concat(wikiprojects));
return e; // filter out undefined from above
})
.map(function (topic) {
// convert topic string to normalised form
return topic
.replace(/[A-Z]/g, function (match) {
return match[0].toLowerCase();
})
.replace(/ /g, '-')
.replace(/&/g, 'and');
});
});
}
 
/***
// fill ORES topics
* @param {string} text
getOresTopics(page.lastrevid).then(function (topics) {
* @returns {{wikitext: string, name: string}[]}
console.log('ORES topics: ', topics);
*/
if (!topics || !topics.length) { // unexpected API response or API returns unsorted
function extractWikiProjectTagsFromText(text) {
topicsLayout.toggle(true);
if (!text) {
} else {
return [];
topicsLayout.toggle(false);
}
oresTopics = topics;
}
}, function () {
topicsLayout.toggle(true);
});
 
// this is best-effort, no guaranteed accuracy
var existingTags = [];
var rgx = /\{\{(WikiProject [^|}]*).*?\}\}/g;
var match;
while (match = rgx.exec(text)) { // jshint ignore:line
var tag = match[1].trim();
if (tag === 'WikiProject banner shell') {
continue;
}
existingTags.push({
wikitext: match[0],
name: tag
});
}
return existingTags;
}
 
/**
* @param {string} type
* @param {string} message
*/
function setMainStatus(type, message) {
if (!ui.mainStatusLayout || !ui.mainStatusLayout.isElementAttached()) {
ui.fieldset.addItems([
ui.mainStatusLayout = new OO.ui.FieldLayout(ui.mainStatusArea = new OO.ui.MessageWidget())
]);
}
ui.mainStatusArea.setType(type);
ui.mainStatusArea.setLabel(message);
}
 
var titleObj = mw.Title.newFromText(drafttitle);
if (!titleObj || titleObj.isTalkPage()) {
return;
}
var talkpagename = titleObj.getTalkPage().toText();
console.log(talkpagename);
lookupApi.get({
"action": "query",
"prop": "revisions",
"titles": talkpagename,
"rvprop": "content",
"rvslots": "main",
}).then(function (json) {
var talkpage = json.query.pages[0];
if (!talkpage || talkpage.missing) {
return;
}
talktext = talkpage.revisions[0].slots.main.content;
console.log(talktext);
 
/**
var existingWikiProjects = extractWikiProjectTagsFromText(talktext);
* @param {string} type
var existingTags = existingWikiProjects.map(function (e) {
* @param {string} message
return e.name;
*/
});
function setTalkStatus(type, message) {
talkTagOptionsLoaded.then(function () {
if (!ui.talkStatusLayout) {
console.log('setValue2:', talkTagsInput.getValue().concat(existingTags));
ui.fieldset.addItems([
talkTagsInput.setValue(talkTagsInput.getValue().concat(existingTags));
ui.talkStatusLayout = new OO.ui.FieldLayout(ui.talkStatusArea = new OO.ui.MessageWidget())
});
]);
}
ui.talkStatusArea.setType(type);
ui.talkStatusArea.setLabel(message);
}
 
function handleSubmit() {
console.log(existingTags);
 
setMainStatus('notice', msg('status-processing'));
});
mw.track('counter.gadget_afcsw.submit_attempted');
ui.submitButton.setDisabled(true);
ui.mainStatusLayout.scrollElementIntoView();
 
var draft = ui.titleInput.getValue();
if (!draft) {
ui.titleLayout.setErrors([msg('validation-notitle')]);
ui.fieldset.removeItems([ui.mainStatusLayout]);
ui.submitButton.setDisabled(false);
ui.titleLayout.scrollElementIntoView();
return;
}
debug(draft);
 
afc.api.get({
function getOresTopics(revid) {
"action": "query",
return $.get('https://ores.wikimedia.org/v3/scores/enwiki/?models=drafttopic&revids=' + revid).then(function (json) {
"prop": "revisions|description",
"titles": draft,
"rvprop": "content",
"rvslots": "main",
}).then(function (json) {
var apiPage = json.query.pages[0];
 
var errors = errorsFromPageData(apiPage);
// null is returned if at any point something in the API output is unexpected
if (errors.length) {
// ES2020 has optional chaining, but of course on MediaWiki we're still stuck with ES5
ui.titleLayout.setErrors(errors);
return json &&
ui.fieldset.removeItems([ui.mainStatusLayout]);
json.enwiki &&
ui.submitButton.setDisabled(false);
json.enwiki.scores &&
ui.titleLayout.scrollElementIntoView();
json.enwiki.scores[revid] &&
return;
json.enwiki.scores[revid].drafttopic &&
}
json.enwiki.scores[revid].drafttopic.score &&
 
(json.enwiki.scores[revid].drafttopic.score.prediction instanceof Array) &&
var text = prepareDraftText(apiPage);
json.enwiki.scores[revid].drafttopic.score.prediction.map(function (topic, idx, topics) {
 
// Remove Asia.Asia* if Asia.South-Asia is present (example)
setMainStatus('notice', msg('status-saving'));
if (topic.slice(-1) === '*') {
saveDraftPage(draft, text).then(function () {
var metatopic = topic.split('.').slice(0, -1).join('.');
setMainStatus('success', msg('status-redirecting'));
for (var i = 0; i < topics.length; i++) {
mw.track('counter.gadget_afcsw.submit_succeeded');
if (topics[i] !== topic && topics[i].startsWith(metatopic)) {
 
return;
$(window).off('beforeunload', afc.beforeUnload);
}
setTimeout(function () {
}
___location.href = mw.util.getUrl(draft);
return metatopic.split('.').pop();
}, config.redirectionDelay);
}
}, function (code, err) {
return topic.split('.').pop();
if (code === 'captcha') {
})
ui.fieldset.removeItems([ui.mainStatusLayout, ui.talkStatusLayout]);
.filter(function (e) {
ui.captchaLayout.scrollElementIntoView();
return e; // filter out undefined from above
mw.track('counter.gadget_afcsw.submit_captcha');
})
.map(function} (topic)else {
setMainStatus('error', msg('error-saving-main', makeErrorMessage(code, err)));
// convert topic string to normalised form
mw.track('counter.gadget_afcsw.submit_failed');
return topic
mw.track('counter.gadget_afcsw.submit_failed_' + code);
.replace(/[A-Z]/g, function (match) {
}
return match[0].toLowerCase();
ui.submitButton.setDisabled(false);
})
.replace(/ /g, '-')
.replace(/&/g, 'and');
});
});
}
 
var talktext = prepareTalkText(afc.talktext);
function extractWikiProjectTagsFromText(text) {
if (!textafc.talktext && !talktext) {
// No content earlier, no content now. Stop here to avoid
return [];
// creating the talk page as empty.
return;
}
 
setTalkStatus('notice', msg('status-saving-talk'));
// this is best-effort, no guaranteed accuracy
afc.api.postWithEditToken({
var existingTags = [];
"action": "edit",
var rgx = /\{\{(WikiProject [^|}]*).*?\}\}/g;
"title": new mw.Title(draft).getTalkPage().toText(),
var match;
"text": talktext,
while (match = rgx.exec(text)) { // jshint ignore:line
"summary": msg('editsummary-talk')
var tag = match[1].trim();
}).then(function (data) {
if (tag === 'WikiProject banner shell') {
if (data.edit && data.edit.result === 'Success') {
continue;
setTalkStatus('success', msg('status-talk-success'));
} else {
return $.Deferred().reject('unexpected result');
}
}).catch(function (code, err) {
existingTags.push({
setTalkStatus('error', msg('error-saving-talk', makeErrorMessage(code, err)));
wikitext: match[0],
});
name: tag
 
});
 
}
}).catch(function (code, err) {
return existingTags;
setMainStatus('error', msg('error-main', makeErrorMessage(code, err)));
ui.submitButton.setDisabled(false);
mw.track('counter.gadget_afcsw.submit_failed');
mw.track('counter.gadget_afcsw.submit_failed_' + code);
});
 
}
 
function saveDraftPage(title, text) {
 
// TODO: handle edit conflict
var editParams = {
"action": "edit",
"title": title,
"text": text,
"summary": msg('editsummary-main')
};
if (ui.captchaLayout && ui.captchaLayout.isElementAttached()) {
editParams.captchaid = afc.captchaid;
editParams.captchaword = ui.captchaInput.getValue();
ui.fieldset.removeItems([ui.captchaLayout]);
}
return afc.api.postWithEditToken(editParams).then(function (data) {
if (!data.edit || data.edit.result !== 'Success') {
if (data.edit && data.edit.captcha) {
// Handle captcha for non-confirmed users
 
var url = data.edit.captcha.url;
function evaluate() {
afc.captchaid = data.edit.captcha.id; // abuse of global?
ui.fieldset.addItems([
ui.captchaLayout = new OO.ui.FieldLayout(ui.captchaInput = new OO.ui.TextInputWidget({
placeholder: msg('captcha-placeholder'),
required: true
}), {
warnings: [ new OO.ui.HtmlSnippet('<img src=' + url + '>') ],
label: msg('captcha-label'),
align: 'top',
help: msg('captcha-helptip'),
helpInline: true,
}),
], /* position */ 6); // just after submit button
// TODO: submit when enter key is pressed in captcha field
 
return $.Deferred().reject('captcha');
if (!mainStatusLayout || !mainStatusLayout.isElementAttached()) {
 
fieldset.addItems([
} else {
mainStatusLayout = new OO.ui.FieldLayout(mainStatusArea = new OO.ui.MessageWidget({
return $.Deferred().reject('unexpected-result');
type: 'notice',
}
label: 'Processing ...'
}))
]);
}
});
}
 
/**
var draft = draftInput.getValue();
* @param {Object} page - page information from the API
console.log(draft);
* @returns {string} final draft page text to save
*/
function prepareDraftText(page) {
var text = page.revisions[0].slots.main.content;
 
var header = '';
submitApi.get({
"action": "query",
"prop": "revisions",
"titles": draft,
"rvprop": "content",
"rvslots": "main"
}).then(function (json) {
var page = json.query.pages[0];
if (!page || page.invalid || page.missing) {
draftLayout.setErrors(['Please check draft title. No such draft exists.']);
fieldset.removeItems([mainStatusLayout]);
return;
}
var text = page.revisions[0].slots.main.content;
 
// Handle short description
var header = '';
var shortDescTemplateExists = /\{\{[Ss]hort ?desc(ription)?\s*\|/.test(text);
var shortDescExists = !!page.description;
var existingShortDesc = page.description;
 
if (ui.shortdescInput.getValue()) {
// add shortdesc
// 1. No shortdesc - insert the one provided by user
if (shortdescInput.getValue()) {
if (!shortDescExists) {
text = text.replace(/\{\{[Ss]hort description\|.*?\}\}\n*/g, '');
header += '{{Short description|' + ui.shortdescInput.getValue() + '}}\n';
}
 
// 2. Shortdesc exists from {{short description}} template - replace it
// draft topics
} else if (shortDescExists && shortDescTemplateExists) {
console.log(topicsInput);
text = text.replace(/\{\{[Ss]hort ?desc(ription)?\s*\|.*?\}\}\n*/g, '');
header += '{{Short description|' + ui.shortdescInput.getValue() + '}}\n';
 
// 3. Shortdesc exists, but not generated by {{short description}}. If the user
if (topicsLayout.isVisible()) {
// has changed the value, save the new value
oresTopics = topicsInput.getValue();
} else if (shortDescExists && existingShortDesc !== ui.shortdescInput.getValue()) {
}
header += '{{Short description|' + ui.shortdescInput.getValue() + '}}\n';
if (oresTopics.length) {
text = text.replace(/\{\{[Dd]raft topics\|.*?\}\}\n*/g, '');
header += '{{Draft topics|' + oresTopics.join('|') + '}}\n';
}
 
// 4. Shortdesc exists, but not generated by {{short description}}, and user hasn't changed the value
text = text.replace(/\{\{AFC topic\|(.*?)\}\}/g, '');
} else {
header += '{{AFC topic|' + rawClass.getValue() + '}}\n';
// Do nothing
}
} else {
// User emptied the shortdesc field (or didn't exist from before): remove any existing shortdesc.
// This doesn't remove any shortdesc that is generated by other templates
// Race condition (FIXME): if someone else added a shortdesc to the draft after this user opened the wizard,
// that shortdesc gets removed
text = text.replace(/\{\{[Ss]hort ?desc(ription)?\s*\|.*?\}\}\n*/g, '');
}
 
// put AFC submission template
header += '{{subst:submit|' + (mw.util.getParamValue('username') || mw.config.get('wgUserName')) + '}}\n';
 
// Draft topics
// insert everything to the top
debug(ui.oresTopicInput);
text = header + text;
if (ui.oresTopicLayout.isVisible()) {
afc.oresTopics = ui.oresTopicInput.getValue();
}
if (afc.oresTopics && afc.oresTopics.length) {
text = text.replace(/\{\{[Dd]raft topics\|.*?\}\}\n*/g, '');
header += '{{Draft topics|' + afc.oresTopics.join('|') + '}}\n';
}
 
// Add AfC topic
console.log(text);
text = text.replace(/\{\{AfC topic\|(.*?)\}\}/g, '');
header += '{{AfC topic|' + ui.afcTopicInput.getValue() + '}}\n';
 
// put AfC submission template
mainStatusArea.setType('notice');
header += '{{subst:submit|1=' + (mw.util.getParamValue('username') || '{{subst:REVISIONUSER}}') + '}}\n';
mainStatusArea.setLabel('Saving draft page ...');
 
// insert everything to the top
// saving draft page
text = header + text;
submitApi.postWithEditToken({
debug(text);
"action": "edit",
"title": draft,
"text": text,
"summary": 'Submitting using [[MediaWiki:AFC-submit-wizard.js|AFC-submit-wizard]])'
}).then(function (data) {
if (data.edit && data.edit.result === 'Success') {
mainStatusArea.setType('success');
mainStatusArea.setLabel('Submission succeeded. Redirecting you to the draft page ...');
 
return text;
setTimeout(function () {
}
___location.href = mw.util.getUrl(draft);
}, 1000);
} else {
return $.Deferred().reject('unexpected-result');
}
}).catch(function (err) {
mainStatusArea.setType('error');
mainStatusArea.setLabel('An error occurred (' + err + '). Please try again or refer to the help desk.');
});
 
fieldset.addItems([
talkStatusLayout = new OO.ui.FieldLayout(talkStatusArea = new OO.ui.MessageWidget({
type: 'notice',
label: 'Saving draft talk page ...'
}))
]);
 
/**
// Process text of the talk page
* @param {string} initialText - initial talk page text
var alreadyExistingWikiProjects = extractWikiProjectTagsFromText(talktext);
* @returns {string} - final talk page text to save
var alreadyExistingTags = alreadyExistingWikiProjects.map(function (e) {
*/
return e.name;
function prepareTalkText(initialText) {
});
var text = initialText;
var tagsToAdd = talkTagsInput.getValue().filter(function (tag) {
return alreadyExistingTags.indexOf(tag) === -1;
});
var tagsToRemove = alreadyExistingTags.filter(function (tag) {
return talkTagsInput.getValue().indexOf(tag) === -1;
});
 
// TODO: this can be improved to put tags within {{WikiProject banner shell}} (if already present or otherwise)
tagsToRemove.forEach(function (tag) {
var alreadyExistingWikiProjects = extractWikiProjectTagsFromText(text);
talktext = talktext.replace(new RegExp('\\{\\{\\s*' + tag + '\\s*(\\|.*?)?\\}\\}\\n?'), '');
var alreadyExistingTags = alreadyExistingWikiProjects.map(function (e) {
});
return e.name;
});
var tagsToAdd = ui.talkTagsInput.getValue().filter(function (tag) {
return alreadyExistingTags.indexOf(tag) === -1;
});
var tagsToRemove = alreadyExistingTags.filter(function (tag) {
return ui.talkTagsInput.getValue().indexOf(tag) === -1;
});
 
var tagsToAddText = tagsToAdd tagsToRemove.mapforEach(function (tag) {
returntext = text.replace(new RegExp('\\{\\{\\s*' + tag + '\\s*(\\|.*?)?\\}\\}\\n?'), '');
});
}).join('\n') + (tagsToAdd.length ? '\n' : '');
 
talktext = var tagsToAddText += tagsToAdd.map(talktextfunction || ''(tag); {
return '{{' + tag + '}}';
}).join('\n') + (tagsToAdd.length ? '\n' : '');
 
text = tagsToAddText + (text || '');
submitApi.postWithEditToken({
 
"action": "edit",
// remove |class=draft parameter in any WikiProject templates
"title": new mw.Title(draft).getTalkPage().toText(),
text = text.replace(/(\{\{wikiproject.*?)\|\s*class\s*=\s*draft\s*/gi, '$1');
"text": talktext,
 
"summary": 'Adding WikiProject tags using [[MediaWiki:AFC-submit-wizard.js|AFC-submit-wizard]])'
return text;
}).then(function (data) {
}
if (data.edit && data.edit.result === 'Success') {
 
talkStatusArea.setType('success');
/**
talkStatusArea.setLabel('Successfully added WikiProject tags to talk page');
* Load a JSON page from the wiki.
} else {
* Use API (instead of $.getJSON with action=raw) to take advantage of caching
return $.Deferred().reject('unexpected-result');
* @param {string} page
* @returns {jQuery.Promise<Record<string, any>>}
**/
function getJSONPage (page) {
return afc.api.get({
action: 'query',
titles: page,
prop: 'revisions',
rvprop: 'content',
rvlimit: 1,
rvslots: 'main',
uselang: 'content',
maxage: '3600', // 1 hour
smaxage: '3600',
formatversion: 2
}).then(function (json) {
var content = json.query.pages[0].revisions[0].slots.main.content;
return JSON.parse(content);
}).catch(function (code, err) {
console.error(makeErrorMessage(code, err));
});
}
 
/**
* Expands wikilinks and external links into HTML.
* Used instead of mw.msg(...).parse() because we want links to open in a new tab,
* and we don't want tags to be mangled.
* @param {string} input
* @returns {string}
*/
function linkify(input) {
return input
.replace(
/\[\[:?(?:([^|\]]+?)\|)?([^\]|]+?)\]\]/g,
function(_, target, text) {
if (!target) {
target = text;
}
return '<a target="_blank" href="' + mw.util.getUrl(target) +
}).catch(function (err) {
'" title="' + target.replace(/"/g, '&#34;') + '">' + text + '</a>';
talkStatusArea.setType('error');
}
talkStatusArea.setLabel('An error occurred in editing the talk page (' + err + ').');
});
// for ext links, display text should be given
.replace(
/\[(\S*?) (.*?)\]/g,
function (_, target, text) {
return '<a target="_blank" href="' + target + '">' + text + '</a>';
}
);
}
 
}).catch(function msg(errkey) {
var messageArgs = Array.prototype.slice.call(arguments, 1);
mainStatusArea.setType('error');
return mw.msg.apply(mw, ['afcsw-' + key].concat(messageArgs));
mainStatusArea.setLabel('An error occurred (' + err + '). Please try again or refer to the help desk.');
}
});
 
function makeErrorMessage(code, err) {
if (code === 'http') {
return 'http: there is no internet connectivity';
}
return code + (err && err.error && err.error.info ? ': ' + err.error.info : '');
}
 
function debug() {
});
Array.prototype.slice.call(arguments).forEach(function (arg) {
console.log(arg);
});
}
 
})(); // File-level closure to protect functions from being exposed to the global scope or overwritten
 
/* </nowiki> */