MediaWiki:AFC-add-project-tags.js
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
/**
* MediaWiki:AFC-add-project-tags.js
*
* Add WikiProject tags to draft talk page. Script for
* [[Wikipedia:WikiProject Articles for creation/Add WikiProject tags]],
* loaded via [[mw:Snippets/Load JS and CSS by URL]].
*
* Author: [[User:SD0001]]
* Licence: MIT
*
*/
// <nowiki>
var api;
$.when(
$.ready,
mw.loader.using(['mediawiki.util', 'mediawiki.api', 'mediawiki.widgets'])
).then(function () {
if (mw.config.get('wgPageName').indexOf('Wikipedia:WikiProject_Articles_for_creation/Add_WikiProject_tags') !== 0) {
return;
}
api = new mw.Api();
var titleInput = new mw.widgets.TitleInputWidget({
// get prefill value from the URL query string
value: (mw.util.getParamValue('title') || '')
// decode XML entities in it if any
.replace(/&#(\d );/g, function (_, numStr) {
return String.fromCharCode(parseInt(numStr, 10));
})
// replace underscores with spaces (just for tidiness)
.replace(/_/g, ' ')
});
var tagInput = new OO.ui.MenuTagMultiselectWidget({
placeholder: 'Start typing to search for tags ...',
tagLimit: 10,
autocomplete: false,
$overlay: $('<div>').addClass('projectTagOverlay').css({
'position': 'absolute',
'z-index': '110'
}).appendTo('body')
});
$('.mw-parser-output .mw-ui-progressive').parent().replaceWith(
$('<label>')
.text('Enter draft page title: '),
titleInput.$element
.css('margin-bottom', '8px'),
$('<label>')
.attr('for', 'draft-select')
.text('Select WikiProjects to tag with'),
$('<div>')
.append(tagInput.$element),
$('<button>')
.attr('id', 'draft-submit')
.addClass('mw-ui-button mw-ui-progressive')
.text('Add selected WikiProject tags')
.css('margin-top', '10px')
.on('click', evaluate),
$('<div>')
.attr('id', 'draft-status')
);
$.getJSON('https://en.wikipedia.org/w/index.php?title='
encodeURIComponent("Wikipedia:WikiProject_Articles_for_creation/WikiProject_templates.json")
'&action=raw&ctype=text/json'
).then(function (data) {
tagInput.addOptions(Object.keys(data).map(function (k) {
return {
data: data[k],
label: k
};
}));
});
function evaluate() {
$('#draft-status').text('Opening draft talk page ...').css('color', 'blue');
var draftTitle = titleInput.getValue();
var draft = mw.Title.newFromText(draftTitle);
if (!draft) {
$('#draft-status').text('Please check the draft page title.').css('color', 'red');
return;
}
if (draft.namespace !== 118 && draft.namespace !== 2) {
$('#draft-status').text('Please check the draft page title. It doesn\'t seem to be in draft namespace').css('color', 'red');
return;
}
api.get({
"action": "query",
"prop": "revisions",
"titles": [draft.toString(), draft.getTalkPage().toString()],
"formatversion": "2",
"rvprop": "content",
"rvslots": "main",
"rvsection": "0"
}).then(function(data) {
// verify that the draft exists
var subjectpage = data.query.pages.filter(function(pg) {
return pg.ns === 118
})[0];
if (!subjectpage || subjectpage.missing) {
$('#draft-status').text('Please check the draft page title. No such page exists.')
.css('color', 'red');
return;
}
// get list of tags already present on talk page
var existingTags = [];
var talkpage = data.query.pages.filter(function(pg) {
return pg.ns === 119;
})[0];
if (talkpage && !talkpage.missing) {
var talktext = talkpage.revisions[0].slots.main.content;
// this is best-effort, no guaranteed accuracy
var rgx = /\{\{(WikiProject [^|}]*)/g;
var match;
while (match = rgx.exec(talktext)) {
existingTags.push(match[1]);
}
}
var newTags = tagInput.getValue().filter(function(tag) {
return existingTags.indexOf(tag) === -1;
}).map(function (tag) {
return '{{' tag '}}'
}).join('\n');
// api.edit() doens't work if page doesn't exist originally
api.postWithEditToken({
"action": "edit",
"title": draft.getTalkPage().toString(),
"prependtext": newTags '\n',
"formatversion": "2",
"summary": 'Adding WikiProject tags ([[MediaWiki:AFC-add-project-tags.js|assisted]])'
}).then(function (data) {
if (data.edit && data.edit.result === 'Success') {
$('#draft-status').text('WikiProject tags added. Redirecting you to the draft talk page ...').css('color', 'green');
setTimeout(function () {
location.href = mw.util.getUrl(draft.getTalkPage().toString());
}, 1000);
} else {
return $.Deferred().reject('unexpected-result');
}
}).catch(function (err) {
$('#draft-status').text('An error occurred (' err ') Please try again.').css('color', 'red');
});
}).catch(function(err) {
$('#draft-status').text('An error occurred (' err ') Please try again.').css('color', 'red');
});
}
}).catch(console.log);
// </nowiki>