MediaWiki:Gadget-morebits.js: Difference between revisions

Content deleted Content added
Maintenance: mw:RL/MGU - Updated deprecated module name
Repo at ac3c1e3: replace es-x/no-array-prototype-includes with unicorn/prefer-includes (#2125)
 
(16 intermediate revisions by 3 users not shown)
Line 34:
*/
 
(function() {
 
(function (window, document, $) { // Wrap entire file with anonymous function
 
/** @lends Morebits */
varconst Morebits = {};
window.Morebits = Morebits; // allow global access
 
/**
* i18n support for strings in Morebits
*/
Morebits.i18n = {
parser: null,
/**
* Set an i18n library to use with Morebits.
* Examples:
* Use jquery-i18n:
* Morebits.i18n.setParser({ get: $.i18n });
* Use banana-i18n or orange-i18n:
* var banana = new Banana('en');
* Morebits.i18n.setParser({ get: banana.i18n });
*
* @param {Object} parser
*/
setParser: function(parser) {
if (!parser || typeof parser.get !== 'function') {
throw new Error('Morebits.i18n: parser must implement get()');
}
Morebits.i18n.parser = parser;
},
/**
* @private
* @return {string}
*/
getMessage: function () {
const 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
const msgName = args[0];
const fallback = args[args.length - 1];
if (!Morebits.i18n.parser) {
return fallback;
}
// i18n libraries are generally invoked with variable number of arguments
// as msg(msgName, ...parameters)
const 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) {
return fallback;
}
return i18nMessage;
}
};
 
// shortcut
const msg = Morebits.i18n.getMessage;
 
/**
* Wiki-specific configurations for Morebits
*/
Morebits.l10n = {
/**
* Local aliases for "redirect" magic word.
* Check using api.php?action=query&format=json&meta=siteinfo&formatversion=2&siprop=magicwords
*/
redirectTagAliases: ['#REDIRECT'],
 
/**
* Takes a string as argument and checks if it is a timestamp or not
* If not, it returns null. If yes, it returns an array of integers
* in the format [year, month, date, hour, minute, second]
* which can be passed to Date.UTC()
*
* @param {string} str
* @return {number[] | null}
*/
signatureTimestampFormat: function (str) {
// HH:mm, DD Month YYYY (UTC)
const rgx = /(\d{2}):(\d{2}), (\d{1,2}) (\w+) (\d{4}) \(UTC\)/;
const match = rgx.exec(str);
if (!match) {
return null;
}
const month = Morebits.date.localeData.months.indexOf(match[4]);
if (month === -1) {
return null;
}
// ..... year ... month .. date ... hour .... minute
return [match[5], month, match[3], match[1], match[2]];
}
};
 
/**
Line 46 ⟶ 129:
*
* @param {string} group - e.g. `sysop`, `extendedconfirmed`, etc.
* @returnsreturn {boolean}
*/
Morebits.userIsInGroup = function (group) {
return mw.config.get('wgUserGroups').indexOfincludes(group) !== -1;
};
/**
/** Hardcodes whether the user is a sysop, used a lot.
* Hardcodes whether the user is a sysop, used a lot.
*
* @type {boolean}
Line 67 ⟶ 151:
*
* @param {string} address - The IPv6 address, with or without CIDR.
* @returnsreturn {string}
*/
Morebits.sanitizeIPv6 = function (address) {
Line 79 ⟶ 163:
* detect Module:RfD, with the same failure points.
*
* @returnsreturn {boolean}
*/
Morebits.isPageRedirect = function() {
Line 92 ⟶ 176:
*/
Morebits.pageNameNorm = mw.config.get('wgPageName').replace(/_/g, ' ');
 
 
/**
Line 100 ⟶ 183:
*
* @param {string} pageName - Page name without namespace.
* @returnsreturn {string} - For a page name `Foo bar`, returns the string `[Ff]oo[_ ]bar`.
*/
Morebits.pageNameRegex = function(pageName) {
Line 106 ⟶ 189:
return '';
}
varconst firstChar = pageName[0],
remainder = Morebits.string.escapeRegExp(pageName.slice(1));
if (mw.Title.phpCharToUpper(firstChar) !== firstChar.toLowerCase()) {
Line 112 ⟶ 195:
}
return Morebits.string.escapeRegExp(firstChar) + remainder;
};
 
/**
* Converts string or array of DOM nodes into an HTML fragment.
* Wikilink syntax (`[[...]]`) is transformed into HTML anchor.
* Used in Morebits.quickForm and Morebits.status
*
* @internal
* @param {string|Node|(string|Node)[]} input
* @return {DocumentFragment}
*/
Morebits.createHtml = function(input) {
const fragment = document.createDocumentFragment();
if (!input) {
return fragment;
}
if (!Array.isArray(input)) {
input = [ input ];
}
for (let i = 0; i < input.length; ++i) {
if (input[i] instanceof Node) {
fragment.appendChild(input[i]);
} else {
$.parseHTML(Morebits.createHtml.renderWikilinks(input[i])).forEach((node) => {
fragment.appendChild(node);
});
}
}
return fragment;
};
 
/**
* Converts wikilinks to HTML anchor tags.
*
* @param text
* @return {*}
*/
Morebits.createHtml.renderWikilinks = function (text) {
const 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,
(_, target, text) => {
if (!target) {
target = text;
}
return '<a target="_blank" href="' + mw.util.getUrl(target) +
'" title="' + target.replace(/"/g, '&#34;') + '">' + text + '</a>';
});
return ub.rebind();
};
 
Line 127 ⟶ 261:
* // returns '(?:[Ff][Ii][Ll][Ee]|[Ii][Mm][Aa][Gg][Ee])'
* Morebits.namespaceRegex([6])
* @returnsreturn {string} - Regex-suitable string of all namespace aliases.
*/
Morebits.namespaceRegex = function(namespaces) {
Line 133 ⟶ 267:
namespaces = [namespaces];
}
varconst aliases = [],;
let regex;
$.each(mw.config.get('wgNamespaceIds'), function(name, number) => {
if (namespaces.indexOfincludes(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 157 ⟶ 290:
return regex;
};
 
 
/* **************** Morebits.quickForm **************** */
Line 177 ⟶ 309:
*
* @memberof Morebits.quickForm
* @returnsreturn {HTMLElement}
*/
Morebits.quickForm.prototype.render = function QuickFormRender() {
varconst ret = this.root.render();
ret.names = {};
return ret;
Line 191 ⟶ 323:
* @param {(object|Morebits.quickForm.element)} data - A quickform element, or the object with which
* a quickform element is constructed.
* @returnsreturn {Morebits.quickForm.element} - Same as what is passed to the function.
*/
Morebits.quickForm.prototype.append = function QuickFormAppend(data) {
Line 201 ⟶ 333:
*
* Index to Morebits.quickForm.element types:
* - Global attributes: id, className, style, tooltip, extra, $data, adminonly
* - `select`: A combo box (aka drop-down).
* - Attributes: name, label, multiple, size, list, event, disabled
Line 221 ⟶ 353:
* - Attributes: Everything the text `input` has, as well as: min, max, step, list
* - `dyninput`: A set of text boxes with "Remove" buttons and an "Add" button.
* - Attributes: name, label, min, max, inputs, sublabel, value, size, maxlength, event
* - `hidden`: An invisible form field.
* - Attributes: name, value
Line 236 ⟶ 368:
* - `fragment`: A DocumentFragment object.
* - No attributes, and no global attributes except adminonly.
* There is some difference on how types handle the `label` attribute:
* - `div`, `select`, `field`, `checkbox`/`radio`, `input`, `textarea`, `header`, and `dyninput` can accept an array of items,
* and the label item(s) can be `Element`s.
* - `option`, `optgroup`, `_dyninput_cell`, `submit`, and `button` accept only a single string.
*
* @memberof Morebits.quickForm
* @class
* @param {objectObject} data - Object representing the quickform element. Should
* specify one of the available types from the index above, as well as any
* relevant and available attributes.
Line 253 ⟶ 389:
this.data = data;
this.childs = [];
this.id = Morebits.quickForm.element.id++;
};
 
Line 268 ⟶ 403:
* @param {Morebits.quickForm.element} data - A quickForm element or the object required to
* create the quickForm element.
* @returnsreturn {Morebits.quickForm.element} The same element passed in.
*/
Morebits.quickForm.element.prototype.append = function QuickFormElementAppend(data) {
varlet child;
if (data instanceof Morebits.quickForm.element) {
child = data;
Line 286 ⟶ 421:
*
* @memberof Morebits.quickForm.element
* @returnsreturn {HTMLElement}
*/
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 300 ⟶ 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_' + thisMorebits.quickForm.element.id++;
if (data.adminonly && !Morebits.userIsSysop) {
// hell hack alpha
Line 309 ⟶ 444:
}
 
varlet i, current, subnode;
switch (data.type) {
case 'form':
Line 323 ⟶ 458:
// fragments can't have any attributes, so just return it straight away
return [ node, node ];
// Sometimes Twinkle uses fancy searchable "select" elements. This is powered by the third party library "select2". Activate it by creating a Morebits "select" element, then call `$('select[name=sub_group]').select2({});` or similar towards the end of your main code.
case 'select':
node = document.createElement('div');
Line 330 ⟶ 466:
label = node.appendChild(document.createElement('label'));
label.setAttribute('for', id);
label.appendChild(documentMorebits.createTextNodecreateHtml(data.label));
label.style.marginRight = '3px';
}
var select = node.appendChild(document.createElement('select'));
Line 395 ⟶ 532:
node = document.createElement('fieldset');
label = node.appendChild(document.createElement('legend'));
label.appendChild(documentMorebits.createTextNodecreateHtml(data.label));
if (data.name) {
node.setAttribute('name', data.name);
Line 408 ⟶ 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 442 ⟶ 579:
}
label = cur_div.appendChild(document.createElement('label'));
 
label.appendChild(document.createTextNode(current.label));
label.appendChild(Morebits.createHtml(current.label));
label.setAttribute('for', cur_id);
if (current.tooltip) {
Line 454 ⟶ 592:
var event;
if (current.subgroup) {
varlet tmpgroup = current.subgroup;
 
if (!Array.isArray(tmpgroup)) {
Line 464 ⟶ 602:
id: id + '_' + i + '_subgroup'
});
$.each(tmpgroup, function(idx, el) => {
varconst newEl = $.extend({}, el);
if (!newEl.type) {
newEl.type = data.type;
Line 473 ⟶ 611:
});
 
varconst subgroup = subgroupRaw.render(cur_id);
subgroup.className = 'quickformSubgroup';
subnode.subgroup = subgroup;
Line 482 ⟶ 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 499 ⟶ 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 528 ⟶ 666:
if (data.label) {
label = node.appendChild(document.createElement('label'));
label.appendChild(documentMorebits.createTextNodecreateHtml(data.label));
label.setAttribute('for', data.id || id);
label.style.marginRight = '3px';
}
 
Line 539 ⟶ 678:
} else {
subnode.setAttribute('type', 'number');
['min', 'max', 'step', 'list'].forEach(function(att) => {
if (data[att]) {
subnode.setAttribute(att, data[att]);
Line 546 ⟶ 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 569 ⟶ 708:
 
label = node.appendChild(document.createElement('h5'));
label.appendChild(documentMorebits.createTextNodecreateHtml(data.label));
 
var listNode = node.appendChild(document.createElement('div'));
 
Line 578 ⟶ 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 592 ⟶ 730:
 
var sublist = {
type: '_dyninput_element_dyninput_row',
label: data.sublabel || data.label,
name: data.name,
value: data.value,
size: data.size,
remove: false,
maxlength: data.maxlength,
event: data.event,
inputs: data.inputs || [{
// compatibility
label: data.sublabel || data.label,
name: data.name,
value: data.value,
size: data.size
}]
};
 
for (i = 0; i < min; ++i) {
varconst elem = new Morebits.quickForm.element(sublist);
listNode.appendChild(elem.render());
}
Line 615 ⟶ 756:
moreButton.counter = 0;
break;
case '_dyninput_element_dyninput_row': // Private, similar to normal input
node = document.createElement('div');
 
data.inputs.forEach((subdata) => {
const cell = new Morebits.quickForm.element($.extend(subdata, { type: '_dyninput_cell' }));
node.appendChild(cell.render());
});
if (data.remove) {
const remove = this.compute({
type: 'button',
label: 'remove',
event: function(e) {
const list = e.target.listnode;
const node = e.target.inputnode;
const more = e.target.morebutton;
 
list.removeChild(node);
--more.counter;
more.removeAttribute('disabled');
e.stopPropagation();
}
});
node.appendChild(remove[0]);
const removeButton = remove[1];
removeButton.inputnode = node;
removeButton.listnode = data.listnode;
removeButton.morebutton = data.morebutton;
}
break;
case '_dyninput_cell': // Private, similar to normal input
node = document.createElement('span');
 
if (data.label) {
label = node.appendChild(document.createElement('label'));
label.appendChild(document.createTextNode(data.label));
label.setAttribute('for', id + '_input');
label.style.marginRight = '3px';
}
 
subnode = node.appendChild(document.createElement('input'));
subnode.setAttribute('id', id + '_input');
if (data.value) {
subnode.setAttribute('value', data.value);
Line 630 ⟶ 802:
subnode.setAttribute('name', data.name);
subnode.setAttribute('type', 'text');
subnode.setAttribute('data-dyninput', 'data-dyninput');
if (data.size) {
subnode.setAttribute('size', data.size);
Line 635 ⟶ 808:
if (data.maxlength) {
subnode.setAttribute('maxlength', data.maxlength);
}
if (data.required) {
subnode.setAttribute('required', 'required');
}
if (data.disabled) {
subnode.setAttribute('required', 'disabled');
}
if (data.event) {
subnode.addEventListener('keyup', data.event, false);
}
node.style.marginRight = '3px';
if (data.remove) {
var remove = this.compute({
type: 'button',
label: 'remove',
event: function(e) {
var list = e.target.listnode;
var node = e.target.inputnode;
var more = e.target.morebutton;
 
list.removeChild(node);
--more.counter;
more.removeAttribute('disabled');
e.stopPropagation();
}
});
node.appendChild(remove[0]);
var removeButton = remove[1];
removeButton.inputnode = node;
removeButton.listnode = data.listnode;
removeButton.morebutton = data.morebutton;
}
break;
case 'hidden':
Line 670 ⟶ 829:
case 'header':
node = document.createElement('h5');
node.appendChild(documentMorebits.createTextNodecreateHtml(data.label));
break;
case 'div':
Line 678 ⟶ 837:
}
if (data.label) {
const result = document.createElement('span');
if (!Array.isArray(data.label)) {
data.label = [ data.label ];
}
var result = document.createElement('span');
result.className = 'quickformDescription';
for result.appendChild(Morebits.createHtml(i = 0; i < data.label.length; ++i) {);
if (typeof data.label[i] === 'string') {
result.appendChild(document.createTextNode(data.label[i]));
} else if (data.label[i] instanceof Element) {
result.appendChild(data.label[i]);
}
}
node.appendChild(result);
}
Line 725 ⟶ 875:
if (data.label) {
label = node.appendChild(document.createElement('h5'));
varconst labelElement = document.createElement('label');
labelElement.textContent = appendChild(Morebits.createHtml(data.label));
labelElement.setAttribute('for', data.id || id);
label.appendChild(labelElement);
Line 765 ⟶ 915:
if (data.extra) {
childContainer.extra = data.extra;
}
if (data.$data) {
$(childContainer).data(data.$data);
}
if (data.style) {
Line 783 ⟶ 936:
*
* @memberof Morebits.quickForm.element
* @requires jqueryjQuery.ui
* @param {HTMLElement} node - The HTML element beside which a tooltip is to be generated.
* @param {objectObject} data - Tooltip-related configuration data.
*/
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
tooltipButton.appendChild(document.createTextNode(msg('tooltip-mark', '?')));
$(tooltipButton).tooltip({
position: { my: 'left top', at: 'center bottom', collision: 'flipfit' },
Line 798 ⟶ 951:
});
};
 
 
// Some utility methods for manipulating quickForms after their creation:
Line 809 ⟶ 961:
* @memberof Morebits.quickForm
* @param {HTMLFormElement} form
* @returnsreturn {objectObject} With field names as keys, input data as values.
*/
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 823 ⟶ 975:
// 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 846 ⟶ 998:
case 'text': // falls through
case 'textarea':
result[fieldNameNorm] =if (field.valuedataset.trim(dyninput); {
result[fieldNameNorm] = result[fieldNameNorm] || [];
result[fieldNameNorm].push(field.value.trim());
} else {
result[fieldNameNorm] = field.value.trim();
}
break;
default: // could be select-one, date, number, email, etc
Line 857 ⟶ 1,014:
return result;
};
 
 
/**
Line 865 ⟶ 1,021:
* @param {HTMLFormElement} form
* @param {string} fieldName - The name or id of the fields.
* @returnsreturn {HTMLElement[]} - Array of matching form elements.
*/
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 885 ⟶ 1,041:
* @param {HTMLInputElement[]} elementArray - Array of checkbox or radio elements.
* @param {string} value - Value to search for.
* @returnsreturn {HTMLInputElement}
*/
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 903 ⟶ 1,057:
* @memberof Morebits.quickForm
* @param {HTMLElement} element
* @returnsreturn {HTMLElement}
*/
Morebits.quickForm.getElementContainer = function QuickFormGetElementContainer(element) {
Line 922 ⟶ 1,076:
* @memberof Morebits.quickForm
* @param {(HTMLElement|Morebits.quickForm.element)} element
* @returnsreturn {HTMLElement}
*/
Morebits.quickForm.getElementLabelObject = function QuickFormGetElementLabelObject(element) {
Line 945 ⟶ 1,099:
* @memberof Morebits.quickForm
* @param {(HTMLElement|Morebits.quickForm.element)} element
* @returnsreturn {string}
*/
Morebits.quickForm.getElementLabel = function QuickFormGetElementLabel(element) {
varconst labelElement = Morebits.quickForm.getElementLabelObject(element);
 
if (!labelElement) {
Line 962 ⟶ 1,116:
* @param {(HTMLElement|Morebits.quickForm.element)} element
* @param {string} labelText
* @returnsreturn {boolean} True if succeeded, false if the label element is unavailable.
*/
Morebits.quickForm.setElementLabel = function QuickFormSetElementLabel(element, labelText) {
varconst labelElement = Morebits.quickForm.getElementLabelObject(element);
 
if (!labelElement) {
Line 980 ⟶ 1,134:
* @param {(HTMLElement|Morebits.quickForm.element)} element
* @param {string} temporaryLabelText
* @returnsreturn {boolean} `true` if succeeded, `false` if the label element is unavailable.
*/
Morebits.quickForm.overrideElementLabel = function QuickFormOverrideElementLabel(element, temporaryLabelText) {
Line 994 ⟶ 1,148:
* @memberof Morebits.quickForm
* @param {(HTMLElement|Morebits.quickForm.element)} element
* @returnsreturn {boolean} True if succeeded, false if the label element is unavailable.
*/
Morebits.quickForm.resetElementLabel = function QuickFormResetElementLabel(element) {
Line 1,024 ⟶ 1,178:
$(Morebits.quickForm.getElementContainer(element)).find('.morebits-tooltipButton').toggle(visibility);
};
 
 
 
/**
Line 1,033 ⟶ 1,185:
* Get checked items in the form.
*
* @functionmethod external:HTMLFormElement.getChecked
* @param {string} name - Find checked property of elements (i.e. a checkbox
* or a radiobutton) with the given name, or select options that have selected
Line 1,039 ⟶ 1,191:
* @param {string} [type] - Optionally specify either radio or checkbox (for
* the event that both checkboxes and radiobuttons have the same name).
* @returnsreturn {string[]} - Contains the values of elements with the given name
* checked property set to true.
*/
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,087 ⟶ 1,239:
* Does the same as {@link HTMLFormElement.getChecked|getChecked}, but with unchecked elements.
*
* @functionmethod external:HTMLFormElement.getUnchecked
* @param {string} name - Find checked property of elements (i.e. a checkbox
* or a radiobutton) with the given name, or select options that have selected
Line 1,093 ⟶ 1,245:
* @param {string} [type] - Optionally specify either radio or checkbox (for
* the event that both checkboxes and radiobuttons have the same name).
* @returnsreturn {string[]} - Contains the values of elements with the given name
* checked property set to true.
*/
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,152 ⟶ 1,304:
*
* @param {string} address - The IPv6 address, with or without CIDR.
* @returnsreturn {string}
*/
sanitizeIPv6: function (address) {
Line 1,165 ⟶ 1,317:
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,188 ⟶ 1,340:
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,205 ⟶ 1,357:
*
* @param {string} ip
* @returnsreturn {boolean} - True if given a valid IP address range, false otherwise.
*/
isRange: function (ip) {
Line 1,216 ⟶ 1,368:
* for IPv4 and /32 for IPv6.
*
* @returnsreturn {boolean} - True for valid ranges within the CIDR limits,
* otherwise false (ranges outside the limit, single IPs, non-IPs).
*/
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,241 ⟶ 1,393:
*
* @param {string} ipv6 - The IPv6 address, with or without a subnet.
* @returnsreturn {boolean|string} - False if not IPv6 or bigger than a 64,
* otherwise the (sanitized) /64 address.
*/
Line 1,248 ⟶ 1,400:
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})?$/;
// eslint-disable-next-line no-useless-concat
return ipv6.replace(ip_re, '$1' + '0:0:0:0/64');
}
};
 
 
/**
* @external RegExp
*/
/**
* Deprecated as of September 2020, use {@link Morebits.string.escapeRegExp}
* or `mw.util.escapeRegExp`.
*
* @function external:RegExp.escape
* @deprecated Use {@link Morebits.string.escapeRegExp} or `mw.util.escapeRegExp`.
* @param {string} text - String to be escaped.
* @param {boolean} [space_fix=false] - Whether to replace spaces and
* underscores with `[ _]` as they are often equivalent.
* @returns {string} - The escaped text.
*/
RegExp.escape = function(text, space_fix) {
if (space_fix) {
console.error('NOTE: RegExp.escape from Morebits was deprecated September 2020, please replace it with Morebits.string.escapeRegExp'); // eslint-disable-line no-console
return Morebits.string.escapeRegExp(text);
}
console.error('NOTE: RegExp.escape from Morebits was deprecated September 2020, please replace it with mw.util.escapeRegExp'); // eslint-disable-line no-console
return mw.util.escapeRegExp(text);
};
 
 
/**
Line 1,292 ⟶ 1,420:
/**
* @param {string} str
* @returnsreturn {string}
*/
toUpperCaseFirstChar: function(str) {
str = str.toString();
return str.substrslice(0, 1).toUpperCase() + str.substrslice(1);
},
/**
* @param {string} str
* @returnsreturn {string}
*/
toLowerCaseFirstChar: function(str) {
str = str.toString();
return str.substrslice(0, 1).toLowerCase() + str.substrslice(1);
},
 
Line 1,316 ⟶ 1,444:
* @param {string} end
* @param {(string[]|string)} [skiplist]
* @returnsreturn {string[]}
* @throws If the `start` and `end` strings aren't of the same length.
* @throws If `skiplist` isn't an array or string
Line 1,324 ⟶ 1,452:
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,336 ⟶ 1,464:
}
}
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,370 ⟶ 1,498:
* @param {string} str
* @param {boolean} [addSig]
* @returnsreturn {string}
*/
formatReasonText: function(str, addSig) {
varlet reason = (str || '').toString().trim();
varconst unbinder = new Morebits.unbinder(reason);
// eslint-disable-next-line no-useless-concat
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,393 ⟶ 1,522:
*
* @param {string} str
* @returnsreturn {string}
*/
formatReasonForLog: function(str) {
Line 1,413 ⟶ 1,542:
* @param {(string|RegExp)} pattern
* @param {string} replacement
* @returnsreturn {string}
*/
safeReplace: function morebitsStringSafeReplace(string, pattern, replacement) {
Line 1,426 ⟶ 1,555:
*
* @param {string} expiry
* @returnsreturn {boolean}
*/
isInfinity: function morebitsStringIsInfinity(expiry) {
return ['indefinite', 'infinity', 'infinite', 'never'].indexOfincludes(expiry) !== -1;
},
 
Line 1,435 ⟶ 1,564:
* Escapes a string to be used in a RegExp, replacing spaces and
* underscores with `[_ ]` as they are often equivalent.
* Replaced RegExp.escape September 2020.
*
* @param {string} text - String to be escaped.
* @returnsreturn {string} - The escaped text.
*/
escapeRegExp: function(text) {
Line 1,444 ⟶ 1,572:
}
};
 
 
/**
Line 1,457 ⟶ 1,584:
*
* @param {Array} arr
* @returnsreturn {Array} A copy of the array with duplicates removed.
* @throws When provided a non-array.
*/
uniq: function(arr) {
if (!Array.isArray(arr)) {
throw new Error('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,473 ⟶ 1,598:
*
* @param {Array} arr
* @returnsreturn {Array} A copy of the array with the first instance of each value
* removed; subsequent instances of those values (duplicates) remain.
* @throws When provided a non-array.
Line 1,479 ⟶ 1,604:
dups: function(arr) {
if (!Array.isArray(arr)) {
throw new Error('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,492 ⟶ 1,614:
* @param {Array} arr
* @param {number} size - Size of each chunk (except the last, which could be different).
* @returnsreturn {Array[]} An array containing the smaller, chunked arrays.
* @throws When provided a non-array.
*/
chunk: function(arr, size) {
if (!Array.isArray(arr)) {
throw new Error('A non-array object passed to Morebits.array.chunk');
}
if (typeof size !== 'number' || size <= 0) { // pretty impossible to do anything :)
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,519 ⟶ 1,641:
* @namespace Morebits.select2
* @memberof Morebits
* @requires jqueryjQuery.select2
*/
Morebits.select2 = {
Line 1,528 ⟶ 1,650:
*/
optgroupFull: function(params, data) {
varconst originalMatcher = $.fn.select2.defaults.defaults.matcher;
varconst result = originalMatcher(params, data);
 
if (result && params.term &&
data.text.toUpperCase().indexOfincludes(params.term.toUpperCase()) !== -1) {
result.children = data.children;
}
Line 1,540 ⟶ 1,662:
/** 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,552 ⟶ 1,674:
/** 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,583 ⟶ 1,705:
return;
}
varlet $target = $(ev.target).closest('.select2-container');
if (!$target.length) {
return;
}
$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)
search.focus();
search[0].focus();
}
 
};
 
 
/**
Line 1,635 ⟶ 1,757:
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,642 ⟶ 1,764:
* Restore the hidden portion of the `content` string.
*
* @returnsreturn {string} The processed output.
*/
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,663 ⟶ 1,785:
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,669 ⟶ 1,791:
};
};
 
 
 
/* **************** Morebits.date **************** */
Line 1,682 ⟶ 1,802:
*/
Morebits.date = function() {
varconst args = Array.prototype.slice.call(arguments);
 
// Check MediaWiki formats
Line 1,689 ⟶ 1,809:
// 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
this._dprivateDate = new Date(Date.UTC.apply(null, [digitMatch[1], digitMatch[2] - 1, digitMatch[3], digitMatch[4], digitMatch[5], digitMatch[6]]));
}
} else if (typeof param === 'string') {
// Wikitext signature timestamp
varconst dateParts = Morebits.date.localeDatal10n.signatureTimestampFormat(param);
if (dateParts) {
this._dprivateDate = new Date(Date.UTC.apply(null, dateParts));
}
}
}
 
if (!this._dprivateDate) {
// Try standard date
this._dprivateDate = new (Function.prototype.bind.apply(Date, [Date].concat(args)))();
}
 
Line 1,730 ⟶ 1,850:
*/
Morebits.date.localeData = {
// message names here correspond to MediaWiki message names
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
months: [msg('january', 'January'), msg('february', 'February'), msg('march', 'March'),
monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
days: ['Sunday', msg('Mondayapril', 'TuesdayApril'), msg('Wednesdaymay_long', 'ThursdayMay'), msg('Fridayjune', 'SaturdayJune']),
daysShort: ['Sun', msg('Monjuly', 'TueJuly'), msg('Wedaugust', 'ThuAugust'), msg('Friseptember', 'SatSeptember']),
msg('october', 'October'), msg('november', 'November'), msg('december', 'December')],
monthsShort: [msg('jan', 'Jan'), msg('feb', 'Feb'), msg('mar', 'Mar'),
msg('apr', 'Apr'), msg('may', 'May'), msg('jun', 'Jun'),
msg('jul', 'Jul'), msg('aug', 'Aug'), msg('sep', 'Sep'),
msg('oct', 'Oct'), msg('nov', 'Nov'), msg('dec', 'Dec')],
days: [msg('sunday', 'Sunday'), msg('monday', 'Monday'), msg('tuesday', 'Tuesday'),
msg('wednesday', 'Wednesday'), msg('thursday', 'Thursday'), msg('friday', 'Friday'),
msg('saturday', 'Saturday')],
daysShort: [msg('sun', 'Sun'), msg('mon', 'Mon'), msg('tue', 'Tue'),
msg('wed', 'Wed'), msg('thu', 'Thu'), msg('fri', 'Fri'),
msg('sat', 'Sat')],
 
relativeTimes: {
thisDay: msg('relative-today', '[Today at] h:mm A'),
prevDay: msg('relative-prevday', '[Yesterday at] h:mm A'),
nextDay: msg('relative-nextday', '[Tomorrow at] h:mm A'),
thisWeek: msg('relative-thisweek', 'dddd [at] h:mm A'),
pastWeek: msg('relative-pastweek', '[Last] dddd [at] h:mm A'),
other: msg('relative-other', 'YYYY-MM-DD')
},
signatureTimestampFormat: function (str) {
// HH:mm, DD Month YYYY (UTC)
var rgx = /(\d{2}):(\d{2}), (\d{1,2}) (\w+) (\d{4}) \(UTC\)/;
var match = rgx.exec(str);
if (!match) {
return null;
}
var month = Morebits.date.localeData.months.indexOf(match[4]);
if (month === -1) {
return null;
}
// ..... year ... month .. date ... hour .... minute
return [match[5], month, match[3], match[1], match[2]];
}
};
Line 1,783 ⟶ 1,901:
 
Morebits.date.prototype = {
/** @returnsreturn {boolean} */
isValid: function() {
return !isNaN(this.getTime());
Line 1,790 ⟶ 1,908:
/**
* @param {(Date|Morebits.date)} date
* @returnsreturn {boolean}
*/
isBefore: function(date) {
Line 1,797 ⟶ 1,915:
/**
* @param {(Date|Morebits.date)} date
* @returnsreturn {boolean}
*/
isAfter: function(date) {
Line 1,803 ⟶ 1,921:
},
 
/** @returnsreturn {string} */
getUTCMonthName: function() {
return Morebits.date.localeData.months[this.getUTCMonth()];
},
/** @returnsreturn {string} */
getUTCMonthNameAbbrev: function() {
return Morebits.date.localeData.monthsShort[this.getUTCMonth()];
},
/** @returnsreturn {string} */
getMonthName: function() {
return Morebits.date.localeData.months[this.getMonth()];
},
/** @returnsreturn {string} */
getMonthNameAbbrev: function() {
return Morebits.date.localeData.monthsShort[this.getMonth()];
},
/** @returnsreturn {string} */
getUTCDayName: function() {
return Morebits.date.localeData.days[this.getUTCDay()];
},
/** @returnsreturn {string} */
getUTCDayNameAbbrev: function() {
return Morebits.date.localeData.daysShort[this.getUTCDay()];
},
/** @returnsreturn {string} */
getDayName: function() {
return Morebits.date.localeData.days[this.getDay()];
},
/** @returnsreturn {string} */
getDayNameAbbrev: function() {
return Morebits.date.localeData.daysShort[this.getDay()];
Line 1,843 ⟶ 1,961:
* @param {string} unit
* @throws If invalid or unsupported unit is given.
* @returnsreturn {Morebits.date}
*/
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
// Probably can't be used for Julian->Gregorian changeovers, etc.
if (unitNorm === 'Week') {
unitNorm = 'Date', ;
num *= 7;
}
this['set' + unitNorm](this['get' + unitNorm]() + num);
Line 1,872 ⟶ 1,991:
* @param {string} unit
* @throws If invalid or unsupported unit is given.
* @returnsreturn {Morebits.date}
*/
subtract: function(number, unit) {
Line 1,885 ⟶ 2,004:
* |--------|--------|
* | H | Hours (24-hour) |
* | HH | Hours (24-hour, padded to 2 digits) |
* | h | Hours (12-hour) |
* | hh | Hours (12-hour, padded to 2 digits) |
* | A | AM or PM |
* | m | Minutes |
* | mm | Minutes (padded to 2 digits) |
* | s | Seconds |
* | ss | Seconds (padded to 2 digits) |
* | SSS | Milliseconds fragment, padded3 digits |
* | d | Day number of the week (Sun=0) |
* | ddd | Abbreviated day name |
* | dddd | Full day name |
* | D | Date |
* | DD | Date (padded to 2 digits) |
* | M | Month number (01-indexed) |
* | MM | Month number (01-indexed, padded to 2 digits) |
* | MMM | Abbreviated month name |
* | MMMM | Full month name |
Line 1,912 ⟶ 2,031:
* @param {(string|number)} [zone=system] - `system` (for browser-default time zone),
* `utc`, or specify a time zone as number of minutes relative to UTC.
* @returnsreturn {string}
*/
format: function(formatstr, zone) {
Line 1,918 ⟶ 2,037:
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 1,932 ⟶ 2,051:
}
 
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 1,950 ⟶ 2,069:
};
 
varconst unbinder = new Morebits.unbinder(formatstr); // escape stuff between [...]
unbinder.unbind('\\[', '\\]');
unbinder.content = unbinder.content.replace(
Line 1,958 ⟶ 2,077:
*/
/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 1,971 ⟶ 2,088:
* @param {(string|number)} [zone=system] - 'system' (for browser-default time zone),
* 'utc' (for UTC), or specify a time zone as number of minutes past UTC.
* @returnsreturn {string}
*/
calendar: function(zone) {
// 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 1,998 ⟶ 2,115:
* as `==December 2019==` or `=== Jan 2018 ===`.
*
* @returnsreturn {RegExp}
*/
monthHeaderRegex: function() {
Line 2,010 ⟶ 2,127:
* @param {number} [level=2] - Header level. Pass 0 for just the text
* with no wikitext markers (==).
* @returnsreturn {string}
*/
monthHeader: function(level) {
Line 2,017 ⟶ 2,134:
level = isNaN(level) ? 2 : level;
 
const header = '='.repeat(level);
var header = Array(level + 1).join('='); // String.prototype.repeat not supported in IE 11
varconst text = this.getUTCMonthName() + ' ' + this.getUTCFullYear();
 
if (header.length) { // wikitext-formatted header
Line 2,030 ⟶ 2,147:
 
// Allow native Date.prototype methods to be used on Morebits.date objects
Object.getOwnPropertyNames(Date.prototype).forEach(function(func) => {
Morebits.date.prototype[func] = function() {
// Exclude methods that collide with PageTriage's Date.js external, which clobbers native Date: [[phab:T268513]]
return this.privateDate[func].apply(this.privateDate, Array.prototype.slice.call(arguments));
if (['add', 'getDayName', 'getMonthName'].indexOf(func) === -1) {
};
Morebits.date.prototype[func] = function() {
return this._d[func].apply(this._d, Array.prototype.slice.call(arguments));
};
}
});
 
 
/* **************** Morebits.wiki **************** */
Line 2,053 ⟶ 2,166:
* @deprecated in favor of Morebits.isPageRedirect as of November 2020
* @memberof Morebits.wiki
* @returnsreturn {boolean}
*/
Morebits.wiki.isPageRedirect = function wikipediaIsPageRedirect() {
Line 2,059 ⟶ 2,172:
return Morebits.isPageRedirect();
};
 
 
/* **************** Morebits.wiki.actionCompleted **************** */
Line 2,121 ⟶ 2,233:
}
}
window.setTimeout(function() => {
window.___location = Morebits.wiki.actionCompleted.redirect;
}, Morebits.wiki.actionCompleted.timeOut);
Line 2,145 ⟶ 2,257:
}
};
 
 
/* **************** Morebits.wiki.api **************** */
Line 2,164 ⟶ 2,275:
* @class
* @param {string} currentAction - The current action (required).
* @param {objectObject} query - The query (required).
* @param {Function} [onSuccess] - The function to call when request is successful.
* @param {Morebits.status} [statusElement] - A Morebits.status object to use for status messages.
Line 2,174 ⟶ 2,285:
this.query.assert = 'user';
// Enforce newer error formats, preferring html
if (!query.errorformat || !['wikitext', 'plaintext'].indexOfincludes(query.errorformat) === -1) {
this.query.errorformat = 'html';
}
Line 2,195 ⟶ 2,306:
} else if (query.format === 'json' && !query.formatversion) {
this.query.formatversion = '2';
} else if (!['xml', 'json'].indexOfincludes(query.format) === -1) {
this.statelem.error('Invalid API format: only xml and json are supported.');
}
 
// Ignore tags for queries and most common unsupported actions, produces warnings
if (query.action && ['query', 'review', 'stabilize', 'pagetriageaction', 'watch'].indexOfincludes(query.action) !== -1) {
delete query.tags;
} else if (!query.tags && morebitsWikiChangeTag) {
Line 2,211 ⟶ 2,322:
onSuccess: null,
onError: null,
parent: window, // use global context if there is no parent object
query: null,
response: null,
responseXML: null, // use `response` instead; retained for backwards compatibility
statelem: null, // this non-standard name kept for backwards compatibility
statusText: null, // result received from the API, normally "success" or "error"
errorCode: null, // short text error code, if any, as documented in the MediaWiki API
Line 2,239 ⟶ 2,350:
* Carry out the request.
*
* @param {objectObject} callerAjaxParameters - Do not specify a parameter unless you really
* really want to give jQuery some extra parameters.
* @returnsreturn {promisejQuery.Promise} - A jQuery promise object that is resolved or rejected with the api object.
*/
post: function(callerAjaxParameters) {
Line 2,247 ⟶ 2,358:
++Morebits.wiki.numberOfActionsLeft;
 
varconst queryString = $.map(this.query, function(val, i) => {
if (Array.isArray(val)) {
return encodeURIComponent(i) + '=' + val.map(encodeURIComponent).join('|');
Line 2,256 ⟶ 2,367:
// 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,297 ⟶ 2,408:
this.onSuccess.call(this.parent, this);
} else {
this.statelem.info(msg('done', 'done'));
}
 
Line 2,309 ⟶ 2,420:
this.statusText = statusText;
this.errorThrown = errorThrown; // frequently undefined
this.errorText = msg('api-error', statusText, jqXHR.statusText, statusText + ' "' + jqXHR.statusText + '" occurred while contacting the API.');
return this.returnError();
}
Line 2,318 ⟶ 2,429:
returnError: function(callerAjaxParameters) {
if (this.errorCode === 'badtoken' && !this.badtokenRetry) {
this.statelem.warn(msg('invalid-token-retrying', 'Invalid token. Getting a new token and retrying...'));
this.badtokenRetry = true;
// 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,362 ⟶ 2,473:
}
 
};
 
/** Retrieves wikitext from a page. Caching enabled, duration 1 day. */
Morebits.wiki.getCachedJson = function(title) {
const query = {
action: 'query',
prop: 'revisions',
titles: title,
rvslots: '*',
rvprop: 'content',
format: 'json',
smaxage: '86400', // cache for 1 day
maxage: '86400' // cache for 1 day
};
return new Morebits.wiki.api('', query).post().then((apiobj) => {
apiobj.getStatusElement().unlink();
const response = apiobj.getResponse();
const wikitext = response.query.pages[0].revisions[0].slots.main.content;
return JSON.parse(wikitext);
});
};
 
Line 2,381 ⟶ 2,512:
morebitsWikiApiUserAgent = (ua ? ua + ' ' : '') + 'morebits.js ([[w:WT:TW]])';
};
 
 
 
/**
Line 2,393 ⟶ 2,522:
*/
var morebitsWikiChangeTag = '';
 
 
/**
Line 2,399 ⟶ 2,527:
*
* @memberof Morebits.wiki.api
* @returnsreturn {string} MediaWiki CSRF token.
*/
Morebits.wiki.api.getToken = function() {
varconst tokenApi = new Morebits.wiki.api(msg('getting-token', 'Getting token'), {
action: 'query',
meta: 'tokens',
Line 2,408 ⟶ 2,536:
format: 'json'
});
return tokenApi.post().then(function(apiobj) {=> apiobj.response.query.tokens.csrftoken);
return apiobj.response.query.tokens.csrftoken;
});
};
 
 
/* **************** Morebits.wiki.page **************** */
Line 2,453 ⟶ 2,578:
* 2. The sequence for append/prepend/newSection could be slightly shortened,
* but it would require significant duplication of code for little benefit.
*
*
* @memberof Morebits.wiki
Line 2,465 ⟶ 2,589:
 
if (!status) {
status = msg('opening-page', pageName, 'Opening page "' + pageName + '"');
}
 
Line 2,476 ⟶ 2,600:
* @private
*/
varconst ctx = {
// backing fields for public properties
pageName: pageName,
Line 2,482 ⟶ 2,606:
editSummary: null,
changeTags: null,
testActions: null, // array if any valid actions
callbackParameters: null,
statusElement: status instanceof Morebits.status ? status : new Morebits.status(status),
Line 2,488 ⟶ 2,612:
// - edit
pageText: null,
editMode: 'all', // save() replaces entire contents of the page by default
appendText: null, // can't reuse pageText for this because pageText is needed to follow a redirect
prependText: null, // can't reuse pageText for this because pageText is needed to follow a redirect
newSectionText: null,
newSectionTitle: null,
Line 2,520 ⟶ 2,644:
protectCreate: null,
protectCascade: null,
 
// - delete
deleteTalkPage: false,
 
// - undelete
undeleteTalkPage: false,
 
// - creation lookup
Line 2,582 ⟶ 2,712:
};
 
varconst emptyFunction = function() { };
 
/**
Line 2,615 ⟶ 2,745:
 
if (ctx.editMode === 'all') {
ctx.loadQuery.rvprop = 'content|timestamp'; // get the page content at the same time, if needed
} else if (ctx.editMode === 'revert') {
ctx.loadQuery.rvprop = 'timestamp';
Line 2,623 ⟶ 2,753:
 
if (ctx.followRedirect) {
ctx.loadQuery.redirects = ''; // follow all redirects
}
if (typeof ctx.pageSection === 'number') {
Line 2,632 ⟶ 2,762:
}
 
ctx.loadApi = new Morebits.wiki.api(msg('retrieving-page', 'Retrieving page...'), ctx.loadQuery, fnLoadSuccess, ctx.statusElement, ctx.onLoadFailure);
ctx.loadApi.setParent(this);
ctx.loadApi.post();
Line 2,655 ⟶ 2,785:
 
// are we getting our editing token from mw.user.tokens?
varconst canUseMwUserToken = fnCanUseMwUserToken('edit');
 
if (!ctx.pageLoaded && !canUseMwUserToken) {
Line 2,677 ⟶ 2,807:
// shouldn't happen if canUseMwUserToken === true
if (ctx.fullyProtected && !ctx.suppressProtectWarning &&
!confirm(
!confirm('You are about to make an edit to the fully protected page "' + ctx.pageName +
( ctx.fullyProtected === 'infinity' ? '" (protected indefinitely)' : '" (protection expiring ' + new Morebits.date(ctx.fullyProtected).calendar('utc') + ' (UTC))') +
msg('protected-indef-edit-warning', ctx.pageName,
'. \n\nClick OK to proceed with the edit, or Cancel to skip this edit.')) {
'You are about to make an edit to the fully protected page "' + ctx.pageName + '" (protected indefinitely). \n\nClick OK to proceed with the edit, or Cancel to skip this edit.'
ctx.statusElement.error('Edit to fully protected page was aborted.');
) :
msg('protected-edit-warning', ctx.pageName, ctx.fullyProtected,
'You are about to make an edit to the fully protected page "' + ctx.pageName +
'" (protection expiring ' + new Morebits.date(ctx.fullyProtected).calendar('utc') + ' (UTC)). \n\nClick OK to proceed with the edit, or Cancel to skip this edit.'
)
)
) {
ctx.statusElement.error(msg('protected-aborted', 'Edit to fully protected page was aborted.'));
ctx.onSaveFailure(this);
return;
Line 2,687 ⟶ 2,825:
ctx.retries = 0;
 
varconst query = {
action: 'edit',
title: ctx.pageName,
Line 2,711 ⟶ 2,849:
query.minor = true;
} else {
query.notminor = true; // force Twinkle config to override user preference setting for "all edits are minor"
}
 
Line 2,726 ⟶ 2,864:
return;
}
query.appendtext = ctx.appendText; // use mode to append to current page contents
break;
case 'prepend':
Line 2,734 ⟶ 2,872:
return;
}
query.prependtext = ctx.prependText; // use mode to prepend to current page contents
break;
case 'new':
Line 2,743 ⟶ 2,881:
}
query.section = 'new';
query.text = ctx.newSectionText; // add a new section to current page
query.sectiontitle = ctx.newSectionTitle || ctx.editSummary; // done by the API, but non-'' values would get treated as text
break;
Line 2,763 ⟶ 2,901:
}
 
if (['recreate', 'createonly', 'nocreate'].indexOfincludes(ctx.createOption) !== -1) {
query[ctx.createOption] = '';
}
Line 2,771 ⟶ 2,909:
}
 
ctx.saveApi = new Morebits.wiki.api(msg('saving-page', 'Saving page...'), query, fnSaveSuccess, ctx.statusElement, fnSaveError);
ctx.saveApi.setParent(this);
ctx.saveApi.post();
Line 2,839 ⟶ 2,977:
};
 
/** @returnsreturn {string} The name of the loaded page, including the namespace */
this.getPageName = function() {
return ctx.pageName;
};
 
/** @returnsreturn {string} The text of the page after a successful load() */
this.getPageText = function() {
return ctx.pageText;
Line 2,881 ⟶ 3,019:
ctx.newSectionTitle = newSectionTitle;
};
 
 
 
// Edit-related setter methods:
Line 2,906 ⟶ 3,042:
ctx.changeTags = tags;
};
 
 
/**
Line 2,916 ⟶ 3,051:
* - `null`: create the page if it does not exist, unless it was deleted
* in the moment between loading the page and saving the edit (default).
*
*/
this.setCreateOption = function(createOption) {
Line 3,160 ⟶ 3,294:
this.suppressProtectWarning = function() {
ctx.suppressProtectWarning = true;
};
 
// Delete-related setter
/** @param {boolean} flag */
this.setDeleteTalkPage = function (flag) {
ctx.deleteTalkPage = !!flag;
};
 
// Undelete-related setter
/** @param {boolean} flag */
this.setUndeleteTalkPage = function (flag) {
ctx.undeleteTalkPage = !!flag;
};
 
Line 3,167 ⟶ 3,313:
};
 
/** @returnsreturn {string} The current revision ID of the page */
this.getCurrentID = function() {
return ctx.revertCurID;
};
 
/** @returnsreturn {string} Last editor of the page */
this.getRevisionUser = function() {
return ctx.revertUser;
};
 
/** @returnsreturn {string} ISO 8601 timestamp at which the page was last edited. */
this.getLastEditTime = function() {
return ctx.lastEditTime;
Line 3,194 ⟶ 3,340:
* detected upon calling `save()`.
*
* @param {objectObject} callbackParameters
*/
this.setCallbackParameters = function(callbackParameters) {
Line 3,201 ⟶ 3,347:
 
/**
* @returnsreturn {objectObject} - The object previously set by `setCallbackParameters()`.
*/
this.getCallbackParameters = function() {
Line 3,215 ⟶ 3,361:
 
/**
* @returnsreturn {Morebits.status} Status element created by the constructor.
*/
this.getStatusElement = function() {
Line 3,231 ⟶ 3,377:
 
/**
* @returnsreturn {boolean} True if the page existed on the wiki when it was last loaded.
*/
this.exists = function() {
Line 3,238 ⟶ 3,384:
 
/**
* @returnsreturn {string} Page ID of the page loaded. 0 if the page doesn't
* exist.
*/
Line 3,246 ⟶ 3,392:
 
/**
* @returnsreturn {string} - Content model of the page. Possible values
* include (but may not be limited to): `wikitext`, `javascript`,
* `css`, `json`, `Scribunto`, `sanitized-css`, `MassMessageListContent`.
Line 3,256 ⟶ 3,402:
 
/**
* @returnsreturn {boolean|string} - Watched status of the page. Boolean
* unless it's being watched temporarily, in which case returns the
* expiry string.
Line 3,265 ⟶ 3,411:
 
/**
* @returnsreturn {string} ISO 8601 timestamp at which the page was last loaded.
*/
this.getLoadTime = function() {
Line 3,272 ⟶ 3,418:
 
/**
* @returnsreturn {string} The user who created the page following `lookupCreation()`.
*/
this.getCreator = function() {
Line 3,279 ⟶ 3,425:
 
/**
* @returnsreturn {string} The ISOString timestamp of page creation following `lookupCreation()`.
*/
this.getCreationTimestamp = function() {
Line 3,285 ⟶ 3,431:
};
 
/** @returnsreturn {boolean} whether or not you can edit the page */
this.canEdit = function() {
return !!ctx.testActions && ctx.testActions.indexOfincludes('edit') !== -1;
};
 
Line 3,311 ⟶ 3,457:
}
 
varconst query = {
action: 'query',
prop: 'revisions',
Line 3,332 ⟶ 3,478:
 
if (ctx.followRedirect) {
query.redirects = ''; // follow all redirects
}
 
ctx.lookupCreationApi = new Morebits.wiki.api(msg('getting-creator', 'Retrieving page creation information'), query, fnLookupCreationSuccess, ctx.statusElement, ctx.onLookupCreationFailure);
ctx.lookupCreationApi.setParent(this);
ctx.lookupCreationApi.post();
Line 3,383 ⟶ 3,529:
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);
ctx.moveApi.setParent(this);
ctx.moveApi.post();
Line 3,407 ⟶ 3,553:
// 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,424 ⟶ 3,570:
};
 
ctx.patrolApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), patrolQuery, fnProcessPatrol);
ctx.patrolApi.setParent(this);
ctx.patrolApi.post();
Line 3,449 ⟶ 3,595:
this.triage = function() {
// Fall back to patrol if not a valid triage namespace
if (!mw.config.get('pageTriageNamespaces').indexOfincludes(new mw.Title(ctx.pageName).getNamespaceId()) === -1) {
this.patrol();
} else {
Line 3,461 ⟶ 3,607:
fnProcessTriageList(this, this);
} else {
varconst query = fnNeedTokenInfoQuery('triage');
 
ctx.triageApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessTriageList);
ctx.triageApi.setParent(this);
ctx.triageApi.post();
Line 3,488 ⟶ 3,634:
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);
ctx.deleteApi.setParent(this);
ctx.deleteApi.post();
Line 3,513 ⟶ 3,659:
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);
ctx.undeleteApi.setParent(this);
ctx.undeleteApi.post();
Line 3,544 ⟶ 3,690:
// (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);
ctx.protectApi.setParent(this);
ctx.protectApi.post();
Line 3,579 ⟶ 3,725:
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);
ctx.stabilizeApi.setParent(this);
ctx.stabilizeApi.post();
Line 3,603 ⟶ 3,749:
* @param {string} [action=edit] - The action being undertaken, e.g.
* "edit" or "delete". In practice, only "edit" or "notedit" matters.
* @returnsreturn {boolean}
*/
var fnCanUseMwUserToken = function(action = 'edit') {
action = typeof action !== 'undefined' ? action : 'edit'; // IE doesn't support default parameters
 
// If a watchlist expiry is set, we must always load the page
// to avoid overwriting indefinite protection. Of course, not
Line 3,634 ⟶ 3,778:
// wgRestrictionEdit is null on non-existent pages,
// so this neatly handles nonexistent pages
varconst editRestriction = mw.config.get('wgRestrictionEdit');
if (!editRestriction || editRestriction.indexOfincludes('sysop') !== -1) {
return false;
}
Line 3,656 ⟶ 3,800:
* @param {string} action - The action being undertaken, e.g. "edit" or
* "delete".
* @returnsreturn {objectObject} Appropriate query.
*/
var fnNeedTokenInfoQuery = function(action) {
varconst query = {
action: 'query',
meta: 'tokens',
Line 3,685 ⟶ 3,829:
// callback from loadApi.post()
var fnLoadSuccess = function() {
varconst response = ctx.loadApi.getResponse().query;
 
if (!fnCheckPageName(response, ctx.onLoadFailure)) {
Line 3,691 ⟶ 3,835:
}
 
varconst page = response.pages[0], rev;
let rev;
ctx.pageExists = !page.missing;
if (ctx.pageExists) {
Line 3,699 ⟶ 3,844:
ctx.pageID = page.pageid;
} else {
ctx.pageText = ''; // allow for concatenation, etc.
ctx.pageID = 0; // nonexistent in response, matches wgArticleId
}
ctx.csrfToken = response.tokens.csrftoken;
if (!ctx.csrfToken) {
ctx.statusElement.error(msg('token-fetch-fail', 'Failed to retrieve edit token.'));
ctx.onLoadFailure(this);
return;
Line 3,721 ⟶ 3,866:
// 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,733 ⟶ 3,876:
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,750 ⟶ 3,893:
ctx.revertUser = rev && rev.user;
if (!ctx.revertUser) {
if (rev && rev.userhidden) { // username was RevDel'd or oversighted
ctx.revertUser = '<username hidden>';
} else {
Line 3,765 ⟶ 3,908:
 
// alert("Generate edit conflict now"); // for testing edit conflict recovery logic
ctx.onLoadSuccess(this); // invoke callback
};
 
Line 3,774 ⟶ 3,917:
}
 
varconst page = response.pages && response.pages[0];
if (page) {
// check for invalid titles
if (page.invalid) {
ctx.statusElement.error(msg('invalid-title', ctx.pageName, 'The page title is invalid: ' + ctx.pageName));
onFailure(this);
return false; // abort
Line 3,784 ⟶ 3,927:
 
// 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'));
onFailure(this);
return false;
Line 3,797 ⟶ 3,940:
 
// only notify user for redirects, not normalization
new Morebits.status('Note', msg('redirected', ctx.pageName, resolvedName, 'Redirected from ' + ctx.pageName + ' to ' + resolvedName));
}
 
Line 3,804 ⟶ 3,947:
} else {
// could be a circular redirect or other problem
ctx.statusElement.error(msg('redirect-resolution-fail', ctx.pageName, 'Could not resolve redirects for: ' + ctx.pageName));
onFailure(this);
 
Line 3,823 ⟶ 3,966:
* ensured of knowing the watch status by the use of this.
*
* @returnsreturn {boolean}
*/
var fnApplyWatchlistExpiry = function() {
Line 3,830 ⟶ 3,973:
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 3,858 ⟶ 4,001:
// callback from saveApi.post()
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 3,866 ⟶ 4,009:
// 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));
ctx.statusElement.info(['completed (', link, ')']);
if (ctx.onSaveSuccess) {
ctx.onSaveSuccess(this); // invoke callback
}
return;
Line 3,881 ⟶ 4,024:
ctx.statusElement.error('Could not save the page because the wiki server wanted you to fill out a CAPTCHA.');
} else {
ctx.statusElement.error(msg('api-error-unknown', 'Unknown error received from API while saving page'));
}
 
Line 3,892 ⟶ 4,035:
// callback from saveApi.post()
var fnSaveError = function() {
varconst errorCode = ctx.saveApi.getErrorCode();
 
// check for edit conflict
Line 3,898 ⟶ 4,041:
 
// 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
 
ctx.statusElement.info(msg('editconflict-retrying', 'Edit conflict detected, reapplying edit'));
if (fnCanUseMwUserToken('edit')) {
ctx.saveApi.post(); // necessarily append, prepend, or newSection, so this should work as desired
Line 3,912 ⟶ 4,055:
ctx.loadApi.post(); // reload the page and reapply the edit
}
}), ctx.statusElement);
purgeApi.post();
 
Line 3,919 ⟶ 4,062:
 
// the error might be transient, so try again
ctx.statusElement.info(msg('save-failed-retrying', 2, 'Save failed, retrying in 2 seconds ...'));
--Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds
 
// wait for sometime for client to regain connectivity
sleep(2000).then(function() => {
ctx.saveApi.post(); // give it another go!
});
Line 3,929 ⟶ 4,072:
// hard error, give up
} else {
const response = ctx.saveApi.getResponse();
const errorData = response.error || // bc error format
response.errors[0].data; // html/wikitext/plaintext error format
 
switch (errorCode) {
Line 3,938 ⟶ 4,084:
 
case 'abusefilter-disallowed':
ctx.statusElement.error('The edit was disallowed by the edit filter: "' + ctx.saveApi.getResponse().errorerrorData.abusefilter.description + '".');
break;
 
case 'abusefilter-warning':
ctx.statusElement.error([ 'A warning was returned by the edit filter: "', ctx.saveApi.getResponse().errorerrorData.abusefilter.description, '". If you wish to proceed with the edit, please carry it out again. This warning will not appear a second time.' ]);
// We should provide the user with a way to automatically retry the action if they so choose -
// I can't see how to do this without creating a UI dependency on Morebits.wiki.page though -- TTO
Line 3,949 ⟶ 4,095:
case 'spamblacklist':
// If multiple items are blacklisted, we only return the first
var spam = ctx.saveApi.getResponse().errorerrorData.spamblacklist.matches[0];
ctx.statusElement.error('Could not save the page because the URL ' + spam + ' is on the spam blacklist');
break;
Line 3,957 ⟶ 4,103:
}
 
ctx.editMode = 'all'; // cancel append/prepend/newSection/revert modes
if (ctx.onSaveFailure) {
ctx.onSaveFailure(this); // invoke callback
}
}
};
 
const isTextRedirect = function(text) {
if (!text) { // no text - content empty or inaccessible (revdelled or suppressed)
return false;
}
return Morebits.l10n.redirectTagAliases.some((tag) => new RegExp('^\\s*' + tag + '\\W', 'i').test(text));
};
 
var fnLookupCreationSuccess = function() {
varconst response = ctx.lookupCreationApi.getResponse().query;
 
if (!fnCheckPageName(response, ctx.onLookupCreationFailure)) {
Line 3,971 ⟶ 4,124:
}
 
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 3,978 ⟶ 4,131:
}
 
if (!ctx.lookupNonRedirectCreator || !/^\s*#redirect/i.testisTextRedirect(rev.content)) {
 
ctx.creator = rev.user;
Line 4,008 ⟶ 4,161:
 
var fnLookupNonRedirectCreator = function() {
varconst response = ctx.lookupCreationApi.getResponse().query;
varconst revs = response.pages[0].revisions;
 
for (let i = 0; i < revs.length; i++) {
 
if (!isTextRedirect(revs[i].content)) {
for (var i = 0; i < revs.length; i++) {
if (!/^\s*#redirect/i.test(revs[i].content)) { // inaccessible revisions also check out
ctx.creator = revs[i].user;
ctx.timestamp = revs[i].timestamp;
Line 4,047 ⟶ 4,201:
* @param {string} action - The action being checked.
* @param {string} onFailure - Failure callback.
* @returnsreturn {boolean}
*/
var fnPreflightChecks = function(action, onFailure) {
Line 4,072 ⟶ 4,226:
* @param {string} onFailure - Failure callback.
* @param {string} response - The response document from the API call.
* @returnsreturn {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'].indexOfincludes(action) !== -1;
varconst protectMissing = action === 'protect' && missing && (ctx.protectEdit || ctx.protectMove);
varconst saltMissing = action === 'protect' && !missing && ctx.protectCreate;
 
if (actionMissing || protectMissing || saltMissing) {
Line 4,090 ⟶ 4,244:
// 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,118 ⟶ 4,268:
 
var fnProcessMove = function() {
varlet pageTitle, token;
 
if (fnCanUseMwUserToken('move')) {
Line 4,124 ⟶ 4,274:
pageTitle = ctx.pageName;
} else {
varconst response = ctx.moveApi.getResponse().query;
 
if (!fnProcessChecks('move', ctx.onMoveFailure, response)) {
Line 4,131 ⟶ 4,281:
 
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,162 ⟶ 4,312:
}
 
ctx.moveProcessApi = new Morebits.wiki.api(msg('moving-page', 'moving page...'), query, ctx.onMoveSuccess, ctx.statusElement, ctx.onMoveFailure);
ctx.moveProcessApi.setParent(this);
ctx.moveProcessApi.post();
Line 4,168 ⟶ 4,318:
 
var fnProcessPatrol = function() {
varconst query = {
action: 'patrol',
format: 'json'
Line 4,178 ⟶ 4,328:
query.token = mw.user.tokens.get('patrolToken');
} else {
varconst response = ctx.patrolApi.getResponse().query;
 
// Don't patrol if not unpatrolled
Line 4,185 ⟶ 4,335:
}
 
varconst lastrevid = response.pages[0].lastrevid;
if (!lastrevid) {
return;
Line 4,191 ⟶ 4,341:
query.revid = lastrevid;
 
varconst token = response.tokens.csrftoken;
if (!token) {
return;
Line 4,201 ⟶ 4,351:
}
 
varconst patrolStat = new Morebits.status('Marking page as patrolled');
 
ctx.patrolProcessApi = new Morebits.wiki.api('patrolling page...', query, null, patrolStat);
Line 4,213 ⟶ 4,363:
ctx.csrfToken = mw.user.tokens.get('csrfToken');
} else {
varconst response = ctx.triageApi.getResponse().query;
 
ctx.pageID = response.pages[0].pageid;
Line 4,226 ⟶ 4,376:
}
 
varconst query = {
action: 'pagetriagelist',
page_id: ctx.pageID,
Line 4,239 ⟶ 4,389:
// 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,257 ⟶ 4,407:
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,265 ⟶ 4,415:
 
var fnProcessDelete = function() {
varlet pageTitle, token;
 
if (fnCanUseMwUserToken('delete')) {
Line 4,271 ⟶ 4,421:
pageTitle = ctx.pageName;
} else {
varconst response = ctx.deleteApi.getResponse().query;
 
if (!fnProcessChecks('delete', ctx.onDeleteFailure, response)) {
Line 4,278 ⟶ 4,428:
 
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,293 ⟶ 4,443:
if (ctx.changeTags) {
query.tags = ctx.changeTags;
}
if (ctx.deleteTalkPage) {
query.deletetalk = 'true';
}
 
Line 4,307 ⟶ 4,460:
var fnProcessDeleteError = function() {
 
varconst errorCode = ctx.deleteProcessApi.getErrorCode();
 
// check for "Database query error"
if (errorCode === 'internal_api_error_DBQueryError' && ctx.retries++ < ctx.maxRetries) {
ctx.statusElement.info('Database query error, retrying');
--Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds
ctx.deleteProcessApi.post(); // give it another go!
 
Line 4,318 ⟶ 4,471:
ctx.statusElement.error('Cannot delete the page, because it no longer exists');
if (ctx.onDeleteFailure) {
ctx.onDeleteFailure.call(this, ctx.deleteProcessApi); // invoke callback
}
// hard error, give up
Line 4,324 ⟶ 4,477:
ctx.statusElement.error('Failed to delete the page: ' + ctx.deleteProcessApi.getErrorText());
if (ctx.onDeleteFailure) {
ctx.onDeleteFailure.call(this, ctx.deleteProcessApi); // invoke callback
}
}
Line 4,330 ⟶ 4,483:
 
var fnProcessUndelete = function() {
varlet pageTitle, token;
 
if (fnCanUseMwUserToken('undelete')) {
Line 4,336 ⟶ 4,489:
pageTitle = ctx.pageName;
} else {
varconst response = ctx.undeleteApi.getResponse().query;
 
if (!fnProcessChecks('undelete', ctx.onUndeleteFailure, response)) {
Line 4,343 ⟶ 4,496:
 
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,358 ⟶ 4,511:
if (ctx.changeTags) {
query.tags = ctx.changeTags;
}
if (ctx.undeleteTalkPage) {
query.undeletetalk = 'true';
}
 
Line 4,372 ⟶ 4,528:
var fnProcessUndeleteError = function() {
 
varconst errorCode = ctx.undeleteProcessApi.getErrorCode();
 
// check for "Database query error"
Line 4,378 ⟶ 4,534:
if (ctx.retries++ < ctx.maxRetries) {
ctx.statusElement.info('Database query error, retrying');
--Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds
ctx.undeleteProcessApi.post(); // give it another go!
} else {
ctx.statusElement.error('Repeated database query error, please try again');
if (ctx.onUndeleteFailure) {
ctx.onUndeleteFailure.call(this, ctx.undeleteProcessApi); // invoke callback
}
}
Line 4,389 ⟶ 4,545:
ctx.statusElement.error('Cannot undelete the page, either because there are no revisions to undelete or because it has already been undeleted');
if (ctx.onUndeleteFailure) {
ctx.onUndeleteFailure.call(this, ctx.undeleteProcessApi); // invoke callback
}
// hard error, give up
Line 4,395 ⟶ 4,551:
ctx.statusElement.error('Failed to undelete the page: ' + ctx.undeleteProcessApi.getErrorText());
if (ctx.onUndeleteFailure) {
ctx.onUndeleteFailure.call(this, ctx.undeleteProcessApi); // invoke callback
}
}
Line 4,401 ⟶ 4,557:
 
var fnProcessProtect = function() {
varconst response = ctx.protectApi.getResponse().query;
 
if (!fnProcessChecks('protect', ctx.onProtectFailure, response)) {
Line 4,407 ⟶ 4,563:
}
 
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,425 ⟶ 4,581:
}
});
 
 
// Fall back to current levels if not explicitly set
Line 4,440 ⟶ 4,595:
// 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,464 ⟶ 4,617:
 
// Build protection levels and expirys (expiries?) for query
varconst protections = [], expirys = [];
if (ctx.protectEdit) {
protections.push('edit=' + ctx.protectEdit.level);
Line 4,480 ⟶ 4,633:
}
 
varconst query = {
action: 'protect',
title: pageTitle,
Line 4,508 ⟶ 4,661:
 
var fnProcessStabilize = function() {
varlet pageTitle, token;
 
if (fnCanUseMwUserToken('stabilize')) {
Line 4,514 ⟶ 4,667:
pageTitle = ctx.pageName;
} else {
varconst response = ctx.stabilizeApi.getResponse().query;
 
// 'stabilize' as a verb not necessarily well understood
Line 4,522 ⟶ 4,675:
 
token = response.tokens.csrftoken;
varconst page = response.pages[0];
pageTitle = page.title;
// Doesn't support watchlist expiry [[phab:T263336]]
Line 4,528 ⟶ 4,681:
}
 
varconst query = {
action: 'stabilize',
title: pageTitle,
Line 4,552 ⟶ 4,705:
 
var sleep = function(milliseconds) {
varconst deferred = $.Deferred();
setTimeout(deferred.resolve, milliseconds);
return deferred;
Line 4,565 ⟶ 4,718:
* - Need to reset all parameters once done (e.g. edit summary, move destination, etc.)
*/
 
 
/* **************** Morebits.wiki.preview **************** */
Line 4,593 ⟶ 4,745:
* @param {string} [pageTitle] - Optional parameter for the page this should be rendered as being on, if omitted it is taken as the current page.
* @param {string} [sectionTitle] - If provided, render the text as a new section using this as the title.
* @returnsreturn {jQuery.promise}
*/
this.beginRender = function(wikitext, pageTitle, sectionTitle) {
$(previewbox).show();
 
varconst statusspan = document.createElement('span');
previewbox.appendChild(statusspan);
Morebits.status.init(statusspan);
 
varconst query = {
action: 'parse',
prop: ['text', 'modules'],
pst: 'true', // PST = pre-save transform; this makes substitution work properly
preview: true,
text: wikitext,
title: pageTitle || mw.config.get('wgPageName'),
disablelimitreport: true,
disableeditsection: true,
format: 'json'
};
Line 4,615 ⟶ 4,769:
query.sectiontitle = sectionTitle;
}
varconst renderApi = new Morebits.wiki.api('loading...', query, fnRenderSuccess, new Morebits.status('Preview'));
return renderApi.post();
};
 
var fnRenderSuccess = function(apiobj) {
varconst htmlresponse = apiobj.getResponse().parse.text;
const html = response.parse.text;
if (!html) {
apiobj.statelem.error('failed to retrieve preview, or template was blanked');
Line 4,626 ⟶ 4,781:
}
previewbox.innerHTML = html;
mw.loader.load(response.parse.modulestyles);
$(previewbox).find('a').attr('target', '_blank'); // this makes links open in new tab
mw.loader.load(response.parse.modules);
 
// this makes links open in new tab
$(previewbox).find('a').attr('target', '_blank');
};
 
Line 4,634 ⟶ 4,793:
};
};
 
 
/* **************** Morebits.wikitext **************** */
Line 4,652 ⟶ 4,810:
* @param {string} text - Wikitext containing a template.
* @param {number} [start=0] - Index noting where in the text the template begins.
* @returnsreturn {objectObject} `{name: templateName, parameters: {key: value}}`.
*/
Morebits.wikitext.parseTemplate = function(text, start) {
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,677 ⟶ 4,835:
// Nothing found yet, this must be the template name
if (count === -1) {
result.name = current.substringslice(2).trim();
++count;
} else {
Line 4,689 ⟶ 4,847:
} 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,698 ⟶ 4,856:
}
 
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,710 ⟶ 4,868:
continue;
}
varconst test2 = text.substr(i, 2);
// Entering a template (or link)
if (test2 === '{{' || test2 === '[[') {
Line 4,772 ⟶ 4,930:
*
* @param {string} link_target
* @returnsreturn {Morebits.wikitext.page}
*/
removeLink: function(link_target) {
const mwTitle = mw.Title.newFromText(link_target);
// Remove a leading colon, to be handled later
const namespaceID = mwTitle.getNamespaceId();
if (link_target.indexOf(':') === 0) {
link_targetconst title = link_targetmwTitle.slicegetMainText(1);
}
var link_re_string = '', ns = '', title = link_target;
 
var idx = link_target.indexOf(':');
if (idx > 0) {
ns = link_target.slice(0, idx);
title = link_target.slice(idx + 1);
 
let link_regex_string = '';
link_re_string = Morebits.namespaceRegex(mw.config.get('wgNamespaceIds')[ns.toLowerCase().replace(/ /g, '_')]) + ':';
if (namespaceID !== 0) {
link_regex_string = Morebits.namespaceRegex(namespaceID) + ':';
}
link_re_stringlink_regex_string += Morebits.pageNameRegex(title);
 
// AllowFor formost annamespaces, optionalunlink leadingboth colon,[[User:Test]] e.g.and [[:User:Test]]
// FilesFor files and Categoriescategories, becomeonly linksunlink with[[:Category:Test]]. aDo leadingnot colon, e.g.unlink [[:FileCategory:Test.png]]
const isFileOrCategory = [6, 14].includes(namespaceID);
var colon = new RegExp(Morebits.namespaceRegex([6, 14])).test(ns) ? ':' : ':?';
const colon = isFileOrCategory ? ':' : ':?';
 
varconst link_simple_resimple_link_regex = new RegExp('\\[\\[' + colon + '(' + link_re_stringlink_regex_string + ')\\]\\]', 'g');
varconst link_named_repiped_link_regex = new RegExp('\\[\\[' + colon + link_re_stringlink_regex_string + '\\|(.+?)\\]\\]', 'g');
this.text = this.text.replace(link_simple_resimple_link_regex, '$1').replace(link_named_repiped_link_regex, '$1');
return this;
},
Line 4,806 ⟶ 4,960:
* @param {string} image - Image name without `File:` prefix.
* @param {string} [reason] - Reason to be included in comment, alongside the commented-out image.
* @returnsreturn {Morebits.wikitext.page}
*/
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
unbinder.unbind('<!--', '-->');
}
}
// unbind the newly created comments
unbinder.unbind('<!--', '-->');
 
// Check for gallery images, i.e. instances that must start on a new line,
// 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 4,839 ⟶ 4,993:
// 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 4,851 ⟶ 5,005:
* @param {string} image - Image name without File: prefix.
* @param {string} data - The display options.
* @returnsreturn {Morebits.wikitext.page}
*/
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 4,865 ⟶ 5,019:
}
}
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 4,876 ⟶ 5,030:
* @param {string} template - Page name whose transclusions are to be removed,
* include namespace prefix only if not in template namespace.
* @returnsreturn {Morebits.wikitext.page}
*/
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 4,902 ⟶ 5,056:
* @param {string|string[]} [preRegex] - Optional regex string or array to match
* before any template matches (i.e. before `{{`), such as html comments.
* @returnsreturn {Morebits.wikitext.page}
*/
insertAfterTemplates: function(tag, regex, flags, preRegex) {
Line 4,926 ⟶ 5,080:
preRegex = preRegex.join('|');
}
 
 
// Regex is extra complicated to allow for templates with
Line 4,961 ⟶ 5,114:
* Get the manipulated wikitext.
*
* @returnsreturn {string}
*/
getText: function() {
Line 4,967 ⟶ 5,120:
}
};
 
 
/* *********** Morebits.userspaceLogger ************ */
Line 5,001 ⟶ 5,153:
* @param {string} logText - Doesn't include leading `#` or `*`.
* @param {string} summaryText - Edit summary.
* @returnsreturn {JQueryjQuery.Promise}
*/
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,025 ⟶ 5,177:
pageobj.setCreateOption('recreate');
pageobj.save(def.resolve, def.reject);
}.bind(this));
return def;
};
};
 
 
/* **************** Morebits.status **************** */
Line 5,048 ⟶ 5,199:
Morebits.status = function Status(text, stat, type) {
this.textRaw = text;
this.text = thisMorebits.codifycreateHtml(text);
this.type = type || 'status';
this.generate();
Line 5,085 ⟶ 5,236:
Morebits.status.errorEvent = handler;
} else {
throw new Error('Morebits.status.onError: handler is not a function');
}
};
Line 5,113 ⟶ 5,264:
this.linked = false;
}
},
 
/**
* Create a document fragment with the status text, parsing as HTML.
* Runs upon construction for text (part before colon) and upon
* render/update for status (part after colon).
*
* @param {(string|Element|Array)} obj
* @returns {DocumentFragment}
*/
codify: function(obj) {
if (!Array.isArray(obj)) {
obj = [ obj ];
}
var result;
result = document.createDocumentFragment();
for (var i = 0; i < obj.length; ++i) {
if (obj[i] instanceof Element) {
result.appendChild(obj[i]);
} else {
$.parseHTML(obj[i]).forEach(function(elem) {
result.appendChild(elem);
});
}
}
return result;
 
},
 
Line 5,151 ⟶ 5,275:
update: function(status, type) {
this.statRaw = status;
this.stat = thisMorebits.codifycreateHtml(status);
if (type) {
this.type = type;
Line 5,205 ⟶ 5,329:
* @param {string} text - Before colon
* @param {string} status - After colon
* @returnsreturn {Morebits.status} - `status`-type (blue)
*/
Morebits.status.status = function(text, status) {
Line 5,214 ⟶ 5,338:
* @param {string} text - Before colon
* @param {string} status - After colon
* @returnsreturn {Morebits.status} - `info`-type (green)
*/
Morebits.status.info = function(text, status) {
Line 5,223 ⟶ 5,347:
* @param {string} text - Before colon
* @param {string} status - After colon
* @returnsreturn {Morebits.status} - `warn`-type (red)
*/
Morebits.status.warn = function(text, status) {
Line 5,232 ⟶ 5,356:
* @param {string} text - Before colon
* @param {string} status - After colon
* @returnsreturn {Morebits.status} - `error`-type (bold red)
*/
Morebits.status.error = function(text, status) {
Line 5,246 ⟶ 5,370:
*/
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,263 ⟶ 5,387:
*/
Morebits.status.printUserText = function(comments, message) {
varconst p = document.createElement('p');
p.innerHTML = message;
varconst div = document.createElement('div');
div.className = 'toccoloursmorebits-usertext';
div.style.marginTop = '0';
div.style.whiteSpace = 'pre-wrap';
Line 5,273 ⟶ 5,397:
Morebits.status.root.appendChild(p);
};
 
 
 
/**
Line 5,282 ⟶ 5,404:
* @param {string} content - Text content.
* @param {string} [color] - Font color.
* @returnsreturn {HTMLElement}
*/
Morebits.htmlNode = function (type, content, color) {
varconst node = document.createElement(type);
if (color) {
node.style.color = color;
Line 5,292 ⟶ 5,414:
return node;
};
 
 
 
/**
Line 5,304 ⟶ 5,424:
*/
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 resortingre-sorting
varlet index = -1, lastIndex = -1, i;
for (i = 0; i < $cbs.length; i++) {
if ($cbs[i] === thisCb) {
index = i;
if (lastIndex > -1) {
Line 5,318 ⟶ 5,438:
}
}
if ($cbs[i] === lastCheckbox) {
lastIndex = i;
if (index > -1) {
Line 5,328 ⟶ 5,448:
if (index > -1 && lastIndex > -1) {
// inspired by wikibits
varconst endState = thisCb.checked;
varlet start, finish;
if (index < lastIndex) {
start = index + 1;
Line 5,339 ⟶ 5,459:
 
for (i = start; i <= finish; i++) {
if ($cbs[i].checked !== endState) {
$cbs[i].click();
}
}
Line 5,349 ⟶ 5,469:
}
 
$(jQuerySelector, jQueryContext).clickon('click', clickHandler);
};
 
 
 
/* **************** Morebits.batchOperation **************** */
Line 5,393 ⟶ 5,511:
*/
Morebits.batchOperation = function(currentAction) {
varconst ctx = {
// backing fields for public properties
pageList: null,
Line 5,402 ⟶ 5,520:
 
// internal counters, etc.
statusElement: new Morebits.status(currentAction || msg('batch-starting', 'Performing batch operation')),
worker: null, // function that executes for each item in pageList
postFinish: null, // function that executes when the whole batch has been processed
Line 5,467 ⟶ 5,585:
ctx.pageChunks = [];
 
varconst total = ctx.pageList.length;
if (!total) {
ctx.statusElement.info(msg('batch-no-pages', 'no pages specified'));
ctx.running = false;
if (ctx.postFinish) {
Line 5,496 ⟶ 5,614:
*/
this.workerSuccess = function(arg) {
 
var createPageLink = function(pageName) {
var link = document.createElement('a');
link.setAttribute('href', mw.util.getUrl(pageName));
link.appendChild(document.createTextNode(pageName));
return link;
};
 
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 ([[', createPageLink(+ pageName), + ']])']));
} else {
// we don't know the page title - just display a generic message
statelem.info(msg('done', 'done'));
}
} else {
Line 5,522 ⟶ 5,633:
 
} else if (typeof arg === 'string' && ctx.options.preserveIndividualStatusLines) {
new Morebits.status(arg, [msg('batch-done (-page', createPageLink(arg), ')completed ([[' + arg + ']])'));
}
 
Line 5,535 ⟶ 5,646:
// private functions
 
varconst thisProxy = this;
 
var fnStartNewChunk = function() {
varconst chunk = ctx.pageChunks[++ctx.currentChunkIndex];
if (!chunk) {
return; // done! yay
}
 
// start workers for the current chunk
ctx.countStarted += chunk.length;
chunk.forEach(function(page) => {
ctx.worker(page, thisProxy);
});
Line 5,554 ⟶ 5,665:
 
// update overall status line
varconst total = ctx.pageList.length;
if (ctx.countFinished < total) {
ctxconst progress = Math.statusElement.status(parseIntround(100 * ctx.countFinished / total, 10) + '%');
ctx.statusElement.status(msg('percent', progress, progress + '%'));
 
// start a new chunk if we're close enough to the end of the previous chunk, and
Line 5,565 ⟶ 5,677:
}
} 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) {
ctx.statusElement.warn(statusString);
Line 5,602 ⟶ 5,714:
this.failureCallbackMap = new Map();
this.deferreds = new Map();
this.allDeferreds = []; // Hack: IE doesn't support Map.prototype.values
this.context = context || window;
 
Line 5,618 ⟶ 5,729:
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);
this.allDeferreds.push(deferred);
};
 
Line 5,627 ⟶ 5,737:
* Run all the tasks. Multiple tasks may be run at once.
*
* @returnsreturn {jQuery.Promise} - Resolved if all tasks succeed, rejected otherwise.
*/
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,652 ⟶ 5,760:
});
});
return $.when.apply(null, [...this.allDeferredsdeferreds.values()]); // resolved when everything is done!
};
 
Line 5,662 ⟶ 5,770:
* @memberof Morebits
* @class
* @requires jqueryjQuery.ui.dialog
* @param {number} width
* @param {number} height - The maximum allowable height for the content area.
*/
Morebits.simpleWindow = function SimpleWindow(width, height) {
varconst content = document.createElement('div');
this.content = content;
content.className = 'morebits-dialog-content';
Line 5,678 ⟶ 5,786:
buttons: { 'Placeholder button': function() {} },
dialogClass: 'morebits-dialog',
width: Math.min(parseInt(window.innerWidth, 10), parseInt(width ? width :|| 800, 10)),
// give jQuery the given height value (which represents the anticipated height of the dialog) here, so
// it can position the dialog appropriately
Line 5,705 ⟶ 5,813:
});
 
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,721 ⟶ 5,829:
// resize the scrollbox with the dialog, if one is present
$widget.resizable('option', 'alsoResize', '#' + this.content.id + ' .morebits-scrollbox, #' + this.content.id);
 
// add skin-invert to "close" button
$('.morebits-dialog .ui-dialog-titlebar-close').addClass('skin-invert');
};
 
Line 5,732 ⟶ 5,843:
* Focuses the dialog. This might work, or on the contrary, it might not.
*
* @returnsreturn {Morebits.simpleWindow}
*/
focus: function() {
Line 5,744 ⟶ 5,855:
*
* @param {event} [event]
* @returnsreturn {Morebits.simpleWindow}
*/
close: function(event) {
Line 5,758 ⟶ 5,869:
* might work, but it is not guaranteed.
*
* @returnsreturn {Morebits.simpleWindow}
*/
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;
$widget.find('.ui-dialog-title').prepend(scriptnamespan);
}
 
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;
window.setupTooltips(dialog.parent()[0]);
}
this.setHeight(this.height); // init height algorithm
return this;
},
Line 5,783 ⟶ 5,894:
*
* @param {string} title
* @returnsreturn {Morebits.simpleWindow}
*/
setTitle: function(title) {
Line 5,795 ⟶ 5,906:
*
* @param {string} name
* @returnsreturn {Morebits.simpleWindow}
*/
setScriptName: function(name) {
Line 5,806 ⟶ 5,917:
*
* @param {number} width
* @returnsreturn {Morebits.simpleWindow}
*/
setWidth: function(width) {
Line 5,818 ⟶ 5,929:
*
* @param {number} height
* @returnsreturn {Morebits.simpleWindow}
*/
setHeight: function(height) {
Line 5,844 ⟶ 5,955:
*
* @param {HTMLElement} content
* @returnsreturn {Morebits.simpleWindow}
*/
setContent: function(content) {
Line 5,856 ⟶ 5,967:
*
* @param {HTMLElement} content
* @returnsreturn {Morebits.simpleWindow}
*/
addContent: function(content) {
Line 5,862 ⟶ 5,973:
 
// 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');
 
button.textContent = value.hasAttribute('value') ? value.getAttribute('value') : value.textContent ? value.textContent : 'Submit Query';
if (value.hasAttribute('value')) {
button.textContent = value.getAttribute('value');
} else if (value.textContent) {
button.textContent = value.textContent;
} else {
button.textContent = msg('submit', 'Submit');
}
 
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 5,878 ⟶ 5,997:
$(this.content).dialog('widget').find('.morebits-dialog-buttons').empty().append(this.buttons)[0].removeAttribute('data-empty');
} else {
$(this.content).dialog('widget').find('.morebits-dialog-buttons')[0].setAttribute('data-empty', 'data-empty'); // used by CSS
}
return this;
Line 5,886 ⟶ 6,005:
* Removes all contents from the dialog, barring any footer links.
*
* @returnsreturn {Morebits.simpleWindow}
*/
purgeContent: function() {
Line 5,908 ⟶ 6,027:
* @param {string} wikiPage - Link target.
* @param {boolean} [prep=false] - Set true to prepend rather than append.
* @returnsreturn {Morebits.simpleWindow}
*/
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) {
$footerlinks.prepend(bullet);
Line 5,921 ⟶ 6,040:
}
}
varconst link = document.createElement('a');
link.setAttribute('href', mw.util.getUrl(wikiPage));
link.setAttribute('title', wikiPage);
Line 5,942 ⟶ 6,061:
* @param {boolean} [modal=false] - If set to true, other items on the
* page will be disabled, i.e., cannot be interacted with.
* @returnsreturn {Morebits.simpleWindow}
*/
setModality: function(modal) {
Line 5,965 ⟶ 6,084:
};
 
// Create capital letter aliases for all Morebits @classes (functions that work with the `new` keyword), to follow the coding convention that classes should start with an uppercase letter. This will let us start fixing ESLint `new-cap` errors in other files.
Morebits.BatchOperation = Morebits.batchOperation;
Morebits.Date = Morebits.date;
Morebits.QuickForm = Morebits.quickForm;
Morebits.QuickForm.Element = Morebits.quickForm.element;
Morebits.SimpleWindow = Morebits.simpleWindow;
Morebits.Status = Morebits.status;
Morebits.TaskManager = Morebits.taskManager;
Morebits.Unbinder = Morebits.unbinder;
Morebits.UserspaceLogger = Morebits.userspaceLogger;
Morebits.wiki.Api = Morebits.wiki.api;
Morebits.wiki.Page = Morebits.wiki.page;
Morebits.wiki.Preview = Morebits.wiki.preview;
Morebits.wikitext.Page = Morebits.wikitext.page;
 
}());
}(window, document, jQuery)); // End wrap with anonymous function
 
 
/**
Line 5,978 ⟶ 6,110:
*/
 
if (typeof arguments === 'undefined') { // typeof is here for a reason...
/* global Morebits */
window.SimpleWindow = Morebits.simpleWindow;