User:Captain Medusa alt/fork.js
Appearance
Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. This code will be executed when previewing this page. |
Documentation for this user script can be added at User:Captain Medusa alt/fork. |
// <nowiki>
//forked from User:SD0001/DYK-helper.js
//Credit goes to User:SD0001
var dyk = {};
window.dyk = dyk;
$.when(
mw.loader.using([ 'mediawiki.util', 'mediawiki.user', 'jquery.ui', 'jquery.tipsy' ]),
mw.loader.getScript( 'https://en.wikipedia.org/w/index.php?title=MediaWiki:Gadget-morebits.js&action=raw&ctype=text/javascript' ),
importStylesheet( 'mediawiki.ui.input", "text/css' ),
$.ready
).then(function() {
mw.loader.using( 'mediawiki.util', function () {
$(document).ready( function () {
var link = mw.util.addPortletLink ( 'p-views', '#', 'review', 'ca-DYK', 'Review this DYK');
$( '#ca-DYK' ).hide();
$( link ).click( function ( event ) {
event.preventDefault();
dyk.callback();
} );
$(document).on( "mousemove", check );
} );
} );
function check(){
//$(document).off( "mousemove", check );
if ( (window.location.href.indexOf("Template:Did_you_know_nominations/") > -1) && (mw.config.get( 'wgAction' ) === 'view' || mw.config.get( 'wgAction' ) === 'edit' ) ) {
$( '#ca-DYK' ).show();
}
}
dyk.config = {
version: '1.0.0',
advert: ' ([[User:Captain Medusa alt/fork.js|DYK-Reviwer]])'
};
dyk.callback = function dykMainCallback(e) {
e.preventDefault();
var Window = new Morebits.simpleWindow(1000, 500);
Window.setTitle( "Review this DYK" );
Window.setScriptName( "DYK-reviwer" );
Window.addFooterLink( "DYK rules", "WP:DYKRULES" );
var form = new Morebits.quickForm( dyk.evaluate );
form.append({
type: 'radio',
name: 'radio',
label: 'radio: ',
list: [
{ type: 'label', label: 'Green Tick (<small>No problems, ready for DYK</small>', value: 'ready for DYK', selected: true },
{ type: 'label', label: 'Blue Tick', value: 'ready for DYK' },
{ type: 'label', label: 'Query (<small>DYK eligibility requires that an issue be addressed</small>', value: 'question' },
{ type: 'label', label: 'Maybe (<small>DYK eligibility requires additional work.</small>', value: 'question' },
{ type: 'label', label: 'No', value: 'no' },
{ type: 'label', label: 'New review ', value: 'new' }
]
});
form.append({
type: 'input', // converted to date input below
label: 'Created/expanded on: ',
name: 'date',
tooltip: 'The date as of which creation/expansion has been completed. Must be within the past week. ',
value: new Date().toISOString().slice(0, 10), // YYYY-MM-DD format
event: dyk.dateCheck // for the benefit of browsers that don't support a datepicker for date fields
});
form.append({
type: 'checkbox',
list: [ {
name: 'multiarticle',
label: 'Multi-article nomination',
subgroup: {
type: 'input',
label: 'Article 2: ',
name: 'article2'
},
event: function addPlusbuttonArticle() {
if (document.getElementById('dyk-plusarticle') === null) { // happens only the first time
var plusbutton = dyk.createPlusButton('dyk-plusarticle');
plusbutton.addEventListener('click', function(e) {
var anchor = e.target.parentElement;
var num = parseInt(anchor.previousElementSibling.previousElementSibling.textContent.slice('Article '.length)) + 1;
var newDiv = new Morebits.quickForm.element({
type: 'input',
label: 'Article ' + num + ': ',
name: 'multiarticle.article' + num
}).render();
$(anchor).parent().after(newDiv);
newDiv.append(plusbutton);
newDiv.querySelector('input').focus();
});
$(result).find('[name="multiarticle.article2"]').after(plusbutton);
}
}
} ]
});
form.append({
type: 'textarea',
name: 'hook',
label: 'Hook: ',
tooltip: 'Should be concise, not more than 200 characters. See WP:DYKHOOK for guidelines. Do wikilink words in the hook and bold the link to the DYK article(s).',
value: '... that ',
className: 'dyk-hook'
}).append({
type: 'textarea',
name: 'source',
label: 'Source: ',
className: 'dyk-source',
tooltip: 'Source for the hook. You are strongly encouraged to quote the source text supporting the hook" (and [link] the source, or cite it briefly without using citation templates)'
});
form.append({
type: 'textarea',
name: 'ALT1',
label: 'ALT hook: ',
value: '... that ',
className: 'dyk-hook',
tooltip: 'Optional, but recommended'
}).append({
type: 'textarea',
name: 'source1',
label: 'Source: ',
className: 'dyk-source'
});
form.append({
type: 'button',
label: 'Add another hook',
name: 'anotherhook',
event: function addAnotherHook(e) {
var span = e.target.parentElement;
var num = parseInt(span.previousElementSibling.childNodes[1].name.slice('ALT'.length)) + 1;
var x = new Morebits.quickForm.element({
type: 'textarea',
name: 'ALT' + num,
label: 'ALT' + num + ' hook: ',
value: '... that ',
className: 'dyk-hook'
});
x.append({
type: 'textarea',
name: 'source' + num,
label: 'Source: ',
className: 'dyk-source'
});
$(span).before(x.render());
dyk.txtareaModifications(result['ALT' + num], 'hook');
dyk.txtareaModifications(result['source' + num], 'source');
}
});
form.append({
type: 'input',
name: 'author',
label: 'Author: ',
value: mw.config.get('wgUserName'),
tooltip: 'If nominating an article created by another editor, change this value',
style: 'padding-top: 8px'
});
form.append({
type: 'checkbox',
list: [ {
name: 'multiauthor',
label: 'Add additional authors',
subgroup: {
type: 'input',
label: 'Author 2: ',
name: 'author2'
},
event: function addPlusbuttonAuthor() {
if (document.getElementById('dyk-plusauthor') === null) {
var plusbutton = dyk.createPlusButton('dyk-plusauthor');
plusbutton.addEventListener('click', function(e) {
var anchor = e.target.parentElement;
var num = parseInt(anchor.previousElementSibling.previousElementSibling.textContent.slice('Author '.length)) + 1;
var newDiv = new Morebits.quickForm.element({
type: 'input',
label: 'Author ' + num + ': ',
name: 'multiauthor.author' + num
}).render();
$(anchor).parent().after(newDiv);
newDiv.append(plusbutton);
newDiv.querySelector('input').focus();
});
$(result).find('[name="multiauthor.author2"]').after(plusbutton);
}
}
} ]
});
form.append({
type: 'checkbox',
list: [ {
name: 'img',
label: 'Include image',
tooltip: 'Images must be free, and used in the article. See WP:DYKIMG',
subgroup: [ {
type: 'input',
label: 'Image name: ',
name: 'name',
size: '50px'
}, {
type: 'input',
label: 'Image caption: ',
name: 'caption',
size: '60px'
} ],
style: 'padding-top: 8px'
} ]
});
form.append({
type: 'input',
name: 'qpq',
label: 'Reviewed: ',
tooltip: 'DYK nomination you reviewed. This is compulsory for editors with 5+ DYK credits (QPQ requirement)',
size: '50px',
value: 'Template:Did you know nominations/'
}).append({
type: 'button',
label: 'find articles to review',
event: function() {
window.open('//en.wikipedia.org/wiki/Template_talk:Did_you_know#Nominations');
}
});
form.append({
type: 'textarea',
name: 'comments',
label: 'Comments ',
tooltip: 'Any additional comments (optional). Do not include signature.'
});
var previewlink = Morebits.htmlNode('a', 'Preview');
previewlink.style.cursor = "pointer";
$(previewlink).click(function() {
result.previewer.beginRender(dyk.getDiscussionWikitext(result), "API"); // |result| is defined below
});
form.append( { type: 'div', id: 'dykpreview', label: [ previewlink ] } );
form.append( { type: 'div', id: 'dyk-previewbox', style: 'display: none' } );
form.append( { type: 'submit', label: 'Submit' } );
var result = form.render();
Window.setContent( result );
Window.display();
result.previewer = new Morebits.wiki.preview(document.getElementById('dyk-previewbox'));
dyk.txtareaModifications(result.hook, 'hook');
dyk.txtareaModifications(result.ALT1, 'hook');
dyk.txtareaModifications(result.source, 'source');
dyk.txtareaModifications(result.source1, 'source');
dyk.txtareaModifications(result.comments, 'comments');
mw.util.addCSS(
'div.dyk-hook > textarea { font-size: 125%; height: 38px; }' +
'div.dyk-hook > label { font-weight: bold; margin-top: 1px black; }' +
'form.quickform div.dyk-source { display: table-row; }' +
'form.quickform div.dyk-source label { display: table-cell; vertical-align: middle; }' +
'div.dyk-source > textarea { font-size: 110%; height: 19px; }' +
'form.quickform textarea[name=comments] { font-size: 110%; height: 35px; }'
);
// Add date check element
var d = document.createElement('span');
d.style.color = 'red';
d.style.paddingLeft = '5px';
$('.quickform [name=date]').parent().append(d);
$('.quickform [name=date]')[0].type = 'date';
$('.quickform [name=date]').on('change', dyk.dateCheck);
};
dyk.dateCheck = function dykDateCheck(e) {
var checkElem = e.target.nextElementSibling;
var date = new Date(e.target.value);
var curDate = new Date();
var diff = curDate.getTime() - date.getTime();
if (date.toString() === 'Invalid date' || diff < 0) {
checkElem.textContent = 'Invalid date';
checkElem.style.color = 'red';
return;
}
var diffdays = diff/(1000*60*60*24);
if (diffdays >= 10) {
checkElem.textContent = 'Must be within the past week, see WP:DYK#New';
checkElem.style.color = '#fa3800e8';
} else if (diffdays >= 8) {
checkElem.textContent = 'Possibly ineligible as date is not within the past week';
checkElem.style.color = '#8f8946';
} else {
checkElem.textContent = '';
}
}
dyk.txtareaModifications = function dykTxtareaModifications(txtarea, type) {
var $txtarea = $(txtarea);
// replace h5 above textarea with label
$txtarea.prev().each(function(i, el) {
var newEl = $('<label>').text(el.textContent).append(el.childNodes[1]);
$(el).replaceWith(newEl);
});
if (type === 'source') {
var width = txtarea.parentElement.previousElementSibling.offsetWidth - txtarea.previousElementSibling.offsetWidth;
txtarea.style.width = width + 'px';
}
if (type !== 'hook') return;
// Add character counter
var stdiv = document.createElement('div');
stdiv.style.float = 'right';
stdiv.style.fontWeight = 'normal';
$txtarea.prev().append(stdiv);
$txtarea.on('keyup', function updateCharCount() {
var len = this.value
.replace(/^\.\.\. ?/, '') // remove ... in the beginning
.replace(/'''/g, '') // remove bold syntax
.replace(/''(\(.*?\))'' /, '') // remove italic text in brackets
.replace(/''/g, '') // remove any remaining italic syntax
.replace(/\[/g, '\1').replace(/\]/g, '\2') // remove link syntax and piped part - step 1
.replace(/\2\2/g, '') // step 2
.replace(/\1\1(?:[^\1\2]*?\|)?/g, '') // step 3
.length;
stdiv.textContent = len + ' characters';
if (len > 200) {
stdiv.style.color = 'red';
} else {
stdiv.style.color = '#222222'; // default morebits color
}
});
};
dyk.createPlusButton = function(id) {
var a = document.createElement('a');
a.id = id;
a.style.paddingLeft = '5px';
var img = document.createElement('img');
img.setAttribute('src', '//upload.wikimedia.org/wikipedia/commons/thumb/b/b9/Nuvola_action_edit_add.svg/20px-Nuvola_action_edit_add.svg.png');
img.setAttribute('alt', 'add another');
img.setAttribute('title', 'Add another');
a.append(img);
return a;
};
dyk.getDiscussionWikitext = function dykGetDiscussionWikitext(form) {
var params = {};
for (var i in form.elements) {
var el = form.elements[i];
if (el.type) {
if (el.type === 'checkbox') {
params[el.name] = el.checked;
} else if (el.type === 'select-one' || el.type === 'text' || el.type === 'textarea') {
params[el.name] = el.value;
}
}
}
var templatetext =
'{{subst:NewDYKnomination' +
' | article = ' + Morebits.pageNameNorm;
dyk.articles = [Morebits.pageNameNorm];
$('input[name^="multiarticle.article"]').each(function(i, el) {
templatetext += ' | ' + el.name.slice('multiarticle.'.length) + ' = ' + params[el.name];
dyk.articles.push(params[el.name]);
});
templatetext +=
' | status = ' + params.status +
' | hook = ' + params.hook + (params.source ? (' <small>Source: ' + params.source + '</small>') : '');
var ALTgiven = function(n) {
return params['ALT' + n] !== '' && !/^\.\.\. ?that ?$/.test(params['ALT' + n]);
};
$('textarea[name^="ALT"]').each(function(i, el) {
var n = el.name.slice('ALT'.length); // string form
if (ALTgiven(n)) {
templatetext += ' | ' + el.name + ' = ' + params[el.name] +
(params['source' + n] ? (' <small>Source: ' + params['source' + n] + '</small>') : '');
}
});
templatetext +=
' | author = ' + params.author;
$('input[name^="multiauthor.author"]').each(function(i, el) {
templatetext += ' | ' + el.name.slice('multiauthor.'.length) + ' = ' + params[el.name];
});
templatetext +=
' | image = ' + (params.img ? params['img.name'] : '') +
' | caption = ' + (params.img ? params['img.caption'] : '') +
' | comment = ' + params.comments +
' | reviewed = ' + (params.qpq !== 'Template:Did you know nominations/' ? '[[' + params.qpq + ']]' : '') +
'}}';
return templatetext;
};
dyk.evaluate = function dykEvaluate(e) {
var form = e.target;
var date = form.date.value;
// Validation
if (!date) {
alert('Please specify the date as of which creation/expansion has been completed');
return;
}
if (form.hook.value === '') {
alert('Please specify the hook for DYK nomination');
return;
}
var broken = false; // flag
var problem; // start or end
var problemhook;
var sourcewarning = false;
$(form).find('.dyk-hook > textarea').each(function(i, e) {
var isGiven = e.value !== '' && !/^\.\.\. ?that ?$/.test(e.value);
if (!isGiven) return true; // continue
e.value = e.value.trim();
if (!e.value.startsWith('... that ')) {
problem = 'start';
problemhook = e.name;
broken = true;
return false; // break
}
if (!e.value.endsWith('?')) {
problem = 'end';
problemhook = e.name;
broken = true;
return false;
}
if (e.nextElementSibling.childNodes[1].value === '') {
sourcewarning = true;
}
});
if (broken) {
alert('Hook ' + (problemhook === 'hook' ? '' : problemhook) + ' must ' + (problem === 'start' ? 'start with "... that "' : 'end with a question mark (?)'));
return;
}
// Date error handling, also done above for on keyup in input field
date = new Date(date);
var curDate = new Date();
var diff = curDate.getTime() - date.getTime();
if (date.toString() === 'Invalid date' || diff < 0) {
alert("Please specify a valid date");
return;
}
var diffdays = diff/(1000*60*60*24);
if (diffdays >= 10) {
alert('The date specified is well outside the past week, and hence the article is ineligible for DYK, see WP:DYK#New');
return;
}
if (diffdays >= 8 && !confirm('The date specified is not within the past week, see WP:DYK#New. Are you sure you want to continue?')) {
return;
}
var prosesizewarn = $('#dyk-prosesize').css('color') === "rgb(255, 0, 0)";
if (prosesizewarn && !confirm('This article has a readable prose size of less than 1500 characters. \n\nWhile you may still nominate it for DYK, it may be rejected unless you expand it to more than 1500 characters after the nomination. \n\nClick OK to continue with the nomination.' )) {
return;
}
if (sourcewarning && !confirm('You have not specified the source for each hook. Are you sure you want to continue?')) {
return;
}
var templatetext = dyk.getDiscussionWikitext(form);
Morebits.simpleWindow.setButtonsEnabled( false );
Morebits.status.init(form);
Morebits.wiki.actionCompleted.redirect = 'Template talk:Did you know#' + dyk.articles.join(', ');
Morebits.wiki.actionCompleted.notice = 'Completed';
var nompage = new Morebits.wiki.page('Template:Did you know nominations/' + Morebits.pageNameNorm, 'Creating nomination page');
nompage.setAppendText(templatetext);
nompage.setCreateOption('createonly');
nompage.setWatchlist(true);
nompage.setEditSummary('Creating DYK nomination for [[' + dyk.articles.join(']], [[') + ']]' + dyk.config.advert);
nompage.append(function onNominationSuccess() {
var dykpage = new Morebits.wiki.page('Template talk:Did you know', 'Adding nomination to Template talk:Did you know');
dykpage.load(function addNomToTTDYK(dykpage) {
var pageText = dykpage.getPageText();
var todaysHeader = 'Articles created/expanded on ' + date.getUTCMonthName() + ' ' + date.getUTCDate();
var re = new RegExp('(===' + todaysHeader + '===\n<!-- After you have created your nomination page, please add it \\(e.g., \\{\\{Did you know nominations/YOUR ARTICLE TITLE\\}\\}\\) to the TOP of this section \\(after this comment\\).-->)');
var newPageText = pageText.replace(re, '$1\n{{Did you know nominations/' + Morebits.pageNameNorm + '}}');
if (pageText === newPageText) {
var linknode = document.createElement('a');
linknode.setAttribute("href", mw.util.getUrl("User:SD0001/DYK-helper/Fixing nomination"));
linknode.appendChild(document.createTextNode('Repair nomination'));
dykpage.getStatusElement().error(['Could not find the target spot for the nomination. Please see: ', linknode, '.']);
return;
}
dykpage.setPageText(newPageText);
dykpage.setEditSummary('/* ' + todaysHeader + ' */ ' + 'Adding [[Template:Did you know nominations/' + Morebits.pageNameNorm + ']]' + dyk.config.advert);
dykpage.setMaxConflictRetries(3);
dykpage.save();
});
dyk.articles.forEach(function transcludeOnTalk(page) {
var talkpagename = 'Talk:' + page;
var talkpage = new Morebits.wiki.page(talkpagename, 'Transcluding nomination on ' + talkpagename);
talkpage.setAppendText('\n\n{{Did you know nominations/' + Morebits.pageNameNorm + '}}\n');
talkpage.setEditSummary('Nominated for DYK, see [[Template:Did you know nominations/' + Morebits.pageNameNorm + ']]' + dyk.config.advert);
talkpage.setCreateOption('recreate');
if (window.DYKH_watchlistTalkPage === undefined) {
talkpage.setWatchlistFromPreferences(true);
} else {
talkpage.setWatchlist(window.DYKH_watchlistTalkPage);
}
talkpage.append();
});
});
};
// </nowiki>
// </nowiki>