MediaWiki:ArchivePoll.js

/** * @name           ArchivePoll * @description    Add "Archive Poll" button to a poll and allow archiving poll * @author         KhangND */ (function(ArchivePoll) {   var $polls = $('.ajax-poll'),        isUser = mw.config.get('wgUserName') !== null;

if(window.ArchivePollLoaded || !$polls.length || !isUser) { return; } window.ArchivePollLoaded = true;

var api = new mw.Api, i18n = {}, config = $.extend({ archive: 'Project:Archived Polls' }, ArchivePoll);

const format = /\w+\s\d+,\s\d{4}|\d{2}:\d{2}/g, // datetime format (M d, yyyy|hh:ss) QUESTION = '.header', ANSWER = '.pollAnswerName', VOTE = '.pollAnswerVotes > span', TOTAL = '.total';

function init(i18n) { this.i18n = i18n._messages.en; for(var i in this.i18n) this.i18n[i] = i18n.msg(i).plain;

$polls.find('[type=submit]').after($(' ', { type: 'submit', value: i18n.button, click: archive }));   }

function archive { // retrieve poll details var thisPoll = $(this).parents('.ajax-poll'), answers = thisPoll.find(ANSWER), votes = thisPoll.find(VOTE), poll = { question: thisPoll.find(QUESTION).text.trim, datetime: thisPoll.find(TOTAL).parent.text.trim.match(format), total: thisPoll.find(TOTAL).text, vote: {} };       for (var i = 0; i < answers.length; i++) { var answer = $(answers[i]).text.trim, num = $(votes[i]).text; poll.vote[answer] = num; }

// create/edit archive page api.post({       	action: 'edit',        	title: config.archive,            token: mw.user.tokens.get('editToken'),            summary: config.summary || i18n.summary,            appendtext: processPoll(poll)        }).done(function(res){            var noti = res.error                ? new BannerNotification(i18n.success, 'error')                : new BannerNotification(i18n.error, 'confirm');            noti.show;        });

return false; }

/**    * @method      processPoll * @description Process poll results and return as a string * @param      {Object} poll * @return     {String} */   function processPoll(poll) { var res = '\n==' + poll.question +'=='; for (var answer in poll.vote) res += '\n*' + answer + ': ' + poll.vote[answer]; res += '\n:' + i18n.total + ': ' + poll.total; res += '\n:' + i18n.created + ': ' + poll.datetime; return res; }

importArticle({ type: 'script', article: 'u:dev:MediaWiki:I18n-js/code.js' }); mw.hook('dev.i18n').add(function(i18n) {       i18n.loadMessages('ArchivePoll').done(init);    }); })(window.ArchivePoll);