MediaWiki:Gadget-morebits.js: Difference between revisions
Content deleted Content added
Repo at 83dcdd2: Support batch requested moves (#1888) |
Repo at ac3c1e3: replace es-x/no-array-prototype-includes with unicorn/prefer-includes (#2125) |
||
(5 intermediate revisions by the same user not shown) | |||
Line 34:
*/
(function() {
/** @lends Morebits */
window.Morebits = Morebits;
/**
Line 50 ⟶ 49:
* Examples:
* Use jquery-i18n:
*
* Use banana-i18n or orange-i18n:
*
*
*▼
* @param {Object} parser
*/
Line 64:
/**
* @private
* @
*/
getMessage: function () {
// 1st arg: message name
// 2nd to (n-1)th arg: message parameters
// nth arg: legacy English fallback
if (!Morebits.i18n.parser) {
return fallback;
Line 78:
// i18n libraries are generally invoked with variable number of arguments
// as msg(msgName, ...parameters)
// if no i18n message exists, i18n libraries generally give back the message name
if (i18nMessage === msgName) {
Line 88:
// shortcut
/**
Line 106 ⟶ 105:
* in the format [year, month, date, hour, minute, second]
* which can be passed to Date.UTC()
*
* @param {string} str
* @
*/
signatureTimestampFormat: function (str) {
// HH:mm, DD Month YYYY (UTC)
if (!match) {
return null;
}
if (month === -1) {
return null;
Line 124:
}
};
/**
Line 130 ⟶ 129:
*
* @param {string} group - e.g. `sysop`, `extendedconfirmed`, etc.
* @
*/
Morebits.userIsInGroup = function (group) {
return mw.config.get('wgUserGroups').
};
/**
*
* @type {boolean}
Line 151:
*
* @param {string} address - The IPv6 address, with or without CIDR.
* @
*/
Morebits.sanitizeIPv6 = function (address) {
Line 163:
* detect Module:RfD, with the same failure points.
*
* @
*/
Morebits.isPageRedirect = function() {
Line 176:
*/
Morebits.pageNameNorm = mw.config.get('wgPageName').replace(/_/g, ' ');
/**
Line 184 ⟶ 183:
*
* @param {string} pageName - Page name without namespace.
* @
*/
Morebits.pageNameRegex = function(pageName) {
Line 190 ⟶ 189:
return '';
}
remainder = Morebits.string.escapeRegExp(pageName.slice(1));
if (mw.Title.phpCharToUpper(firstChar) !== firstChar.toLowerCase()) {
Line 202 ⟶ 201:
* Wikilink syntax (`[[...]]`) is transformed into HTML anchor.
* Used in Morebits.quickForm and Morebits.status
*▼
* @internal
* @param {string|Node|(string|Node)[]} input
* @
*/
Morebits.createHtml = function(input) {
if (!input) {
return fragment;
Line 214:
input = [ input ];
}
for (
if (input[i] instanceof Node) {
fragment.appendChild(input[i]);
} else {
$.parseHTML(Morebits.createHtml.renderWikilinks(input[i])).forEach(
fragment.appendChild(node);
});
Line 228:
/**
* Converts wikilinks to HTML anchor tags.
*
* @param text
* @
*/
Morebits.createHtml.renderWikilinks = function (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,
if (!target) {
target = text;
Line 260 ⟶ 261:
* // returns '(?:[Ff][Ii][Ll][Ee]|[Ii][Mm][Aa][Gg][Ee])'
* Morebits.namespaceRegex([6])
* @
*/
Morebits.namespaceRegex = function(namespaces) {
Line 266 ⟶ 267:
namespaces = [namespaces];
}
let regex; $.each(mw.config.get('wgNamespaceIds'),
if (namespaces.
// 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(
}
});
Line 290:
return regex;
};
/* **************** Morebits.quickForm **************** */
Line 310 ⟶ 309:
*
* @memberof Morebits.quickForm
* @
*/
Morebits.quickForm.prototype.render = function QuickFormRender() {
ret.names = {};
return ret;
Line 324 ⟶ 323:
* @param {(object|Morebits.quickForm.element)} data - A quickform element, or the object with which
* a quickform element is constructed.
* @
*/
Morebits.quickForm.prototype.append = function QuickFormAppend(data) {
Line 376 ⟶ 375:
* @memberof Morebits.quickForm
* @class
* @param {
* specify one of the available types from the index above, as well as any
* relevant and available attributes.
Line 404 ⟶ 403:
* @param {Morebits.quickForm.element} data - A quickForm element or the object required to
* create the quickForm element.
* @
*/
Morebits.quickForm.element.prototype.append = function QuickFormElementAppend(data) {
if (data instanceof Morebits.quickForm.element) {
child = data;
Line 422 ⟶ 421:
*
* @memberof Morebits.quickForm.element
* @
*/
Morebits.quickForm.element.prototype.render = function QuickFormElementRender(internal_subgroup_id) {
for (
// do not pass internal_subgroup_id to recursive calls
currentNode[1].appendChild(this.childs[i].render());
Line 433 ⟶ 432:
return currentNode[0];
};
/** @memberof Morebits.quickForm.element */
Morebits.quickForm.element.prototype.compute = function QuickFormElementCompute(data, in_id) {
if (data.adminonly && !Morebits.userIsSysop) {
// hell hack alpha
Line 446 ⟶ 444:
}
switch (data.type) {
case 'form':
Line 547 ⟶ 545:
if (data.list) {
for (i = 0; i < data.list.length; ++i) {
current = data.list[i];
var cur_div;
Line 594 ⟶ 592:
var event;
if (current.subgroup) {
if (!Array.isArray(tmpgroup)) {
Line 604 ⟶ 602:
id: id + '_' + i + '_subgroup'
});
$.each(tmpgroup,
if (!newEl.type) {
newEl.type = data.type;
Line 613 ⟶ 611:
});
subgroup.className = 'quickformSubgroup';
subnode.subgroup = subgroup;
Line 622 ⟶ 620:
e.target.parentNode.appendChild(e.target.subgroup);
if (e.target.type === 'radio') {
if (e.target.form.names[name] !== undefined) {
e.target.form.names[name].parentNode.removeChild(e.target.form.names[name].subgroup);
Line 639 ⟶ 637:
event = function(e) {
if (e.target.checked) {
if (e.target.form.names[name] !== undefined) {
e.target.form.names[name].parentNode.removeChild(e.target.form.names[name].subgroup);
Line 680 ⟶ 678:
} else {
subnode.setAttribute('type', 'number');
['min', 'max', 'step', 'list'].forEach(
if (data[att]) {
subnode.setAttribute(att, data[att]);
Line 687 ⟶ 685:
}
['value', 'size', 'placeholder', 'maxlength'].forEach(
if (data[att]) {
subnode.setAttribute(att, data[att]);
}
});
['disabled', 'required', 'readonly'].forEach(
if (data[att]) {
subnode.setAttribute(att, att);
Line 718 ⟶ 716:
disabled: min >= max,
event: function(e) {
e.target.area.appendChild(new_node.render());
Line 746 ⟶ 744:
for (i = 0; i < min; ++i) {
listNode.appendChild(elem.render());
}
Line 761 ⟶ 759:
node = document.createElement('div');
data.inputs.forEach(
node.appendChild(cell.render());
});
if (data.remove) {
type: 'button',
label: 'remove',
event: function(e) {
list.removeChild(node);
Line 781 ⟶ 779:
});
node.appendChild(remove[0]);
removeButton.inputnode = node;
removeButton.listnode = data.listnode;
Line 839 ⟶ 837:
}
if (data.label) {
result.className = 'quickformDescription';
result.appendChild(Morebits.createHtml(data.label));
Line 877 ⟶ 875:
if (data.label) {
label = node.appendChild(document.createElement('h5'));
labelElement.appendChild(Morebits.createHtml(data.label));
labelElement.setAttribute('for', data.id || id);
Line 938 ⟶ 936:
*
* @memberof Morebits.quickForm.element
* @requires
* @param {HTMLElement} node - The HTML element beside which a tooltip is to be generated.
* @param {
*/
Morebits.quickForm.element.generateTooltip = function QuickFormElementGenerateTooltip(node, data) {
tooltipButton.className = 'morebits-tooltipButton';
tooltipButton.title = data.tooltip; // Provides the content for jQuery UI
Line 953 ⟶ 951:
});
};
// Some utility methods for manipulating quickForms after their creation:
Line 964 ⟶ 961:
* @memberof Morebits.quickForm
* @param {HTMLFormElement} form
* @
*/
Morebits.quickForm.getInputData = function(form) {
for (
if (field.disabled || !field.name || !field.type ||
field.type === 'submit' || field.type === 'button') {
Line 978 ⟶ 975:
// For elements in subgroups, quickform prepends element names with
// name of the parent group followed by a period, get rid of that.
switch (field.type) {
Line 1,017 ⟶ 1,014:
return result;
};
/**
Line 1,025 ⟶ 1,021:
* @param {HTMLFormElement} form
* @param {string} fieldName - The name or id of the fields.
* @
*/
Morebits.quickForm.getElements = function QuickFormGetElements(form, fieldName) {
fieldName = $.escapeSelector(fieldName); // sanitize input
if ($elements.length > 0) {
return $elements.toArray();
Line 1,045 ⟶ 1,041:
* @param {HTMLInputElement[]} elementArray - Array of checkbox or radio elements.
* @param {string} value - Value to search for.
* @
*/
Morebits.quickForm.getCheckboxOrRadio = function QuickFormGetCheckboxOrRadio(elementArray, value) {
});▼
if (found.length > 0) {
return found[0];
Line 1,063 ⟶ 1,057:
* @memberof Morebits.quickForm
* @param {HTMLElement} element
* @
*/
Morebits.quickForm.getElementContainer = function QuickFormGetElementContainer(element) {
Line 1,082 ⟶ 1,076:
* @memberof Morebits.quickForm
* @param {(HTMLElement|Morebits.quickForm.element)} element
* @
*/
Morebits.quickForm.getElementLabelObject = function QuickFormGetElementLabelObject(element) {
Line 1,105 ⟶ 1,099:
* @memberof Morebits.quickForm
* @param {(HTMLElement|Morebits.quickForm.element)} element
* @
*/
Morebits.quickForm.getElementLabel = function QuickFormGetElementLabel(element) {
if (!labelElement) {
Line 1,122 ⟶ 1,116:
* @param {(HTMLElement|Morebits.quickForm.element)} element
* @param {string} labelText
* @
*/
Morebits.quickForm.setElementLabel = function QuickFormSetElementLabel(element, labelText) {
if (!labelElement) {
Line 1,140 ⟶ 1,134:
* @param {(HTMLElement|Morebits.quickForm.element)} element
* @param {string} temporaryLabelText
* @
*/
Morebits.quickForm.overrideElementLabel = function QuickFormOverrideElementLabel(element, temporaryLabelText) {
Line 1,154 ⟶ 1,148:
* @memberof Morebits.quickForm
* @param {(HTMLElement|Morebits.quickForm.element)} element
* @
*/
Morebits.quickForm.resetElementLabel = function QuickFormResetElementLabel(element) {
Line 1,184 ⟶ 1,178:
$(Morebits.quickForm.getElementContainer(element)).find('.morebits-tooltipButton').toggle(visibility);
};
/**
Line 1,193 ⟶ 1,185:
* Get checked items in the form.
*
* @
* @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,199 ⟶ 1,191:
* @param {string} [type] - Optionally specify either radio or checkbox (for
* the event that both checkboxes and radiobuttons have the same name).
* @
* checked property set to true.
*/
HTMLFormElement.prototype.getChecked = function(name, type) {
if (!elements) {
return [];
}
if (elements instanceof HTMLSelectElement) {
for (i = 0; i < options.length; ++i) {
if (options[i].selected) {
Line 1,247 ⟶ 1,239:
* Does the same as {@link HTMLFormElement.getChecked|getChecked}, but with unchecked elements.
*
* @
* @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,253 ⟶ 1,245:
* @param {string} [type] - Optionally specify either radio or checkbox (for
* the event that both checkboxes and radiobuttons have the same name).
* @
* checked property set to true.
*/
HTMLFormElement.prototype.getUnchecked = function(name, type) {
if (!elements) {
return [];
}
if (elements instanceof HTMLSelectElement) {
for (i = 0; i < options.length; ++i) {
if (!options[i].selected) {
Line 1,312 ⟶ 1,304:
*
* @param {string} address - The IPv6 address, with or without CIDR.
* @
*/
sanitizeIPv6: function (address) {
Line 1,325 ⟶ 1,317:
address = address.toUpperCase();
// Expand zero abbreviations
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").
// If the '::' is at the beginning...
if (abbrevPos === 0) {
repeat = '0:';
Line 1,348 ⟶ 1,340:
pad = 8; // 6+2 (due to '::')
}
pad -= address.split(':').length - 1;
for (
replacement += repeat;
}
Line 1,365 ⟶ 1,357:
*
* @param {string} ip
* @
*/
isRange: function (ip) {
Line 1,376 ⟶ 1,368:
* for IPv4 and /32 for IPv6.
*
* @
* otherwise false (ranges outside the limit, single IPs, non-IPs).
*/
validCIDR: function (ip) {
if (Morebits.ip.isRange(ip)) {
if (subnet) { // Should be redundant
if (mw.util.isIPv6Address(ip, true)) {
Line 1,401 ⟶ 1,393:
*
* @param {string} ipv6 - The IPv6 address, with or without a subnet.
* @
* otherwise the (sanitized) /64 address.
*/
Line 1,408 ⟶ 1,400:
return false;
}
if (subnetMatch && parseInt(subnetMatch[1], 10) < 64) {
return false;
}
ipv6 = Morebits.ip.sanitizeIPv6(ipv6);
// eslint-disable-next-line no-useless-concat
return ipv6.replace(ip_re, '$1' + '0:0:0:0/64');
}
};
/**
Line 1,428 ⟶ 1,420:
/**
* @param {string} str
* @
*/
toUpperCaseFirstChar: function(str) {
str = str.toString();
return str.
},
/**
* @param {string} str
* @
*/
toLowerCaseFirstChar: function(str) {
str = str.toString();
return str.
},
Line 1,452 ⟶ 1,444:
* @param {string} end
* @param {(string[]|string)} [skiplist]
* @
* @throws If the `start` and `end` strings aren't of the same length.
* @throws If `skiplist` isn't an array or string
Line 1,460 ⟶ 1,452:
throw new Error('start marker and end marker must be of the same length');
}
if (!Array.isArray(skiplist)) {
if (skiplist === undefined) {
Line 1,472 ⟶ 1,464:
}
}
for (
for (
if (str.substr(i, skiplist[j].length) === skiplist[j]) {
i += skiplist[j].length - 1;
Line 1,506 ⟶ 1,498:
* @param {string} str
* @param {boolean} [addSig]
* @
*/
formatReasonText: function(str, addSig) {
// 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) {
if (sigIndex === -1 || sigIndex !== reason.length - sig.length) {
reason += ' ' + sig;
Line 1,529 ⟶ 1,522:
*
* @param {string} str
* @
*/
formatReasonForLog: function(str) {
Line 1,549 ⟶ 1,542:
* @param {(string|RegExp)} pattern
* @param {string} replacement
* @
*/
safeReplace: function morebitsStringSafeReplace(string, pattern, replacement) {
Line 1,562 ⟶ 1,555:
*
* @param {string} expiry
* @
*/
isInfinity: function morebitsStringIsInfinity(expiry) {
return ['indefinite', 'infinity', 'infinite', 'never'].
},
Line 1,573 ⟶ 1,566:
*
* @param {string} text - String to be escaped.
* @
*/
escapeRegExp: function(text) {
Line 1,579 ⟶ 1,572:
}
};
/**
Line 1,592 ⟶ 1,584:
*
* @param {Array} arr
* @
* @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(
},
Line 1,608 ⟶ 1,598:
*
* @param {Array} arr
* @
* removed; subsequent instances of those values (duplicates) remain.
* @throws When provided a non-array.
Line 1,614 ⟶ 1,604:
dups: function(arr) {
if (!Array.isArray(arr)) {
throw new Error('A non-array object passed to Morebits.array.dups');
}
return arr.filter(
},
/**
Line 1,627 ⟶ 1,614:
* @param {Array} arr
* @param {number} size - Size of each chunk (except the last, which could be different).
* @
* @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.
}
for (
result[i] = arr.slice(i * size, (i + 1) * size);
}
Line 1,654 ⟶ 1,641:
* @namespace Morebits.select2
* @memberof Morebits
* @requires
*/
Morebits.select2 = {
Line 1,663 ⟶ 1,650:
*/
optgroupFull: function(params, data) {
if (result && params.term &&
data.text.toUpperCase().
result.children = data.children;
}
Line 1,675 ⟶ 1,662:
/** Custom matcher that matches from the beginning of words only. */
wordBeginning: function(params, data) {
if (!params.term || (result &&
new RegExp('\\b' + mw.util.escapeRegExp(params.term), 'i').test(result.text))) {
Line 1,687 ⟶ 1,674:
/** Underline matched part of options. */
highlightSearchMatches: function(data) {
if (!searchTerm || data.loading) {
return data.text;
}
if (idx < 0) {
return data.text;
Line 1,718 ⟶ 1,705:
return;
}
if (!$target.length) {
return;
}
$target = $target.prev();
$target.select2('open');
$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[0].focus();
Line 1,731 ⟶ 1,718:
};
/**
Line 1,771 ⟶ 1,757:
throw new Error('Both prefix and postfix must be provided');
}
this.content = this.content.replace(re, Morebits.unbinder.getCallback(this));
},
Line 1,778 ⟶ 1,764:
* Restore the hidden portion of the `content` string.
*
* @
*/
rebind: function UnbinderRebind() {
content.self = this;
for (
if (Object.prototype.hasOwnProperty.call(this.history, current)) {
content = content.replace(current, this.history[current]);
Line 1,799 ⟶ 1,785:
Morebits.unbinder.getCallback = function UnbinderGetCallback(self) {
return function UnbinderCallback(match) {
self.history[current] = match;
++self.counter;
Line 1,805 ⟶ 1,791:
};
};
/* **************** Morebits.date **************** */
Line 1,818 ⟶ 1,802:
*/
Morebits.date = function() {
// Check MediaWiki formats
Line 1,825 ⟶ 1,809:
// 14-digit string will be interpreted differently.
if (args.length === 1) {
if (/^\d{14}$/.test(param)) {
// YYYYMMDDHHmmss
if (digitMatch) {
// ..... year ... month .. date ... hour .... minute ..... second
this.
}
} else if (typeof param === 'string') {
// Wikitext signature timestamp
if (dateParts) {
this.
}
}
}
if (!this.
// Try standard date
this.
}
Line 1,917 ⟶ 1,901:
Morebits.date.prototype = {
/** @
isValid: function() {
return !isNaN(this.getTime());
Line 1,924 ⟶ 1,908:
/**
* @param {(Date|Morebits.date)} date
* @
*/
isBefore: function(date) {
Line 1,931 ⟶ 1,915:
/**
* @param {(Date|Morebits.date)} date
* @
*/
isAfter: function(date) {
Line 1,937 ⟶ 1,921:
},
/** @
getUTCMonthName: function() {
return Morebits.date.localeData.months[this.getUTCMonth()];
},
/** @
getUTCMonthNameAbbrev: function() {
return Morebits.date.localeData.monthsShort[this.getUTCMonth()];
},
/** @
getMonthName: function() {
return Morebits.date.localeData.months[this.getMonth()];
},
/** @
getMonthNameAbbrev: function() {
return Morebits.date.localeData.monthsShort[this.getMonth()];
},
/** @
getUTCDayName: function() {
return Morebits.date.localeData.days[this.getUTCDay()];
},
/** @
getUTCDayNameAbbrev: function() {
return Morebits.date.localeData.daysShort[this.getUTCDay()];
},
/** @
getDayName: function() {
return Morebits.date.localeData.days[this.getDay()];
},
/** @
getDayNameAbbrev: function() {
return Morebits.date.localeData.daysShort[this.getDay()];
Line 1,977 ⟶ 1,961:
* @param {string} unit
* @throws If invalid or unsupported unit is given.
* @
*/
add: function(number, unit) {
if (isNaN(num)) {
throw new Error('Invalid number "' + number + '" provided.');
}
unit = unit.toLowerCase(); // normalize
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 2,006 ⟶ 1,991:
* @param {string} unit
* @throws If invalid or unsupported unit is given.
* @
*/
subtract: function(number, unit) {
Line 2,046 ⟶ 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.
* @
*/
format: function(formatstr, zone) {
Line 2,052 ⟶ 2,037:
return 'Invalid date'; // Put the truth out, preferable to "NaNNaNNan NaN:NaN" or whatever
}
// create a new date object that will contain the date to display as system time
if (zone === 'utc') {
Line 2,066 ⟶ 2,051:
}
len = len || 2; // Up to length of 00 + 1
return ('00' + num).toString().slice(0 - len);
};
HH: pad(h24), H: h24, hh: pad(h12), h: h12, A: amOrPm,
mm: pad(m), m: m,
Line 2,084 ⟶ 2,069:
};
unbinder.unbind('\\[', '\\]');
unbinder.content = unbinder.content.replace(
Line 2,092 ⟶ 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,
);
return unbinder.rebind().replace(/\[(.*?)\]/g, '$1');
Line 2,105 ⟶ 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.
* @
*/
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().
new Date(this).setHours(0, 0, 0, 0)) / 8.64e7;
switch (true) {
Line 2,132 ⟶ 2,115:
* as `==December 2019==` or `=== Jan 2018 ===`.
*
* @
*/
monthHeaderRegex: function() {
Line 2,144 ⟶ 2,127:
* @param {number} [level=2] - Header level. Pass 0 for just the text
* with no wikitext markers (==).
* @
*/
monthHeader: function(level) {
Line 2,151 ⟶ 2,134:
level = isNaN(level) ? 2 : level;
if (header.length) { // wikitext-formatted header
Line 2,164 ⟶ 2,147:
// Allow native Date.prototype methods to be used on Morebits.date objects
Object.getOwnPropertyNames(Date.prototype).forEach(
Morebits.date.prototype[func] = function() {
return this.
};
});
/* **************** Morebits.wiki **************** */
Line 2,184 ⟶ 2,166:
* @deprecated in favor of Morebits.isPageRedirect as of November 2020
* @memberof Morebits.wiki
* @
*/
Morebits.wiki.isPageRedirect = function wikipediaIsPageRedirect() {
Line 2,190 ⟶ 2,172:
return Morebits.isPageRedirect();
};
/* **************** Morebits.wiki.actionCompleted **************** */
Line 2,252 ⟶ 2,233:
}
}
window.setTimeout(
window.___location = Morebits.wiki.actionCompleted.redirect;
}, Morebits.wiki.actionCompleted.timeOut);
Line 2,276 ⟶ 2,257:
}
};
/* **************** Morebits.wiki.api **************** */
Line 2,295 ⟶ 2,275:
* @class
* @param {string} currentAction - The current action (required).
* @param {
* @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,305 ⟶ 2,285:
this.query.assert = 'user';
// Enforce newer error formats, preferring html
if (!query.errorformat || !['wikitext', 'plaintext'].
this.query.errorformat = 'html';
}
Line 2,326 ⟶ 2,306:
} else if (query.format === 'json' && !query.formatversion) {
this.query.formatversion = '2';
} else if (!['xml', 'json'].
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'].
delete query.tags;
} else if (!query.tags && morebitsWikiChangeTag) {
Line 2,342 ⟶ 2,322:
onSuccess: null,
onError: null,
parent: window,
query: null,
response: null,
responseXML: null,
statelem: null,
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,370 ⟶ 2,350:
* Carry out the request.
*
* @param {
* really want to give jQuery some extra parameters.
* @
*/
post: function(callerAjaxParameters) {
Line 2,378 ⟶ 2,358:
++Morebits.wiki.numberOfActionsLeft;
if (Array.isArray(val)) {
return encodeURIComponent(i) + '=' + val.map(encodeURIComponent).join('|');
Line 2,387 ⟶ 2,367:
// token should always be the last item in the query string (bug TW-B-0013)
context: this,
type: this.query.action === 'query' ? 'GET' : 'POST',
Line 2,453 ⟶ 2,433:
// 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(
this.query.token = token;
return this.post(callerAjaxParameters);
}
}
Line 2,497 ⟶ 2,477:
/** Retrieves wikitext from a page. Caching enabled, duration 1 day. */
Morebits.wiki.getCachedJson = function(title) {
action: 'query',
prop: 'revisions',
Line 2,507 ⟶ 2,487:
maxage: '86400' // cache for 1 day
};
return new Morebits.wiki.api('', query).post().then(
apiobj.getStatusElement().unlink();
return JSON.parse(wikitext);
});
Line 2,532 ⟶ 2,512:
morebitsWikiApiUserAgent = (ua ? ua + ' ' : '') + 'morebits.js ([[w:WT:TW]])';
};
/**
Line 2,544 ⟶ 2,522:
*/
var morebitsWikiChangeTag = '';
/**
Line 2,550 ⟶ 2,527:
*
* @memberof Morebits.wiki.api
* @
*/
Morebits.wiki.api.getToken = function() {
action: 'query',
meta: 'tokens',
Line 2,559 ⟶ 2,536:
format: 'json'
});
return tokenApi.post().then(
};
/* **************** Morebits.wiki.page **************** */
Line 2,604 ⟶ 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,627 ⟶ 2,600:
* @private
*/
// backing fields for public properties
pageName: pageName,
Line 2,633 ⟶ 2,606:
editSummary: null,
changeTags: null,
testActions: null,
callbackParameters: null,
statusElement: status instanceof Morebits.status ? status : new Morebits.status(status),
Line 2,639 ⟶ 2,612:
// - edit
pageText: null,
editMode: 'all',
appendText: null,
prependText: null,
newSectionText: null,
newSectionTitle: null,
Line 2,739 ⟶ 2,712:
};
/**
Line 2,772 ⟶ 2,745:
if (ctx.editMode === 'all') {
ctx.loadQuery.rvprop = 'content|timestamp';
} else if (ctx.editMode === 'revert') {
ctx.loadQuery.rvprop = 'timestamp';
Line 2,780 ⟶ 2,753:
if (ctx.followRedirect) {
ctx.loadQuery.redirects = '';
}
if (typeof ctx.pageSection === 'number') {
Line 2,812 ⟶ 2,785:
// are we getting our editing token from mw.user.tokens?
if (!ctx.pageLoaded && !canUseMwUserToken) {
Line 2,835 ⟶ 2,808:
if (ctx.fullyProtected && !ctx.suppressProtectWarning &&
!confirm(
ctx.fullyProtected === 'infinity' ?
'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.'
) :
'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.'
Line 2,852 ⟶ 2,825:
ctx.retries = 0;
action: 'edit',
title: ctx.pageName,
Line 2,876 ⟶ 2,849:
query.minor = true;
} else {
query.notminor = true;
}
Line 2,891 ⟶ 2,864:
return;
}
query.appendtext = ctx.appendText;
break;
case 'prepend':
Line 2,899 ⟶ 2,872:
return;
}
query.prependtext = ctx.prependText;
break;
case 'new':
Line 2,908 ⟶ 2,881:
}
query.section = 'new';
query.text = ctx.newSectionText;
query.sectiontitle = ctx.newSectionTitle || ctx.editSummary; // done by the API, but non-'' values would get treated as text
break;
Line 2,928 ⟶ 2,901:
}
if (['recreate', 'createonly', 'nocreate'].
query[ctx.createOption] = '';
}
Line 3,004 ⟶ 2,977:
};
/** @
this.getPageName = function() {
return ctx.pageName;
};
/** @
this.getPageText = function() {
return ctx.pageText;
Line 3,046 ⟶ 3,019:
ctx.newSectionTitle = newSectionTitle;
};
// Edit-related setter methods:
Line 3,071 ⟶ 3,042:
ctx.changeTags = tags;
};
/**
Line 3,081 ⟶ 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,344 ⟶ 3,313:
};
/** @
this.getCurrentID = function() {
return ctx.revertCurID;
};
/** @
this.getRevisionUser = function() {
return ctx.revertUser;
};
/** @
this.getLastEditTime = function() {
return ctx.lastEditTime;
Line 3,371 ⟶ 3,340:
* detected upon calling `save()`.
*
* @param {
*/
this.setCallbackParameters = function(callbackParameters) {
Line 3,378 ⟶ 3,347:
/**
* @
*/
this.getCallbackParameters = function() {
Line 3,392 ⟶ 3,361:
/**
* @
*/
this.getStatusElement = function() {
Line 3,408 ⟶ 3,377:
/**
* @
*/
this.exists = function() {
Line 3,415 ⟶ 3,384:
/**
* @
* exist.
*/
Line 3,423 ⟶ 3,392:
/**
* @
* include (but may not be limited to): `wikitext`, `javascript`,
* `css`, `json`, `Scribunto`, `sanitized-css`, `MassMessageListContent`.
Line 3,433 ⟶ 3,402:
/**
* @
* unless it's being watched temporarily, in which case returns the
* expiry string.
Line 3,442 ⟶ 3,411:
/**
* @
*/
this.getLoadTime = function() {
Line 3,449 ⟶ 3,418:
/**
* @
*/
this.getCreator = function() {
Line 3,456 ⟶ 3,425:
/**
* @
*/
this.getCreationTimestamp = function() {
Line 3,462 ⟶ 3,431:
};
/** @
this.canEdit = function() {
return !!ctx.testActions && ctx.testActions.
};
Line 3,488 ⟶ 3,457:
}
action: 'query',
prop: 'revisions',
Line 3,509 ⟶ 3,478:
if (ctx.followRedirect) {
query.redirects = '';
}
Line 3,560 ⟶ 3,529:
fnProcessMove.call(this, this);
} else {
ctx.moveApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessMove, ctx.statusElement, ctx.onMoveFailure);
Line 3,584 ⟶ 3,553:
// If a link is present, don't need to check if it's patrolled
if ($('.patrollink').length) {
ctx.rcid = mw.util.getParamValue('rcid', patrolhref);
fnProcessPatrol(this, this);
} else {
action: 'query',
prop: 'info',
Line 3,626 ⟶ 3,595:
this.triage = function() {
// Fall back to patrol if not a valid triage namespace
if (!mw.config.get('pageTriageNamespaces').
this.patrol();
} else {
Line 3,638 ⟶ 3,607:
fnProcessTriageList(this, this);
} else {
ctx.triageApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessTriageList);
Line 3,665 ⟶ 3,634:
fnProcessDelete.call(this, this);
} else {
ctx.deleteApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessDelete, ctx.statusElement, ctx.onDeleteFailure);
Line 3,690 ⟶ 3,659:
fnProcessUndelete.call(this, this);
} else {
ctx.undeleteApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessUndelete, ctx.statusElement, ctx.onUndeleteFailure);
Line 3,721 ⟶ 3,690:
// (absolute, not differential), we always need to request
// protection levels from the server
ctx.protectApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessProtect, ctx.statusElement, ctx.onProtectFailure);
Line 3,756 ⟶ 3,725:
fnProcessStabilize.call(this, this);
} else {
ctx.stabilizeApi = new Morebits.wiki.api(msg('getting-token', 'retrieving token...'), query, fnProcessStabilize, ctx.statusElement, ctx.onStabilizeFailure);
Line 3,780 ⟶ 3,749:
* @param {string} [action=edit] - The action being undertaken, e.g.
* "edit" or "delete". In practice, only "edit" or "notedit" matters.
* @
*/
var fnCanUseMwUserToken = function(action = 'edit') {
Line 3,809 ⟶ 3,778:
// wgRestrictionEdit is null on non-existent pages,
// so this neatly handles nonexistent pages
if (!editRestriction || editRestriction.
return false;
}
Line 3,831 ⟶ 3,800:
* @param {string} action - The action being undertaken, e.g. "edit" or
* "delete".
* @
*/
var fnNeedTokenInfoQuery = function(action) {
action: 'query',
meta: 'tokens',
Line 3,860 ⟶ 3,829:
// callback from loadApi.post()
var fnLoadSuccess = function() {
if (!fnCheckPageName(response, ctx.onLoadFailure)) {
Line 3,866 ⟶ 3,835:
}
let rev;
ctx.pageExists = !page.missing;
if (ctx.pageExists) {
Line 3,874 ⟶ 3,844:
ctx.pageID = page.pageid;
} else {
ctx.pageText = '';
ctx.pageID = 0; // nonexistent in response, matches wgArticleId
}
Line 3,896 ⟶ 3,866:
// Includes cascading protection
if (Morebits.userIsSysop) {
if (editProt) {
ctx.fullyProtected = editProt.expiry;
Line 3,908 ⟶ 3,876:
ctx.revertCurID = page.lastrevid;
ctx.testActions = []; // was null
Object.keys(testactions).forEach(
if (testactions[action]) {
ctx.testActions.push(action);
Line 3,925 ⟶ 3,893:
ctx.revertUser = rev && rev.user;
if (!ctx.revertUser) {
if (rev && rev.userhidden) {
ctx.revertUser = '<username hidden>';
} else {
Line 3,940 ⟶ 3,908:
// alert("Generate edit conflict now"); // for testing edit conflict recovery logic
ctx.onLoadSuccess(this);
};
Line 3,949 ⟶ 3,917:
}
if (page) {
// check for invalid titles
Line 3,959 ⟶ 3,927:
// retrieve actual title of the page after normalization and redirects
if (response.redirects) {
// check for cross-namespace redirect:
if (origNs !== newNs && !ctx.followCrossNsRedirect) {
ctx.statusElement.error(msg('cross-redirect-abort', ctx.pageName, resolvedName, ctx.pageName + ' is a cross-namespace redirect to ' + resolvedName + ', aborted'));
Line 3,998 ⟶ 3,966:
* ensured of knowing the watch status by the use of this.
*
* @
*/
var fnApplyWatchlistExpiry = function() {
Line 4,005 ⟶ 3,973:
return true;
} else if (typeof ctx.watched === 'string') {
// Attempt to determine if the new expiry is a
// relative (e.g. `1 month`) or absolute datetime
try {
newExpiry = new Morebits.date().add(rel[0], rel[1]);
Line 4,033 ⟶ 4,001:
// callback from saveApi.post()
var fnSaveSuccess = function() {
ctx.editMode = 'all';
// see if the API thinks we were successful
Line 4,041 ⟶ 4,009:
// real success
// default on success action - display link for edited page
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);
}
return;
Line 4,067 ⟶ 4,035:
// callback from saveApi.post()
var fnSaveError = function() {
// check for edit conflict
Line 4,073 ⟶ 4,041:
// edit conflicts can occur when the page needs to be purged from the server cache
action: 'purge',
titles: ctx.pageName
};
--Morebits.wiki.numberOfActionsLeft;
ctx.statusElement.info(msg('editconflict-retrying', 'Edit conflict detected, reapplying edit'));
Line 4,087 ⟶ 4,055:
ctx.loadApi.post(); // reload the page and reapply the edit
}
}), ctx.statusElement);
purgeApi.post();
Line 4,095 ⟶ 4,063:
// 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;
// wait for sometime for client to regain connectivity
sleep(2000).then(
ctx.saveApi.post(); // give it another go!
});
Line 4,104 ⟶ 4,072:
// hard error, give up
} else {
response.errors[0].data; // html/wikitext/plaintext error format
Line 4,135 ⟶ 4,103:
}
ctx.editMode = 'all';
if (ctx.onSaveFailure) {
ctx.onSaveFailure(this);
}
}
};
if (!text) { // no text - content empty or inaccessible (revdelled or suppressed)
return false;
}
return Morebits.l10n.redirectTagAliases.some(
};
var fnLookupCreationSuccess = function() {
if (!fnCheckPageName(response, ctx.onLookupCreationFailure)) {
Line 4,158 ⟶ 4,124:
}
if (!rev) {
ctx.statusElement.error('Could not find any revisions of ' + ctx.pageName);
Line 4,195 ⟶ 4,161:
var fnLookupNonRedirectCreator = function() {
for (
if (!isTextRedirect(revs[i].content)) {
Line 4,235 ⟶ 4,201:
* @param {string} action - The action being checked.
* @param {string} onFailure - Failure callback.
* @
*/
var fnPreflightChecks = function(action, onFailure) {
Line 4,260 ⟶ 4,226:
* @param {string} onFailure - Failure callback.
* @param {string} response - The response document from the API call.
* @
*/
// No undelete as an existing page could have deleted revisions
if (actionMissing || protectMissing || saltMissing) {
Line 4,278 ⟶ 4,244:
// Delete, undelete, move
// extract protection info
if (action === 'undelete') {
editprot = response.pages[0].protection.filter(
} else if (action === 'delete' || action === 'move') {
editprot = response.pages[0].protection.filter(
}
if (editprot && !ctx.suppressProtectWarning &&
Line 4,306 ⟶ 4,268:
var fnProcessMove = function() {
if (fnCanUseMwUserToken('move')) {
Line 4,312 ⟶ 4,274:
pageTitle = ctx.pageName;
} else {
if (!fnProcessChecks('move', ctx.onMoveFailure, response)) {
Line 4,319 ⟶ 4,281:
token = response.tokens.csrftoken;
pageTitle = page.title;
ctx.watched = page.watchlistexpiry || page.watched;
}
action: 'move',
from: pageTitle,
Line 4,356 ⟶ 4,318:
var fnProcessPatrol = function() {
action: 'patrol',
format: 'json'
Line 4,366 ⟶ 4,328:
query.token = mw.user.tokens.get('patrolToken');
} else {
// Don't patrol if not unpatrolled
Line 4,373 ⟶ 4,335:
}
if (!lastrevid) {
return;
Line 4,379 ⟶ 4,341:
query.revid = lastrevid;
if (!token) {
return;
Line 4,389 ⟶ 4,351:
}
ctx.patrolProcessApi = new Morebits.wiki.api('patrolling page...', query, null, patrolStat);
Line 4,401 ⟶ 4,363:
ctx.csrfToken = mw.user.tokens.get('csrfToken');
} else {
ctx.pageID = response.pages[0].pageid;
Line 4,414 ⟶ 4,376:
}
action: 'pagetriagelist',
page_id: ctx.pageID,
Line 4,427 ⟶ 4,389:
// callback from triageProcessListApi.post()
var fnProcessTriage = function() {
// Exit if not in the queue
if (!responseList || responseList.result !== 'success') {
return;
}
// Do nothing if page already triaged/patrolled
if (!page || !parseInt(page.patrol_status, 10)) {
action: 'pagetriageaction',
pageid: ctx.pageID,
Line 4,445 ⟶ 4,407:
format: 'json'
};
ctx.triageProcessApi = new Morebits.wiki.api('curating page...', query, null, triageStat);
ctx.triageProcessApi.setParent(this);
Line 4,453 ⟶ 4,415:
var fnProcessDelete = function() {
if (fnCanUseMwUserToken('delete')) {
Line 4,459 ⟶ 4,421:
pageTitle = ctx.pageName;
} else {
if (!fnProcessChecks('delete', ctx.onDeleteFailure, response)) {
Line 4,466 ⟶ 4,428:
token = response.tokens.csrftoken;
pageTitle = page.title;
ctx.watched = page.watchlistexpiry || page.watched;
}
action: 'delete',
title: pageTitle,
Line 4,498 ⟶ 4,460:
var fnProcessDeleteError = function() {
// 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;
ctx.deleteProcessApi.post(); // give it another go!
Line 4,509 ⟶ 4,471:
ctx.statusElement.error('Cannot delete the page, because it no longer exists');
if (ctx.onDeleteFailure) {
ctx.onDeleteFailure.call(this, ctx.deleteProcessApi);
}
// hard error, give up
Line 4,515 ⟶ 4,477:
ctx.statusElement.error('Failed to delete the page: ' + ctx.deleteProcessApi.getErrorText());
if (ctx.onDeleteFailure) {
ctx.onDeleteFailure.call(this, ctx.deleteProcessApi);
}
}
Line 4,521 ⟶ 4,483:
var fnProcessUndelete = function() {
if (fnCanUseMwUserToken('undelete')) {
Line 4,527 ⟶ 4,489:
pageTitle = ctx.pageName;
} else {
if (!fnProcessChecks('undelete', ctx.onUndeleteFailure, response)) {
Line 4,534 ⟶ 4,496:
token = response.tokens.csrftoken;
pageTitle = page.title;
ctx.watched = page.watchlistexpiry || page.watched;
}
action: 'undelete',
title: pageTitle,
Line 4,566 ⟶ 4,528:
var fnProcessUndeleteError = function() {
// check for "Database query error"
Line 4,572 ⟶ 4,534:
if (ctx.retries++ < ctx.maxRetries) {
ctx.statusElement.info('Database query error, retrying');
--Morebits.wiki.numberOfActionsLeft;
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);
}
}
Line 4,583 ⟶ 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);
}
// hard error, give up
Line 4,589 ⟶ 4,551:
ctx.statusElement.error('Failed to undelete the page: ' + ctx.undeleteProcessApi.getErrorText());
if (ctx.onUndeleteFailure) {
ctx.onUndeleteFailure.call(this, ctx.undeleteProcessApi);
}
}
Line 4,595 ⟶ 4,557:
var fnProcessProtect = function() {
if (!fnProcessChecks('protect', ctx.onProtectFailure, response)) {
Line 4,601 ⟶ 4,563:
}
ctx.watched = page.watchlistexpiry || page.watched;
// Fetch existing protection levels
prs.forEach(
// Filter out protection from cascading
if (pr.type === 'edit' && !pr.source) {
Line 4,619 ⟶ 4,581:
}
});
// Fall back to current levels if not explicitly set
Line 4,634 ⟶ 4,595:
// Default to pre-existing cascading protection if unchanged (similar to above)
if (ctx.protectCascade === null) {
ctx.protectCascade = !!prs.filter(
}
// Warn if cascading protection being applied with an invalid protection level,
Line 4,658 ⟶ 4,617:
// Build protection levels and expirys (expiries?) for query
if (ctx.protectEdit) {
protections.push('edit=' + ctx.protectEdit.level);
Line 4,674 ⟶ 4,633:
}
action: 'protect',
title: pageTitle,
Line 4,702 ⟶ 4,661:
var fnProcessStabilize = function() {
if (fnCanUseMwUserToken('stabilize')) {
Line 4,708 ⟶ 4,667:
pageTitle = ctx.pageName;
} else {
// 'stabilize' as a verb not necessarily well understood
Line 4,716 ⟶ 4,675:
token = response.tokens.csrftoken;
pageTitle = page.title;
// Doesn't support watchlist expiry [[phab:T263336]]
Line 4,722 ⟶ 4,681:
}
action: 'stabilize',
title: pageTitle,
Line 4,746 ⟶ 4,705:
var sleep = function(milliseconds) {
setTimeout(deferred.resolve, milliseconds);
return deferred;
Line 4,759 ⟶ 4,718:
* - Need to reset all parameters once done (e.g. edit summary, move destination, etc.)
*/
/* **************** Morebits.wiki.preview **************** */
Line 4,787 ⟶ 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.
* @
*/
this.beginRender = function(wikitext, pageTitle, sectionTitle) {
$(previewbox).show();
previewbox.appendChild(statusspan);
Morebits.status.init(statusspan);
action: 'parse',
prop: ['text', 'modules'],
pst: true,
preview: true,
text: wikitext,
Line 4,811 ⟶ 4,769:
query.sectiontitle = sectionTitle;
}
return renderApi.post();
};
var fnRenderSuccess = function(apiobj) {
if (!html) {
apiobj.statelem.error('failed to retrieve preview, or template was blanked');
Line 4,835 ⟶ 4,793:
};
};
/* **************** Morebits.wikitext **************** */
Line 4,853 ⟶ 4,810:
* @param {string} text - Wikitext containing a template.
* @param {number} [start=0] - Index noting where in the text the template begins.
* @
*/
Morebits.wikitext.parseTemplate = function(text, start) {
start = start || 0;
name: '',
parameters: {}
};
/**
Line 4,878 ⟶ 4,835:
// Nothing found yet, this must be the template name
if (count === -1) {
result.name = current.
++count;
} else {
Line 4,890 ⟶ 4,847:
} else {
// No equals, so it must be unnamed; no trim since whitespace allowed
if (param) {
result.parameters[++unnamed] = param;
Line 4,899 ⟶ 4,856:
}
for (
if (test3 === '{{{' || (test3 === '}}}' && level[level.length - 1] === 3)) {
current += test3;
Line 4,911 ⟶ 4,868:
continue;
}
// Entering a template (or link)
if (test2 === '{{' || test2 === '[[') {
Line 4,973 ⟶ 4,930:
*
* @param {string} link_target
* @
*/
removeLink: function(link_target) {
if (namespaceID !== 0) {
link_regex_string = Morebits.namespaceRegex(namespaceID) + ':';
Line 4,988 ⟶ 4,945:
// For most namespaces, unlink both [[User:Test]] and [[:User:Test]]
// For files and categories, only unlink [[:Category:Test]]. Do not unlink [[Category:Test]]
this.text = this.text.replace(simple_link_regex, '$1').replace(piped_link_regex, '$1');
return this;
Line 5,003 ⟶ 4,960:
* @param {string} image - Image name without `File:` prefix.
* @param {string} [reason] - Reason to be included in comment, alongside the commented-out image.
* @
*/
commentOutImage: function(image, reason) {
unbinder.unbind('<!--', '-->');
reason = reason ? reason + ': ' : '';
// Check for normal image links, i.e. [[File:Foobar.png|...]]
// Will eat the whole link
for (
if (links_re.test(allLinks[i])) {
unbinder.content = unbinder.content.replace(allLinks[i], replacement);
// unbind the newly created comments
Line 5,028 ⟶ 4,985:
// eventually preceded with some space, and must include File: prefix
// Will eat the whole line.
unbinder.content = unbinder.content.replace(gallery_image_re, '<!-- ' + reason + '$1 -->');
Line 5,036 ⟶ 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
unbinder.content = unbinder.content.replace(free_image_re, '<!-- ' + reason + '$1 -->');
// Rebind the content now, we are done!
Line 5,048 ⟶ 5,005:
* @param {string} image - Image name without File: prefix.
* @param {string} data - The display options.
* @
*/
addToImageComment: function(image, data) {
for (
if (links_re.test(allLinks[i])) {
// just put it at the end?
replacement = replacement.replace(/\]\]$/, '|' + data + ']]');
Line 5,062 ⟶ 5,019:
}
}
this.text = this.text.replace(gallery_re, newtext);
return this;
Line 5,073 ⟶ 5,030:
* @param {string} template - Page name whose transclusions are to be removed,
* include namespace prefix only if not in template namespace.
* @
*/
removeTemplate: function(template) {
for (
if (links_re.test(allTemplates[i])) {
this.text = this.text.replace(allTemplates[i], '');
Line 5,099 ⟶ 5,056:
* @param {string|string[]} [preRegex] - Optional regex string or array to match
* before any template matches (i.e. before `{{`), such as html comments.
* @
*/
insertAfterTemplates: function(tag, regex, flags, preRegex) {
Line 5,123 ⟶ 5,080:
preRegex = preRegex.join('|');
}
// Regex is extra complicated to allow for templates with
Line 5,158 ⟶ 5,114:
* Get the manipulated wikitext.
*
* @
*/
getText: function() {
Line 5,164 ⟶ 5,120:
}
};
/* *********** Morebits.userspaceLogger ************ */
Line 5,198 ⟶ 5,153:
* @param {string} logText - Doesn't include leading `#` or `*`.
* @param {string} summaryText - Edit summary.
* @
*/
this.log = function(logText, summaryText) {
if (!logText) {
return def.reject();
}
'Adding entry to userspace log'); // make this '... to ' + logPageName ?
page.load(
// add blurb if log page doesn't exist or is blank
// create monthly header if it doesn't exist already
if (!date.monthHeaderRegex().exec(text)) {
text += '\n\n' + date.monthHeader(this.headerLevel);
Line 5,222 ⟶ 5,177:
pageobj.setCreateOption('recreate');
pageobj.save(def.resolve, def.reject);
}
return def;
};
};
/* **************** Morebits.status **************** */
Line 5,282 ⟶ 5,236:
Morebits.status.errorEvent = handler;
} else {
throw new Error('Morebits.status.onError: handler is not a function');
}
};
Line 5,375 ⟶ 5,329:
* @param {string} text - Before colon
* @param {string} status - After colon
* @
*/
Morebits.status.status = function(text, status) {
Line 5,384 ⟶ 5,338:
* @param {string} text - Before colon
* @param {string} status - After colon
* @
*/
Morebits.status.info = function(text, status) {
Line 5,393 ⟶ 5,347:
* @param {string} text - Before colon
* @param {string} status - After colon
* @
*/
Morebits.status.warn = function(text, status) {
Line 5,402 ⟶ 5,356:
* @param {string} text - Before colon
* @param {string} status - After colon
* @
*/
Morebits.status.error = function(text, status) {
Line 5,416 ⟶ 5,370:
*/
Morebits.status.actionCompleted = function(text) {
node.appendChild(document.createElement('b')).appendChild(document.createTextNode(text));
node.className = 'morebits_status_info morebits_action_complete';
Line 5,433 ⟶ 5,387:
*/
Morebits.status.printUserText = function(comments, message) {
p.innerHTML = message;
div.className = 'morebits-usertext';
div.style.marginTop = '0';
Line 5,443 ⟶ 5,397:
Morebits.status.root.appendChild(p);
};
/**
Line 5,452 ⟶ 5,404:
* @param {string} content - Text content.
* @param {string} [color] - Font color.
* @
*/
Morebits.htmlNode = function (type, content, color) {
if (color) {
node.style.color = color;
Line 5,462 ⟶ 5,414:
return node;
};
/**
Line 5,474 ⟶ 5,424:
*/
Morebits.checkboxShiftClickSupport = function (jQuerySelector, jQueryContext) {
function clickHandler(event) {
if (event.shiftKey && lastCheckbox !== null) {
for (i = 0; i < $cbs.length; i++) {
if ($cbs[i] === thisCb) {
index = i;
if (lastIndex > -1) {
Line 5,488 ⟶ 5,438:
}
}
if ($cbs[i] === lastCheckbox) {
lastIndex = i;
if (index > -1) {
Line 5,498 ⟶ 5,448:
if (index > -1 && lastIndex > -1) {
// inspired by wikibits
if (index < lastIndex) {
start = index + 1;
Line 5,509 ⟶ 5,459:
for (i = start; i <= finish; i++) {
if ($cbs[i].checked !== endState) {
$cbs[i].click();
}
}
Line 5,519 ⟶ 5,469:
}
$(jQuerySelector, jQueryContext).
};
/* **************** Morebits.batchOperation **************** */
Line 5,563 ⟶ 5,511:
*/
Morebits.batchOperation = function(currentAction) {
// backing fields for public properties
pageList: null,
Line 5,637 ⟶ 5,585:
ctx.pageChunks = [];
if (!total) {
ctx.statusElement.info(msg('batch-no-pages', 'no pages specified'));
Line 5,669 ⟶ 5,617:
if (arg instanceof Morebits.wiki.api || arg instanceof Morebits.wiki.page) {
// update or remove status line
if (ctx.options.preserveIndividualStatusLines) {
if (arg.getPageName || arg.pageName || (arg.query && arg.query.title)) {
// we know the page title - display a relevant message
statelem.info(msg('batch-done-page', pageName, 'completed ([[' + pageName + ']])'));
} else {
Line 5,698 ⟶ 5,646:
// private functions
var fnStartNewChunk = function() {
if (!chunk) {
return;
}
// start workers for the current chunk
ctx.countStarted += chunk.length;
chunk.forEach(
ctx.worker(page, thisProxy);
});
Line 5,717 ⟶ 5,665:
// update overall status line
if (ctx.countFinished < total) {
ctx.statusElement.status(msg('percent', progress, progress + '%'));
Line 5,729 ⟶ 5,677:
}
} else if (ctx.countFinished === total) {
'/' + ctx.countFinished + ' actions completed successfully)');
if (ctx.countFinishedSuccess < ctx.countFinished) {
Line 5,781 ⟶ 5,729:
this.add = function(func, deps, onFailure) {
this.taskDependencyMap.set(func, deps);
this.failureCallbackMap.set(func, onFailure ||
this.deferreds.set(func, deferred);
};
Line 5,789 ⟶ 5,737:
* Run all the tasks. Multiple tasks may be run at once.
*
* @
*/
this.execute = function() {
this.taskDependencyMap.forEach(
$.when.apply(self.context, dependencyPromisesArray).then(function() {
if (result === undefined) { // maybe the function threw, or it didn't return anything
mw.log.error('Morebits.taskManager: task returned undefined');
Line 5,824 ⟶ 5,770:
* @memberof Morebits
* @class
* @requires
* @param {number} width
* @param {number} height - The maximum allowable height for the content area.
*/
Morebits.simpleWindow = function SimpleWindow(width, height) {
this.content = content;
content.className = 'morebits-dialog-content';
Line 5,840 ⟶ 5,786:
buttons: { 'Placeholder button': function() {} },
dialogClass: 'morebits-dialog',
width: Math.min(parseInt(window.innerWidth, 10), parseInt(width
// give jQuery the given height value (which represents the anticipated height of the dialog) here, so
// it can position the dialog appropriately
Line 5,867 ⟶ 5,813:
});
// delete the placeholder button (it's only there so the buttonpane gets created)
$widget.find('button').each(
value.parentNode.removeChild(value);
});
// add container for the buttons we add, and the footer links (if any)
buttonspan.className = 'morebits-dialog-buttons';
linksspan.className = 'morebits-dialog-footerlinks';
$widget.find('.ui-dialog-buttonpane').append(buttonspan, linksspan);
Line 5,897 ⟶ 5,843:
* Focuses the dialog. This might work, or on the contrary, it might not.
*
* @
*/
focus: function() {
Line 5,909 ⟶ 5,855:
*
* @param {event} [event]
* @
*/
close: function(event) {
Line 5,923 ⟶ 5,869:
* might work, but it is not guaranteed.
*
* @
*/
display: function() {
if (this.scriptName) {
$widget.find('.morebits-dialog-scriptname').remove();
scriptnamespan.className = 'morebits-dialog-scriptname';
scriptnamespan.textContent = this.scriptName + ' \u00B7 ';
$widget.find('.ui-dialog-title').prepend(scriptnamespan);
}
if (window.setupTooltips && window.pg && window.pg.re && window.pg.re.diff) {
dialog.parent()[0].ranSetupTooltipsAlready = false;
window.setupTooltips(dialog.parent()[0]);
}
this.setHeight(this.height);
return this;
},
Line 5,948 ⟶ 5,894:
*
* @param {string} title
* @
*/
setTitle: function(title) {
Line 5,960 ⟶ 5,906:
*
* @param {string} name
* @
*/
setScriptName: function(name) {
Line 5,971 ⟶ 5,917:
*
* @param {number} width
* @
*/
setWidth: function(width) {
Line 5,983 ⟶ 5,929:
*
* @param {number} height
* @
*/
setHeight: function(height) {
Line 6,009 ⟶ 5,955:
*
* @param {HTMLElement} content
* @
*/
setContent: function(content) {
Line 6,021 ⟶ 5,967:
*
* @param {HTMLElement} content
* @
*/
addContent: function(content) {
Line 6,027 ⟶ 5,973:
// look for submit buttons in the content, hide them, and add a proxy button to the button pane
$(this.content).find('input[type="submit"], button[type="submit"]').each(
value.style.display = 'none';
if (value.hasAttribute('value')) {
Line 6,042 ⟶ 5,988:
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',
value.click();
}, false);
Line 6,051 ⟶ 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');
}
return this;
Line 6,059 ⟶ 6,005:
* Removes all contents from the dialog, barring any footer links.
*
* @
*/
purgeContent: function() {
Line 6,081 ⟶ 6,027:
* @param {string} wikiPage - Link target.
* @param {boolean} [prep=false] - Set true to prepend rather than append.
* @
*/
addFooterLink: function(text, wikiPage, prep) {
if (this.hasFooterLinks) {
bullet.textContent = msg('bullet-separator', ' \u2022 ');
if (prep) {
$footerlinks.prepend(bullet);
Line 6,094 ⟶ 6,040:
}
}
link.setAttribute('href', mw.util.getUrl(wikiPage));
link.setAttribute('title', wikiPage);
Line 6,115 ⟶ 6,061:
* @param {boolean} [modal=false] - If set to true, other items on the
* page will be disabled, i.e., cannot be interacted with.
* @
*/
setModality: function(modal) {
Line 6,138 ⟶ 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;
/**
Line 6,151 ⟶ 6,110:
*/
if (typeof arguments === 'undefined') {
/* global Morebits */
window.SimpleWindow = Morebits.simpleWindow;
|