MediaWiki:Gadget-morebits.js: Difference between revisions

Content deleted Content added
Repo at 83dcdd2: Support batch requested moves (#1888)
Repo at 3da72fd: apply autofixes 1 (#2058)
Line 38:
 
/** @lends Morebits */
varconst Morebits = {};
window.Morebits = Morebits; // allow global access
 
Line 67:
*/
getMessage: function () {
varconst args = Array.prototype.slice.call(arguments); // array of size `n`
// 1st arg: message name
// 2nd to (n-1)th arg: message parameters
// nth arg: legacy English fallback
varconst msgName = args[0];
varconst fallback = args[args.length - 1];
if (!Morebits.i18n.parser) {
return fallback;
Line 78:
// i18n libraries are generally invoked with variable number of arguments
// as msg(msgName, ...parameters)
varconst i18nMessage = Morebits.i18n.parser.get.apply(null, args.slice(0, -1));
// if no i18n message exists, i18n libraries generally give back the message name
if (i18nMessage === msgName) {
Line 88:
 
// shortcut
varconst msg = Morebits.i18n.getMessage;
 
 
Line 111:
signatureTimestampFormat: function (str) {
// HH:mm, DD Month YYYY (UTC)
varconst rgx = /(\d{2}):(\d{2}), (\d{1,2}) (\w+) (\d{4}) \(UTC\)/;
varconst match = rgx.exec(str);
if (!match) {
return null;
}
varconst month = Morebits.date.localeData.months.indexOf(match[4]);
if (month === -1) {
return null;
Line 190:
return '';
}
varconst firstChar = pageName[0],
remainder = Morebits.string.escapeRegExp(pageName.slice(1));
if (mw.Title.phpCharToUpper(firstChar) !== firstChar.toLowerCase()) {
Line 207:
*/
Morebits.createHtml = function(input) {
varconst fragment = document.createDocumentFragment();
if (!input) {
return fragment;
Line 214:
input = [ input ];
}
for (varlet i = 0; i < input.length; ++i) {
if (input[i] instanceof Node) {
fragment.appendChild(input[i]);
} else {
$.parseHTML(Morebits.createHtml.renderWikilinks(input[i])).forEach(function(node) => {
fragment.appendChild(node);
});
Line 232:
*/
Morebits.createHtml.renderWikilinks = function (text) {
varconst ub = new Morebits.unbinder(text);
// Don't convert wikilinks within code tags as they're used for displaying wiki-code
ub.unbind('<code>', '</code>');
ub.content = ub.content.replace(
/\[\[:?(?:([^|\]]+?)\|)?([^\]|]+?)\]\]/g,
function(_, target, text) => {
if (!target) {
target = text;
Line 266:
namespaces = [namespaces];
}
varlet aliases = [], regex;
$.each(mw.config.get('wgNamespaceIds'), function(name, number) => {
if (namespaces.indexOf(number) !== -1) {
// Namespaces are completely agnostic as to case,
// and a regex string is more useful/compatible than a RegExp object,
// so we accept any casing for any letter.
aliases.push(name.split('').map(function(char) {=> Morebits.pageNameRegex(char)).join(''));
return Morebits.pageNameRegex(char);
}).join(''));
}
});
Line 313 ⟶ 311:
*/
Morebits.quickForm.prototype.render = function QuickFormRender() {
varconst ret = this.root.render();
ret.names = {};
return ret;
Line 407 ⟶ 405:
*/
Morebits.quickForm.element.prototype.append = function QuickFormElementAppend(data) {
varlet child;
if (data instanceof Morebits.quickForm.element) {
child = data;
Line 425 ⟶ 423:
*/
Morebits.quickForm.element.prototype.render = function QuickFormElementRender(internal_subgroup_id) {
varconst currentNode = this.compute(this.data, internal_subgroup_id);
 
for (varlet i = 0; i < this.childs.length; ++i) {
// do not pass internal_subgroup_id to recursive calls
currentNode[1].appendChild(this.childs[i].render());
Line 437 ⟶ 435:
/** @memberof Morebits.quickForm.element */
Morebits.quickForm.element.prototype.compute = function QuickFormElementCompute(data, in_id) {
varlet node;
varlet childContainer = null;
varlet label;
varconst id = (in_id ? in_id + '_' : '') + 'node_' + Morebits.quickForm.element.id++;
if (data.adminonly && !Morebits.userIsSysop) {
// hell hack alpha
Line 446 ⟶ 444:
}
 
varlet i, current, subnode;
switch (data.type) {
case 'form':
Line 547 ⟶ 545:
if (data.list) {
for (i = 0; i < data.list.length; ++i) {
varconst cur_id = id + '_' + i;
current = data.list[i];
var cur_div;
Line 594 ⟶ 592:
var event;
if (current.subgroup) {
varlet tmpgroup = current.subgroup;
 
if (!Array.isArray(tmpgroup)) {
Line 604 ⟶ 602:
id: id + '_' + i + '_subgroup'
});
$.each(tmpgroup, function(idx, el) => {
varconst newEl = $.extend({}, el);
if (!newEl.type) {
newEl.type = data.type;
Line 613 ⟶ 611:
});
 
varconst subgroup = subgroupRaw.render(cur_id);
subgroup.className = 'quickformSubgroup';
subnode.subgroup = subgroup;
Line 622 ⟶ 620:
e.target.parentNode.appendChild(e.target.subgroup);
if (e.target.type === 'radio') {
varconst name = e.target.name;
if (e.target.form.names[name] !== undefined) {
e.target.form.names[name].parentNode.removeChild(e.target.form.names[name].subgroup);
Line 639 ⟶ 637:
event = function(e) {
if (e.target.checked) {
varconst name = e.target.name;
if (e.target.form.names[name] !== undefined) {
e.target.form.names[name].parentNode.removeChild(e.target.form.names[name].subgroup);
Line 680 ⟶ 678:
} else {
subnode.setAttribute('type', 'number');
['min', 'max', 'step', 'list'].forEach(function(att) => {
if (data[att]) {
subnode.setAttribute(att, data[att]);
Line 687 ⟶ 685:
}
 
['value', 'size', 'placeholder', 'maxlength'].forEach(function(att) => {
if (data[att]) {
subnode.setAttribute(att, data[att]);
}
});
['disabled', 'required', 'readonly'].forEach(function(att) => {
if (data[att]) {
subnode.setAttribute(att, att);
Line 718 ⟶ 716:
disabled: min >= max,
event: function(e) {
varconst new_node = new Morebits.quickForm.element(e.target.sublist);
e.target.area.appendChild(new_node.render());
 
Line 746 ⟶ 744:
 
for (i = 0; i < min; ++i) {
varconst elem = new Morebits.quickForm.element(sublist);
listNode.appendChild(elem.render());
}
Line 761 ⟶ 759:
node = document.createElement('div');
 
data.inputs.forEach(function(subdata) => {
varconst cell = new Morebits.quickForm.element($.extend(subdata, { type: '_dyninput_cell' }));
node.appendChild(cell.render());
});
if (data.remove) {
varconst remove = this.compute({
type: 'button',
label: 'remove',
event: function(e) {
varconst list = e.target.listnode;
varconst node = e.target.inputnode;
varconst more = e.target.morebutton;
 
list.removeChild(node);
Line 781 ⟶ 779:
});
node.appendChild(remove[0]);
varconst removeButton = remove[1];
removeButton.inputnode = node;
removeButton.listnode = data.listnode;
Line 839 ⟶ 837:
}
if (data.label) {
varconst result = document.createElement('span');
result.className = 'quickformDescription';
result.appendChild(Morebits.createHtml(data.label));
Line 877 ⟶ 875:
if (data.label) {
label = node.appendChild(document.createElement('h5'));
varconst labelElement = document.createElement('label');
labelElement.appendChild(Morebits.createHtml(data.label));
labelElement.setAttribute('for', data.id || id);
Line 943 ⟶ 941:
*/
Morebits.quickForm.element.generateTooltip = function QuickFormElementGenerateTooltip(node, data) {
varconst tooltipButton = node.appendChild(document.createElement('span'));
tooltipButton.className = 'morebits-tooltipButton';
tooltipButton.title = data.tooltip; // Provides the content for jQuery UI
Line 967 ⟶ 965:
*/
Morebits.quickForm.getInputData = function(form) {
varconst result = {};
 
for (varlet i = 0; i < form.elements.length; i++) {
varconst field = form.elements[i];
if (field.disabled || !field.name || !field.type ||
field.type === 'submit' || field.type === 'button') {
Line 978 ⟶ 976:
// For elements in subgroups, quickform prepends element names with
// name of the parent group followed by a period, get rid of that.
varconst fieldNameNorm = field.name.slice(field.name.indexOf('.') + 1);
 
switch (field.type) {
Line 1,028 ⟶ 1,026:
*/
Morebits.quickForm.getElements = function QuickFormGetElements(form, fieldName) {
varconst $form = $(form);
fieldName = $.escapeSelector(fieldName); // sanitize input
varlet $elements = $form.find('[name="' + fieldName + '"]');
if ($elements.length > 0) {
return $elements.toArray();
Line 1,048 ⟶ 1,046:
*/
Morebits.quickForm.getCheckboxOrRadio = function QuickFormGetCheckboxOrRadio(elementArray, value) {
varconst found = $.grep(elementArray, function(el) {=> el.value === value);
return el.value === value;
});
if (found.length > 0) {
return found[0];
Line 1,108 ⟶ 1,104:
*/
Morebits.quickForm.getElementLabel = function QuickFormGetElementLabel(element) {
varconst labelElement = Morebits.quickForm.getElementLabelObject(element);
 
if (!labelElement) {
Line 1,125 ⟶ 1,121:
*/
Morebits.quickForm.setElementLabel = function QuickFormSetElementLabel(element, labelText) {
varconst labelElement = Morebits.quickForm.getElementLabelObject(element);
 
if (!labelElement) {
Line 1,203 ⟶ 1,199:
*/
HTMLFormElement.prototype.getChecked = function(name, type) {
varconst elements = this.elements[name];
if (!elements) {
return [];
}
varconst return_array = [];
varlet i;
if (elements instanceof HTMLSelectElement) {
varconst options = elements.options;
for (i = 0; i < options.length; ++i) {
if (options[i].selected) {
Line 1,257 ⟶ 1,253:
*/
HTMLFormElement.prototype.getUnchecked = function(name, type) {
varconst elements = this.elements[name];
if (!elements) {
return [];
}
varconst return_array = [];
varlet i;
if (elements instanceof HTMLSelectElement) {
varconst options = elements.options;
for (i = 0; i < options.length; ++i) {
if (!options[i].selected) {
Line 1,325 ⟶ 1,321:
address = address.toUpperCase();
// Expand zero abbreviations
varconst abbrevPos = address.indexOf('::');
if (abbrevPos > -1) {
// We know this is valid IPv6. Find the last index of the
// address before any CIDR number (e.g. "a:b:c::/24").
varconst CIDRStart = address.indexOf('/');
varconst addressEnd = CIDRStart !== -1 ? CIDRStart - 1 : address.length - 1;
// If the '::' is at the beginning...
varlet repeat, extra, pad;
if (abbrevPos === 0) {
repeat = '0:';
Line 1,348 ⟶ 1,344:
pad = 8; // 6+2 (due to '::')
}
varlet replacement = repeat;
pad -= address.split(':').length - 1;
for (varlet i = 1; i < pad; i++) {
replacement += repeat;
}
Line 1,381 ⟶ 1,377:
validCIDR: function (ip) {
if (Morebits.ip.isRange(ip)) {
varconst subnet = parseInt(ip.match(/\/(\d{1,3})$/)[1], 10);
if (subnet) { // Should be redundant
if (mw.util.isIPv6Address(ip, true)) {
Line 1,408 ⟶ 1,404:
return false;
}
varconst subnetMatch = ipv6.match(/\/(\d{1,3})$/);
if (subnetMatch && parseInt(subnetMatch[1], 10) < 64) {
return false;
}
ipv6 = Morebits.ip.sanitizeIPv6(ipv6);
varconst ip_re = /^((?:[0-9A-F]{1,4}:){4})(?:[0-9A-F]{1,4}:){3}[0-9A-F]{1,4}(?:\/\d{1,3})?$/;
return ipv6.replace(ip_re, '$1' + '0:0:0:0/64');
}
Line 1,460 ⟶ 1,456:
throw new Error('start marker and end marker must be of the same length');
}
varlet level = 0;
varlet initial = null;
varconst result = [];
if (!Array.isArray(skiplist)) {
if (skiplist === undefined) {
Line 1,472 ⟶ 1,468:
}
}
for (varlet i = 0; i < str.length; ++i) {
for (varlet j = 0; j < skiplist.length; ++j) {
if (str.substr(i, skiplist[j].length) === skiplist[j]) {
i += skiplist[j].length - 1;
Line 1,509 ⟶ 1,505:
*/
formatReasonText: function(str, addSig) {
varlet reason = (str || '').toString().trim();
varconst unbinder = new Morebits.unbinder(reason);
unbinder.unbind('<no' + 'wiki>', '</no' + 'wiki>');
unbinder.content = unbinder.content.replace(/\|/g, '{{subst:!}}');
reason = unbinder.rebind();
if (addSig) {
varconst sig = '~~~~', sigIndex = reason.lastIndexOf(sig);
if (sigIndex === -1 || sigIndex !== reason.length - sig.length) {
reason += ' ' + sig;
Line 1,599 ⟶ 1,595:
throw 'A non-array object passed to Morebits.array.uniq';
}
return arr.filter(function(item, idx) {=> arr.indexOf(item) === idx);
return arr.indexOf(item) === idx;
});
},
 
Line 1,616 ⟶ 1,610:
throw 'A non-array object passed to Morebits.array.dups';
}
return arr.filter(function(item, idx) {=> arr.indexOf(item) !== idx);
return arr.indexOf(item) !== idx;
});
},
 
Line 1,637 ⟶ 1,629:
return [ arr ]; // we return an array consisting of this array.
}
varconst numChunks = Math.ceil(arr.length / size);
varconst result = new Array(numChunks);
for (varlet i = 0; i < numChunks; i++) {
result[i] = arr.slice(i * size, (i + 1) * size);
}
Line 1,663 ⟶ 1,655:
*/
optgroupFull: function(params, data) {
varconst originalMatcher = $.fn.select2.defaults.defaults.matcher;
varconst result = originalMatcher(params, data);
 
if (result && params.term &&
Line 1,675 ⟶ 1,667:
/** Custom matcher that matches from the beginning of words only. */
wordBeginning: function(params, data) {
varconst originalMatcher = $.fn.select2.defaults.defaults.matcher;
varconst result = originalMatcher(params, data);
if (!params.term || (result &&
new RegExp('\\b' + mw.util.escapeRegExp(params.term), 'i').test(result.text))) {
Line 1,687 ⟶ 1,679:
/** Underline matched part of options. */
highlightSearchMatches: function(data) {
varconst searchTerm = Morebits.select2SearchQuery;
if (!searchTerm || data.loading) {
return data.text;
}
varconst idx = data.text.toUpperCase().indexOf(searchTerm.toUpperCase());
if (idx < 0) {
return data.text;
Line 1,718 ⟶ 1,710:
return;
}
varlet target = $(ev.target).closest('.select2-container');
if (!target.length) {
return;
Line 1,724 ⟶ 1,716:
target = target.prev();
target.select2('open');
varconst search = target.data('select2').dropdown.$search ||
target.data('select2').selection.$search;
// Use DOM .focus() to work around a jQuery 3.6.0 regression (https://github.com/select2/select2/issues/5993)
Line 1,771 ⟶ 1,763:
throw new Error('Both prefix and postfix must be provided');
}
varconst re = new RegExp(prefix + '([\\s\\S]*?)' + postfix, 'g');
this.content = this.content.replace(re, Morebits.unbinder.getCallback(this));
},
Line 1,781 ⟶ 1,773:
*/
rebind: function UnbinderRebind() {
varlet content = this.content;
content.self = this;
for (varconst current in this.history) {
if (Object.prototype.hasOwnProperty.call(this.history, current)) {
content = content.replace(current, this.history[current]);
Line 1,799 ⟶ 1,791:
Morebits.unbinder.getCallback = function UnbinderGetCallback(self) {
return function UnbinderCallback(match) {
varconst current = self.prefix + self.counter + self.postfix;
self.history[current] = match;
++self.counter;
Line 1,818 ⟶ 1,810:
*/
Morebits.date = function() {
varconst args = Array.prototype.slice.call(arguments);
 
// Check MediaWiki formats
Line 1,825 ⟶ 1,817:
// 14-digit string will be interpreted differently.
if (args.length === 1) {
varconst param = args[0];
if (/^\d{14}$/.test(param)) {
// YYYYMMDDHHmmss
varconst digitMatch = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/.exec(param);
if (digitMatch) {
// ..... year ... month .. date ... hour .... minute ..... second
Line 1,835 ⟶ 1,827:
} else if (typeof param === 'string') {
// Wikitext signature timestamp
varconst dateParts = Morebits.l10n.signatureTimestampFormat(param);
if (dateParts) {
this._d = new Date(Date.UTC.apply(null, dateParts));
Line 1,980 ⟶ 1,972:
*/
add: function(number, unit) {
varlet num = parseInt(number, 10); // normalize
if (isNaN(num)) {
throw new Error('Invalid number "' + number + '" provided.');
}
unit = unit.toLowerCase(); // normalize
varconst unitMap = Morebits.date.unitMap;
varlet unitNorm = unitMap[unit] || unitMap[unit + 's']; // so that both singular and plural forms work
if (unitNorm) {
// No built-in week functions, so rather than build out ISO's getWeek/setWeek, just multiply
Line 2,052 ⟶ 2,044:
return 'Invalid date'; // Put the truth out, preferable to "NaNNaNNan NaN:NaN" or whatever
}
varlet udate = this;
// create a new date object that will contain the date to display as system time
if (zone === 'utc') {
Line 2,066 ⟶ 2,058:
}
 
varconst pad = function(num, len) {
len = len || 2; // Up to length of 00 + 1
return ('00' + num).toString().slice(0 - len);
};
varconst h24 = udate.getHours(), m = udate.getMinutes(), s = udate.getSeconds(), ms = udate.getMilliseconds();
varconst D = udate.getDate(), M = udate.getMonth() + 1, Y = udate.getFullYear();
varconst h12 = h24 % 12 || 12, amOrPm = h24 >= 12 ? msg('period-pm', 'PM') : msg('period-am', 'AM');
varconst replacementMap = {
HH: pad(h24), H: h24, hh: pad(h12), h: h12, A: amOrPm,
mm: pad(m), m: m,
Line 2,084 ⟶ 2,076:
};
 
varconst unbinder = new Morebits.unbinder(formatstr); // escape stuff between [...]
unbinder.unbind('\\[', '\\]');
unbinder.content = unbinder.content.replace(
Line 2,092 ⟶ 2,084:
*/
/H{1,2}|h{1,2}|m{1,2}|s{1,2}|SSS|d(d{2,3})?|D{1,2}|M{1,4}|Y{1,2}(Y{2})?|A/g,
function(match) {=> replacementMap[match]
return replacementMap[match];
}
);
return unbinder.rebind().replace(/\[(.*?)\]/g, '$1');
Line 2,110 ⟶ 2,100:
// Zero out the hours, minutes, seconds and milliseconds - keeping only the date;
// find the difference. Note that setHours() returns the same thing as getTime().
varconst dateDiff = (new Date().setHours(0, 0, 0, 0) -
new Date(this).setHours(0, 0, 0, 0)) / 8.64e7;
switch (true) {
Line 2,151 ⟶ 2,141:
level = isNaN(level) ? 2 : level;
 
varconst header = '='.repeat(level);
varconst text = this.getUTCMonthName() + ' ' + this.getUTCFullYear();
 
if (header.length) { // wikitext-formatted header
Line 2,164 ⟶ 2,154:
 
// Allow native Date.prototype methods to be used on Morebits.date objects
Object.getOwnPropertyNames(Date.prototype).forEach(function(func) => {
Morebits.date.prototype[func] = function() {
return this._d[func].apply(this._d, Array.prototype.slice.call(arguments));
Line 2,252 ⟶ 2,242:
}
}
window.setTimeout(function() => {
window.___location = Morebits.wiki.actionCompleted.redirect;
}, Morebits.wiki.actionCompleted.timeOut);
Line 2,378 ⟶ 2,368:
++Morebits.wiki.numberOfActionsLeft;
 
varconst queryString = $.map(this.query, function(val, i) => {
if (Array.isArray(val)) {
return encodeURIComponent(i) + '=' + val.map(encodeURIComponent).join('|');
Line 2,387 ⟶ 2,377:
// token should always be the last item in the query string (bug TW-B-0013)
 
varconst ajaxparams = $.extend({}, {
context: this,
type: this.query.action === 'query' ? 'GET' : 'POST',
Line 2,453 ⟶ 2,443:
// Get a new CSRF token and retry. If the original action needs a different
// type of action than CSRF, we do one pointless retry before bailing out
return Morebits.wiki.api.getToken().then(function(token) => {
this.query.token = token;
return this.post(callerAjaxParameters);
}.bind(this));
}
 
Line 2,497 ⟶ 2,487:
/** Retrieves wikitext from a page. Caching enabled, duration 1 day. */
Morebits.wiki.getCachedJson = function(title) {
varconst query = {
action: 'query',
prop: 'revisions',
Line 2,507 ⟶ 2,497:
maxage: '86400' // cache for 1 day
};
return new Morebits.wiki.api('', query).post().then(function(apiobj) => {
apiobj.getStatusElement().unlink();
varconst response = apiobj.getResponse();
varconst wikitext = response.query.pages[0].revisions[0].slots.main.content;
return JSON.parse(wikitext);
});
Line 2,553 ⟶ 2,543:
*/
Morebits.wiki.api.getToken = function() {
varconst tokenApi = new Morebits.wiki.api(msg('getting-token', 'Getting token'), {
action: 'query',
meta: 'tokens',
Line 2,559 ⟶ 2,549:
format: 'json'
});
return tokenApi.post().then(function(apiobj) {=> apiobj.response.query.tokens.csrftoken);
return apiobj.response.query.tokens.csrftoken;
});
};
 
Line 2,627 ⟶ 2,615:
* @private
*/
varconst ctx = {
// backing fields for public properties
pageName: pageName,
Line 2,739 ⟶ 2,727:
};
 
varconst emptyFunction = function() { };
 
/**
Line 2,812 ⟶ 2,800:
 
// are we getting our editing token from mw.user.tokens?
varconst canUseMwUserToken = fnCanUseMwUserToken('edit');
 
if (!ctx.pageLoaded && !canUseMwUserToken) {
Line 2,852 ⟶ 2,840:
ctx.retries = 0;
 
varconst query = {
action: 'edit',
title: ctx.pageName,
Line 3,488 ⟶ 3,476:
}
 
varconst query = {
action: 'query',
prop: 'revisions',
Line 3,560 ⟶ 3,548:
fnProcessMove.call(this, this);
} else {
varconst query = fnNeedTokenInfoQuery('move');
 
ctx.moveApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessMove, ctx.statusElement, ctx.onMoveFailure);
Line 3,584 ⟶ 3,572:
// If a link is present, don't need to check if it's patrolled
if ($('.patrollink').length) {
varconst patrolhref = $('.patrollink a').attr('href');
ctx.rcid = mw.util.getParamValue('rcid', patrolhref);
fnProcessPatrol(this, this);
} else {
varconst patrolQuery = {
action: 'query',
prop: 'info',
Line 3,638 ⟶ 3,626:
fnProcessTriageList(this, this);
} else {
varconst query = fnNeedTokenInfoQuery('triage');
 
ctx.triageApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessTriageList);
Line 3,665 ⟶ 3,653:
fnProcessDelete.call(this, this);
} else {
varconst query = fnNeedTokenInfoQuery('delete');
 
ctx.deleteApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessDelete, ctx.statusElement, ctx.onDeleteFailure);
Line 3,690 ⟶ 3,678:
fnProcessUndelete.call(this, this);
} else {
varconst query = fnNeedTokenInfoQuery('undelete');
 
ctx.undeleteApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessUndelete, ctx.statusElement, ctx.onUndeleteFailure);
Line 3,721 ⟶ 3,709:
// (absolute, not differential), we always need to request
// protection levels from the server
varconst query = fnNeedTokenInfoQuery('protect');
 
ctx.protectApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessProtect, ctx.statusElement, ctx.onProtectFailure);
Line 3,756 ⟶ 3,744:
fnProcessStabilize.call(this, this);
} else {
varconst query = fnNeedTokenInfoQuery('stabilize');
 
ctx.stabilizeApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessStabilize, ctx.statusElement, ctx.onStabilizeFailure);
Line 3,809 ⟶ 3,797:
// wgRestrictionEdit is null on non-existent pages,
// so this neatly handles nonexistent pages
varconst editRestriction = mw.config.get('wgRestrictionEdit');
if (!editRestriction || editRestriction.indexOf('sysop') !== -1) {
return false;
Line 3,834 ⟶ 3,822:
*/
var fnNeedTokenInfoQuery = function(action) {
varconst query = {
action: 'query',
meta: 'tokens',
Line 3,860 ⟶ 3,848:
// callback from loadApi.post()
var fnLoadSuccess = function() {
varconst response = ctx.loadApi.getResponse().query;
 
if (!fnCheckPageName(response, ctx.onLoadFailure)) {
Line 3,866 ⟶ 3,854:
}
 
varlet page = response.pages[0], rev;
ctx.pageExists = !page.missing;
if (ctx.pageExists) {
Line 3,896 ⟶ 3,884:
// Includes cascading protection
if (Morebits.userIsSysop) {
varconst editProt = page.protection.filter(function(pr) {=> pr.type === 'edit' && pr.level === 'sysop').pop();
return pr.type === 'edit' && pr.level === 'sysop';
}).pop();
if (editProt) {
ctx.fullyProtected = editProt.expiry;
Line 3,908 ⟶ 3,894:
ctx.revertCurID = page.lastrevid;
 
varconst testactions = page.actions;
ctx.testActions = []; // was null
Object.keys(testactions).forEach(function(action) => {
if (testactions[action]) {
ctx.testActions.push(action);
Line 3,949 ⟶ 3,935:
}
 
varconst page = response.pages && response.pages[0];
if (page) {
// check for invalid titles
Line 3,959 ⟶ 3,945:
 
// retrieve actual title of the page after normalization and redirects
varconst resolvedName = page.title;
 
if (response.redirects) {
// check for cross-namespace redirect:
varconst origNs = new mw.Title(ctx.pageName).namespace;
varconst newNs = new mw.Title(resolvedName).namespace;
if (origNs !== newNs && !ctx.followCrossNsRedirect) {
ctx.statusElement.error(msg('cross-redirect-abort', ctx.pageName, resolvedName, ctx.pageName + ' is a cross-namespace redirect to ' + resolvedName + ', aborted'));
Line 4,005 ⟶ 3,991:
return true;
} else if (typeof ctx.watched === 'string') {
varlet newExpiry;
// Attempt to determine if the new expiry is a
// relative (e.g. `1 month`) or absolute datetime
varconst rel = ctx.watchlistExpiry.split(' ');
try {
newExpiry = new Morebits.date().add(rel[0], rel[1]);
Line 4,034 ⟶ 4,020:
var fnSaveSuccess = function() {
ctx.editMode = 'all'; // cancel append/prepend/newSection/revert modes
varconst response = ctx.saveApi.getResponse();
 
// see if the API thinks we were successful
Line 4,041 ⟶ 4,027:
// real success
// default on success action - display link for edited page
varconst link = document.createElement('a');
link.setAttribute('href', mw.util.getUrl(ctx.pageName));
link.appendChild(document.createTextNode(ctx.pageName));
Line 4,067 ⟶ 4,053:
// callback from saveApi.post()
var fnSaveError = function() {
varconst errorCode = ctx.saveApi.getErrorCode();
 
// check for edit conflict
Line 4,073 ⟶ 4,059:
 
// edit conflicts can occur when the page needs to be purged from the server cache
varconst purgeQuery = {
action: 'purge',
titles: ctx.pageName // redirects are already resolved
};
 
varconst purgeApi = new Morebits.wiki.api(msg('editconflict-purging', 'Edit conflict detected, purging server cache'), purgeQuery, function(() => {
--Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds
 
Line 4,087 ⟶ 4,073:
ctx.loadApi.post(); // reload the page and reapply the edit
}
}), ctx.statusElement);
purgeApi.post();
 
Line 4,098 ⟶ 4,084:
 
// wait for sometime for client to regain connectivity
sleep(2000).then(function() => {
ctx.saveApi.post(); // give it another go!
});
Line 4,104 ⟶ 4,090:
// hard error, give up
} else {
varconst response = ctx.saveApi.getResponse();
varconst errorData = response.error || // bc error format
response.errors[0].data; // html/wikitext/plaintext error format
 
Line 4,142 ⟶ 4,128:
};
 
varconst isTextRedirect = function(text) {
if (!text) { // no text - content empty or inaccessible (revdelled or suppressed)
return false;
}
return Morebits.l10n.redirectTagAliases.some(function(tag) {=> new RegExp('^\\s*' + tag + '\\W', 'i').test(text));
return new RegExp('^\\s*' + tag + '\\W', 'i').test(text);
});
};
 
var fnLookupCreationSuccess = function() {
varconst response = ctx.lookupCreationApi.getResponse().query;
 
if (!fnCheckPageName(response, ctx.onLookupCreationFailure)) {
Line 4,158 ⟶ 4,142:
}
 
varconst rev = response.pages[0].revisions && response.pages[0].revisions[0];
if (!rev) {
ctx.statusElement.error('Could not find any revisions of ' + ctx.pageName);
Line 4,195 ⟶ 4,179:
 
var fnLookupNonRedirectCreator = function() {
varconst response = ctx.lookupCreationApi.getResponse().query;
varconst revs = response.pages[0].revisions;
 
for (varlet i = 0; i < revs.length; i++) {
 
if (!isTextRedirect(revs[i].content)) {
Line 4,262 ⟶ 4,246:
* @returns {boolean}
*/
varconst fnProcessChecks = function(action, onFailure, response) {
varconst missing = response.pages[0].missing;
 
// No undelete as an existing page could have deleted revisions
varconst actionMissing = missing && ['delete', 'stabilize', 'move'].indexOf(action) !== -1;
varconst protectMissing = action === 'protect' && missing && (ctx.protectEdit || ctx.protectMove);
varconst saltMissing = action === 'protect' && !missing && ctx.protectCreate;
 
if (actionMissing || protectMissing || saltMissing) {
Line 4,278 ⟶ 4,262:
// Delete, undelete, move
// extract protection info
varlet editprot;
if (action === 'undelete') {
editprot = response.pages[0].protection.filter(function(pr) {=> pr.type === 'create' && pr.level === 'sysop').pop();
return pr.type === 'create' && pr.level === 'sysop';
}).pop();
} else if (action === 'delete' || action === 'move') {
editprot = response.pages[0].protection.filter(function(pr) {=> pr.type === 'edit' && pr.level === 'sysop').pop();
return pr.type === 'edit' && pr.level === 'sysop';
}).pop();
}
if (editprot && !ctx.suppressProtectWarning &&
Line 4,306 ⟶ 4,286:
 
var fnProcessMove = function() {
varlet pageTitle, token;
 
if (fnCanUseMwUserToken('move')) {
Line 4,312 ⟶ 4,292:
pageTitle = ctx.pageName;
} else {
varconst response = ctx.moveApi.getResponse().query;
 
if (!fnProcessChecks('move', ctx.onMoveFailure, response)) {
Line 4,319 ⟶ 4,299:
 
token = response.tokens.csrftoken;
varconst page = response.pages[0];
pageTitle = page.title;
ctx.watched = page.watchlistexpiry || page.watched;
}
 
varconst query = {
action: 'move',
from: pageTitle,
Line 4,356 ⟶ 4,336:
 
var fnProcessPatrol = function() {
varconst query = {
action: 'patrol',
format: 'json'
Line 4,366 ⟶ 4,346:
query.token = mw.user.tokens.get('patrolToken');
} else {
varconst response = ctx.patrolApi.getResponse().query;
 
// Don't patrol if not unpatrolled
Line 4,373 ⟶ 4,353:
}
 
varconst lastrevid = response.pages[0].lastrevid;
if (!lastrevid) {
return;
Line 4,379 ⟶ 4,359:
query.revid = lastrevid;
 
varconst token = response.tokens.csrftoken;
if (!token) {
return;
Line 4,389 ⟶ 4,369:
}
 
varconst patrolStat = new Morebits.status('Marking page as patrolled');
 
ctx.patrolProcessApi = new Morebits.wiki.api('patrolling page...', query, null, patrolStat);
Line 4,401 ⟶ 4,381:
ctx.csrfToken = mw.user.tokens.get('csrfToken');
} else {
varconst response = ctx.triageApi.getResponse().query;
 
ctx.pageID = response.pages[0].pageid;
Line 4,414 ⟶ 4,394:
}
 
varconst query = {
action: 'pagetriagelist',
page_id: ctx.pageID,
Line 4,427 ⟶ 4,407:
// callback from triageProcessListApi.post()
var fnProcessTriage = function() {
varconst responseList = ctx.triageProcessListApi.getResponse().pagetriagelist;
// Exit if not in the queue
if (!responseList || responseList.result !== 'success') {
return;
}
varconst page = responseList.pages && responseList.pages[0];
// Do nothing if page already triaged/patrolled
if (!page || !parseInt(page.patrol_status, 10)) {
varconst query = {
action: 'pagetriageaction',
pageid: ctx.pageID,
Line 4,445 ⟶ 4,425:
format: 'json'
};
varconst triageStat = new Morebits.status('Marking page as curated');
ctx.triageProcessApi = new Morebits.wiki.api('curating page...', query, null, triageStat);
ctx.triageProcessApi.setParent(this);
Line 4,453 ⟶ 4,433:
 
var fnProcessDelete = function() {
varlet pageTitle, token;
 
if (fnCanUseMwUserToken('delete')) {
Line 4,459 ⟶ 4,439:
pageTitle = ctx.pageName;
} else {
varconst response = ctx.deleteApi.getResponse().query;
 
if (!fnProcessChecks('delete', ctx.onDeleteFailure, response)) {
Line 4,466 ⟶ 4,446:
 
token = response.tokens.csrftoken;
varconst page = response.pages[0];
pageTitle = page.title;
ctx.watched = page.watchlistexpiry || page.watched;
}
 
varconst query = {
action: 'delete',
title: pageTitle,
Line 4,498 ⟶ 4,478:
var fnProcessDeleteError = function() {
 
varconst errorCode = ctx.deleteProcessApi.getErrorCode();
 
// check for "Database query error"
Line 4,521 ⟶ 4,501:
 
var fnProcessUndelete = function() {
varlet pageTitle, token;
 
if (fnCanUseMwUserToken('undelete')) {
Line 4,527 ⟶ 4,507:
pageTitle = ctx.pageName;
} else {
varconst response = ctx.undeleteApi.getResponse().query;
 
if (!fnProcessChecks('undelete', ctx.onUndeleteFailure, response)) {
Line 4,534 ⟶ 4,514:
 
token = response.tokens.csrftoken;
varconst page = response.pages[0];
pageTitle = page.title;
ctx.watched = page.watchlistexpiry || page.watched;
}
 
varconst query = {
action: 'undelete',
title: pageTitle,
Line 4,566 ⟶ 4,546:
var fnProcessUndeleteError = function() {
 
varconst errorCode = ctx.undeleteProcessApi.getErrorCode();
 
// check for "Database query error"
Line 4,595 ⟶ 4,575:
 
var fnProcessProtect = function() {
varconst response = ctx.protectApi.getResponse().query;
 
if (!fnProcessChecks('protect', ctx.onProtectFailure, response)) {
Line 4,601 ⟶ 4,581:
}
 
varconst token = response.tokens.csrftoken;
varconst page = response.pages[0];
varconst pageTitle = page.title;
ctx.watched = page.watchlistexpiry || page.watched;
 
// Fetch existing protection levels
varconst prs = response.pages[0].protection;
varlet editprot, moveprot, createprot;
prs.forEach(function(pr) => {
// Filter out protection from cascading
if (pr.type === 'edit' && !pr.source) {
Line 4,634 ⟶ 4,614:
// Default to pre-existing cascading protection if unchanged (similar to above)
if (ctx.protectCascade === null) {
ctx.protectCascade = !!prs.filter(function(pr) {=> pr.cascade).length;
return pr.cascade;
}).length;
}
// Warn if cascading protection being applied with an invalid protection level,
Line 4,658 ⟶ 4,636:
 
// Build protection levels and expirys (expiries?) for query
varconst protections = [], expirys = [];
if (ctx.protectEdit) {
protections.push('edit=' + ctx.protectEdit.level);
Line 4,674 ⟶ 4,652:
}
 
varconst query = {
action: 'protect',
title: pageTitle,
Line 4,702 ⟶ 4,680:
 
var fnProcessStabilize = function() {
varlet pageTitle, token;
 
if (fnCanUseMwUserToken('stabilize')) {
Line 4,708 ⟶ 4,686:
pageTitle = ctx.pageName;
} else {
varconst response = ctx.stabilizeApi.getResponse().query;
 
// 'stabilize' as a verb not necessarily well understood
Line 4,716 ⟶ 4,694:
 
token = response.tokens.csrftoken;
varconst page = response.pages[0];
pageTitle = page.title;
// Doesn't support watchlist expiry [[phab:T263336]]
Line 4,722 ⟶ 4,700:
}
 
varconst query = {
action: 'stabilize',
title: pageTitle,
Line 4,746 ⟶ 4,724:
 
var sleep = function(milliseconds) {
varconst deferred = $.Deferred();
setTimeout(deferred.resolve, milliseconds);
return deferred;
Line 4,792 ⟶ 4,770:
$(previewbox).show();
 
varconst statusspan = document.createElement('span');
previewbox.appendChild(statusspan);
Morebits.status.init(statusspan);
 
varconst query = {
action: 'parse',
prop: ['text', 'modules'],
Line 4,811 ⟶ 4,789:
query.sectiontitle = sectionTitle;
}
varconst renderApi = new Morebits.wiki.api('loading...', query, fnRenderSuccess, new Morebits.status('Preview'));
return renderApi.post();
};
 
var fnRenderSuccess = function(apiobj) {
varconst response = apiobj.getResponse();
varconst html = response.parse.text;
if (!html) {
apiobj.statelem.error('failed to retrieve preview, or template was blanked');
Line 4,858 ⟶ 4,836:
start = start || 0;
 
varconst level = []; // Track of how deep we are ({{, {{{, or [[)
varlet count = -1; // Number of parameters found
varlet unnamed = 0; // Keep track of what number an unnamed parameter should receive
varlet equals = -1; // After finding "=" before a parameter, the index; otherwise, -1
varlet current = '';
varconst result = {
name: '',
parameters: {}
};
varlet key, value;
 
/**
Line 4,890 ⟶ 4,868:
} else {
// No equals, so it must be unnamed; no trim since whitespace allowed
varconst param = final ? current.substring(equals + 1, current.length - 2) : current;
if (param) {
result.parameters[++unnamed] = param;
Line 4,899 ⟶ 4,877:
}
 
for (varlet i = start; i < text.length; ++i) {
varconst test3 = text.substr(i, 3);
if (test3 === '{{{' || (test3 === '}}}' && level[level.length - 1] === 3)) {
current += test3;
Line 4,911 ⟶ 4,889:
continue;
}
varconst test2 = text.substr(i, 2);
// Entering a template (or link)
if (test2 === '{{' || test2 === '[[') {
Line 4,976 ⟶ 4,954:
*/
removeLink: function(link_target) {
varconst mwTitle = mw.Title.newFromText(link_target);
varconst namespaceID = mwTitle.getNamespaceId();
varconst title = mwTitle.getMainText();
 
varlet link_regex_string = '';
if (namespaceID !== 0) {
link_regex_string = Morebits.namespaceRegex(namespaceID) + ':';
Line 4,988 ⟶ 4,966:
// For most namespaces, unlink both [[User:Test]] and [[:User:Test]]
// For files and categories, only unlink [[:Category:Test]]. Do not unlink [[Category:Test]]
varconst isFileOrCategory = [6, 14].indexOf(namespaceID) !== -1;
varconst colon = isFileOrCategory ? ':' : ':?';
 
varconst simple_link_regex = new RegExp('\\[\\[' + colon + '(' + link_regex_string + ')\\]\\]', 'g');
varconst piped_link_regex = new RegExp('\\[\\[' + colon + link_regex_string + '\\|(.+?)\\]\\]', 'g');
this.text = this.text.replace(simple_link_regex, '$1').replace(piped_link_regex, '$1');
return this;
Line 5,006 ⟶ 4,984:
*/
commentOutImage: function(image, reason) {
varconst unbinder = new Morebits.unbinder(this.text);
unbinder.unbind('<!--', '-->');
 
reason = reason ? reason + ': ' : '';
varconst image_re_string = Morebits.pageNameRegex(image);
 
// Check for normal image links, i.e. [[File:Foobar.png|...]]
// Will eat the whole link
varconst links_re = new RegExp('\\[\\[' + Morebits.namespaceRegex(6) + ':\\s*' + image_re_string + '\\s*[\\|(?:\\]\\])]');
varconst allLinks = Morebits.string.splitWeightedByKeys(unbinder.content, '[[', ']]');
for (varlet i = 0; i < allLinks.length; ++i) {
if (links_re.test(allLinks[i])) {
varconst replacement = '<!-- ' + reason + allLinks[i] + ' -->';
unbinder.content = unbinder.content.replace(allLinks[i], replacement);
// unbind the newly created comments
Line 5,028 ⟶ 5,006:
// eventually preceded with some space, and must include File: prefix
// Will eat the whole line.
varconst gallery_image_re = new RegExp('(^\\s*' + Morebits.namespaceRegex(6) + ':\\s*' + image_re_string + '\\s*(?:\\|.*?$|$))', 'mg');
unbinder.content = unbinder.content.replace(gallery_image_re, '<!-- ' + reason + '$1 -->');
 
Line 5,036 ⟶ 5,014:
// Check free image usages, for example as template arguments, might have the File: prefix excluded, but must be preceded by an |
// Will only eat the image name and the preceding bar and an eventual named parameter
varconst free_image_re = new RegExp('(\\|\\s*(?:[\\w\\s]+\\=)?\\s*(?:' + Morebits.namespaceRegex(6) + ':\\s*)?' + image_re_string + ')', 'mg');
unbinder.content = unbinder.content.replace(free_image_re, '<!-- ' + reason + '$1 -->');
// Rebind the content now, we are done!
Line 5,051 ⟶ 5,029:
*/
addToImageComment: function(image, data) {
varconst image_re_string = Morebits.pageNameRegex(image);
varconst links_re = new RegExp('\\[\\[' + Morebits.namespaceRegex(6) + ':\\s*' + image_re_string + '\\s*[\\|(?:\\]\\])]');
varconst allLinks = Morebits.string.splitWeightedByKeys(this.text, '[[', ']]');
for (varlet i = 0; i < allLinks.length; ++i) {
if (links_re.test(allLinks[i])) {
varlet replacement = allLinks[i];
// just put it at the end?
replacement = replacement.replace(/\]\]$/, '|' + data + ']]');
Line 5,062 ⟶ 5,040:
}
}
varconst gallery_re = new RegExp('^(\\s*' + image_re_string + '.*?)\\|?(.*?)$', 'mg');
varconst newtext = '$1|$2 ' + data;
this.text = this.text.replace(gallery_re, newtext);
return this;
Line 5,076 ⟶ 5,054:
*/
removeTemplate: function(template) {
varconst template_re_string = Morebits.pageNameRegex(template);
varconst links_re = new RegExp('\\{\\{(?:' + Morebits.namespaceRegex(10) + ':)?\\s*' + template_re_string + '\\s*[\\|(?:\\}\\})]');
varconst allTemplates = Morebits.string.splitWeightedByKeys(this.text, '{{', '}}', [ '{{{', '}}}' ]);
for (varlet i = 0; i < allTemplates.length; ++i) {
if (links_re.test(allTemplates[i])) {
this.text = this.text.replace(allTemplates[i], '');
Line 5,201 ⟶ 5,179:
*/
this.log = function(logText, summaryText) {
varconst def = $.Deferred();
if (!logText) {
return def.reject();
}
varconst page = new Morebits.wiki.page('User:' + mw.config.get('wgUserName') + '/' + logPageName,
'Adding entry to userspace log'); // make this '... to ' + logPageName ?
page.load(function(pageobj) => {
// add blurb if log page doesn't exist or is blank
varlet text = pageobj.getPageText() || this.initialText;
 
// create monthly header if it doesn't exist already
varconst date = new Morebits.date(pageobj.getLoadTime());
if (!date.monthHeaderRegex().exec(text)) {
text += '\n\n' + date.monthHeader(this.headerLevel);
Line 5,222 ⟶ 5,200:
pageobj.setCreateOption('recreate');
pageobj.save(def.resolve, def.reject);
}.bind(this));
return def;
};
Line 5,416 ⟶ 5,394:
*/
Morebits.status.actionCompleted = function(text) {
varconst node = document.createElement('div');
node.appendChild(document.createElement('b')).appendChild(document.createTextNode(text));
node.className = 'morebits_status_info morebits_action_complete';
Line 5,433 ⟶ 5,411:
*/
Morebits.status.printUserText = function(comments, message) {
varconst p = document.createElement('p');
p.innerHTML = message;
varconst div = document.createElement('div');
div.className = 'morebits-usertext';
div.style.marginTop = '0';
Line 5,455 ⟶ 5,433:
*/
Morebits.htmlNode = function (type, content, color) {
varconst node = document.createElement(type);
if (color) {
node.style.color = color;
Line 5,474 ⟶ 5,452:
*/
Morebits.checkboxShiftClickSupport = function (jQuerySelector, jQueryContext) {
varlet lastCheckbox = null;
 
function clickHandler(event) {
varconst thisCb = this;
if (event.shiftKey && lastCheckbox !== null) {
varconst cbs = $(jQuerySelector, jQueryContext); // can't cache them, obviously, if we want to support resorting
varlet index = -1, lastIndex = -1, i;
for (i = 0; i < cbs.length; i++) {
if (cbs[i] === thisCb) {
Line 5,498 ⟶ 5,476:
if (index > -1 && lastIndex > -1) {
// inspired by wikibits
varconst endState = thisCb.checked;
varlet start, finish;
if (index < lastIndex) {
start = index + 1;
Line 5,563 ⟶ 5,541:
*/
Morebits.batchOperation = function(currentAction) {
varconst ctx = {
// backing fields for public properties
pageList: null,
Line 5,637 ⟶ 5,615:
ctx.pageChunks = [];
 
varconst total = ctx.pageList.length;
if (!total) {
ctx.statusElement.info(msg('batch-no-pages', 'no pages specified'));
Line 5,669 ⟶ 5,647:
if (arg instanceof Morebits.wiki.api || arg instanceof Morebits.wiki.page) {
// update or remove status line
varconst statelem = arg.getStatusElement();
if (ctx.options.preserveIndividualStatusLines) {
if (arg.getPageName || arg.pageName || (arg.query && arg.query.title)) {
// we know the page title - display a relevant message
varconst pageName = arg.getPageName ? arg.getPageName() : arg.pageName || arg.query.title;
statelem.info(msg('batch-done-page', pageName, 'completed ([[' + pageName + ']])'));
} else {
Line 5,698 ⟶ 5,676:
// private functions
 
varconst thisProxy = this;
 
var fnStartNewChunk = function() {
varconst chunk = ctx.pageChunks[++ctx.currentChunkIndex];
if (!chunk) {
return; // done! yay
Line 5,708 ⟶ 5,686:
// start workers for the current chunk
ctx.countStarted += chunk.length;
chunk.forEach(function(page) => {
ctx.worker(page, thisProxy);
});
Line 5,717 ⟶ 5,695:
 
// update overall status line
varconst total = ctx.pageList.length;
if (ctx.countFinished < total) {
varconst progress = Math.round(100 * ctx.countFinished / total);
ctx.statusElement.status(msg('percent', progress, progress + '%'));
 
Line 5,729 ⟶ 5,707:
}
} else if (ctx.countFinished === total) {
varconst statusString = msg('batch-progress', ctx.countFinishedSuccess, ctx.countFinished, 'Done (' + ctx.countFinishedSuccess +
'/' + ctx.countFinished + ' actions completed successfully)');
if (ctx.countFinishedSuccess < ctx.countFinished) {
Line 5,781 ⟶ 5,759:
this.add = function(func, deps, onFailure) {
this.taskDependencyMap.set(func, deps);
this.failureCallbackMap.set(func, onFailure || function(() => {}));
varconst deferred = $.Deferred();
this.deferreds.set(func, deferred);
};
Line 5,792 ⟶ 5,770:
*/
this.execute = function() {
varconst self = this; // proxy for `this` for use inside functions where `this` is something else
this.taskDependencyMap.forEach(function(deps, task) => {
varconst dependencyPromisesArray = deps.map(function(dep) {=> self.deferreds.get(dep));
return self.deferreds.get(dep);
});
$.when.apply(self.context, dependencyPromisesArray).then(function() {
varconst result = task.apply(self.context, arguments);
if (result === undefined) { // maybe the function threw, or it didn't return anything
mw.log.error('Morebits.taskManager: task returned undefined');
Line 5,829 ⟶ 5,805:
*/
Morebits.simpleWindow = function SimpleWindow(width, height) {
varconst content = document.createElement('div');
this.content = content;
content.className = 'morebits-dialog-content';
Line 5,867 ⟶ 5,843:
});
 
varconst $widget = $(this.content).dialog('widget');
 
// delete the placeholder button (it's only there so the buttonpane gets created)
$widget.find('button').each(function(key, value) => {
value.parentNode.removeChild(value);
});
 
// add container for the buttons we add, and the footer links (if any)
varconst buttonspan = document.createElement('span');
buttonspan.className = 'morebits-dialog-buttons';
varconst linksspan = document.createElement('span');
linksspan.className = 'morebits-dialog-footerlinks';
$widget.find('.ui-dialog-buttonpane').append(buttonspan, linksspan);
Line 5,927 ⟶ 5,903:
display: function() {
if (this.scriptName) {
varconst $widget = $(this.content).dialog('widget');
$widget.find('.morebits-dialog-scriptname').remove();
varconst scriptnamespan = document.createElement('span');
scriptnamespan.className = 'morebits-dialog-scriptname';
scriptnamespan.textContent = this.scriptName + ' \u00B7 '; // U+00B7 MIDDLE DOT = &middot;
Line 5,935 ⟶ 5,911:
}
 
varconst dialog = $(this.content).dialog('open');
if (window.setupTooltips && window.pg && window.pg.re && window.pg.re.diff) { // tie in with NAVPOP
dialog.parent()[0].ranSetupTooltipsAlready = false;
Line 6,027 ⟶ 6,003:
 
// look for submit buttons in the content, hide them, and add a proxy button to the button pane
varconst thisproxy = this;
$(this.content).find('input[type="submit"], button[type="submit"]').each(function(key, value) => {
value.style.display = 'none';
varconst button = document.createElement('button');
 
if (value.hasAttribute('value')) {
Line 6,042 ⟶ 6,018:
button.className = value.className || 'submitButtonProxy';
// here is an instance of cheap coding, probably a memory-usage hit in using a closure here
button.addEventListener('click', function() => {
value.click();
}, false);
Line 6,084 ⟶ 6,060:
*/
addFooterLink: function(text, wikiPage, prep) {
varconst $footerlinks = $(this.content).dialog('widget').find('.morebits-dialog-footerlinks');
if (this.hasFooterLinks) {
varconst bullet = document.createElement('span');
bullet.textContent = msg('bullet-separator', ' \u2022 '); // U+2022 BULLET
if (prep) {
Line 6,094 ⟶ 6,070:
}
}
varconst link = document.createElement('a');
link.setAttribute('href', mw.util.getUrl(wikiPage));
link.setAttribute('title', wikiPage);