MediaWiki:Gadget-morebits.js: Difference between revisions

Repo at d404881: Greatly expand style guidelines, enforce linting rules (#657)
imported>Amorymeltzer
(Repo at 769b724: Shift lookupCreator to lookupCreation, also include timestamp; Add documentation for Morebits.status (#645); checkboxShiftClickSupport: trigger click event; Remove Morebits.wikipedia (#600); Add untag functionality (#485); batchOperation: allow post processing function; Remove Morebits.bytes)
(Repo at d404881: Greatly expand style guidelines, enforce linting rules (#657))
Line 1:
// <nowiki>
/**
* morebits.js
Line 30:
 
 
( function ( window, document, $, undefined ) { // Wrap entire file with anonymous function
 
var Morebits = {};
Line 43:
* @returns {boolean}
*/
Morebits.userIsInGroup = function ( group ) {
return mw.config.get( 'wgUserGroups' ).indexOf( group ) !== -1;
};
 
Line 55:
* Converts an IPv6 address to the canonical form stored and used by MediaWiki.
*/
Morebits.sanitizeIPv6 = function ( address ) {
address = address.trim();
if ( address === '' ) {
return null;
}
if ( !mw.util.isIPv6Address( address ) ) {
return address; // nothing else to do for IPv4 addresses or invalid ones
}
Line 66:
address = address.toUpperCase();
// Expand zero abbreviations
var 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").
var CIDRStart = address.indexOf( '/' );
var addressEnd = ( CIDRStart > -1 ) ? CIDRStart - 1 : address.length - 1;
// If the '::' is at the beginning...
var repeat, extra, pad;
if ( abbrevPos === 0 ) {
repeat = '0:';
extra = ( address === '::' ) ? '0' : ''; // for the address '::'
pad = 9; // 7+2 (due to '::')
// If the '::' is at the end...
} else if ( abbrevPos === ( addressEnd - 1 ) ) {
repeat = ':0';
extra = '';
Line 90:
}
var replacement = repeat;
pad -= address.split( ':' ).length - 1;
for ( var i = 1; i < pad; i++ ) {
replacement += repeat;
}
replacement += extra;
address = address.replace( '::', replacement );
}
// Remove leading zeros from each bloc as needed
address = address.replace( /(^|:)0+([0-9A-Fa-f]{1,4})/g, '$1$2' );
 
return address;
Line 153:
* @param {*} eventType
*/
Morebits.quickForm = function QuickForm( event, eventType ) {
this.root = new Morebits.quickForm.element( { type: 'form', event: event, eventType: eventType } );
};
 
Line 171:
* @param {Morebits.quickForm.element} data
*/
Morebits.quickForm.prototype.append = function QuickFormAppend( data ) {
return this.root.append( data );
};
 
Line 179:
* @param {Object}
*/
Morebits.quickForm.element = function QuickFormElement( data ) {
this.data = data;
this.childs = [];
Line 193:
* @returns {Morebits.quickForm.element} The same element passed in
*/
Morebits.quickForm.element.prototype.append = function QuickFormElementAppend( data ) {
var child;
if ( data instanceof Morebits.quickForm.element ) {
child = data;
} else {
child = new Morebits.quickForm.element( data );
}
this.childs.push( child );
return child;
};
Line 209:
* @returns {HTMLElement}
*/
Morebits.quickForm.element.prototype.render = function QuickFormElementRender( internal_subgroup_id ) {
var currentNode = this.compute( this.data, internal_subgroup_id );
 
for( (var i = 0; i < this.childs.length; ++i ) {
// do not pass internal_subgroup_id to recursive calls
currentNode[1].appendChild( this.childs[i].render() );
}
return currentNode[0];
};
 
Morebits.quickForm.element.prototype.compute = function QuickFormElementCompute( data, in_id ) {
var node;
var childContainder = null;
var label;
var id = ( in_id ? in_id + '_' : '' ) + 'node_' + this.id;
if( (data.adminonly && !Morebits.userIsInGroup( 'sysop' ) ) {
// hell hack alpha
data.type = 'hidden';
Line 230:
 
var i, current, subnode;
switch ( data.type ) {
case 'form':
node = document.createElement( 'form' );
node.className = "'quickform"';
node.setAttribute( 'action', 'javascript:void(0);');
if ( data.event ) {
node.addEventListener( data.eventType || 'submit', data.event , false );
}
break;
case 'fragment':
node = document.createDocumentFragment();
// fragments can't have any attributes, so just return it straight away
return [ node, node ];
case 'select':
node = document.createElement( 'div' );
 
node.setAttribute( 'id', 'div_' + id );
if ( data.label ) {
label = node.appendChild( document.createElement( 'label' ) );
label.setAttribute( 'for', id );
label.appendChild( document.createTextNode( data.label ) );
}
var select = node.appendChild( document.createElement( 'select' ) );
if ( data.event ) {
select.addEventListener( 'change', data.event, false );
}
if ( data.multiple ) {
select.setAttribute( 'multiple', 'multiple' );
}
if ( data.size ) {
select.setAttribute( 'size', data.size );
}
select.setAttribute( 'name', data.name );
 
if ( data.list ) {
for( (i = 0; i < data.list.length; ++i ) {
 
current = data.list[i];
 
if ( current.list ) {
current.type = 'optgroup';
} else {
current.type = 'option';
}
 
subnode = this.compute( current );
select.appendChild( subnode[0] );
}
}
childContainder = select;
}
break;
childContainder = select;
case 'option':
break;
case node = document.createElement('option':);
node.values = documentdata.createElement( 'option' )value;
node.values =setAttribute('value', data.value);
if (data.selected) {
node.setAttribute( 'value', data.value );
if node.setAttribute('selected', data.'selected ') {;
}
node.setAttribute( 'selected', 'selected' );
if (data.disabled) {
}
if node.setAttribute('disabled', data.'disabled ') {;
}
node.setAttribute( 'disabled', 'disabled' );
node.setAttribute('label', data.label);
}
node.setAttributeappendChild(document.createTextNode( 'label', data.label ));
break;
node.appendChild( document.createTextNode( data.label ) );
case 'optgroup':
break;
case node = document.createElement('optgroup':);
node = document.createElementsetAttribute( 'optgrouplabel', data.label);
node.setAttribute( 'label', data.label );
 
if ( data.list ) {
for( (i = 0; i < data.list.length; ++i ) {
 
current = data.list[i];
current.type = 'option'; // must be options here
 
subnode = this.compute( current );
node.appendChild( subnode[0] );
}
}
} break;
case 'field':
break;
node = document.createElement('fieldset');
case 'field':
node label = node.appendChild(document.createElement( 'fieldsetlegend' ));
label = node.appendChild( document.createElementcreateTextNode( 'legend' data.label) );
if (data.name) {
label.appendChild( document.createTextNode( data.label ) );
if node.setAttribute('name', data.name ) {;
}
node.setAttribute( 'name', data.name );
if (data.disabled) {
}
if node.setAttribute('disabled', data.'disabled ') {;
}
node.setAttribute( 'disabled', 'disabled' );
} break;
case 'checkbox':
break;
case 'checkboxradio':
node = document.createElement('div');
case 'radio':
if (data.list) {
node = document.createElement( 'div' );
if for (i = 0; i < data.list.length; ++i) {
for( var icur_id = 0;id i+ <'_' data.list.length;+ ++i ) {;
var cur_id current = id + '_' + data.list[i];
current var = data.list[i]cur_div;
if (current.type === 'header') {
var cur_div;
if( current.type === 'header' ) {
// inline hack
cur_div = node.appendChild( document.createElement( 'h6' ) );
cur_div.appendChild( document.createTextNode( current.label ) );
if ( current.tooltip ) {
Morebits.quickForm.element.generateTooltip( cur_div , current );
}
continue;
}
cur_div = node.appendChild(document.createElement('div'));
continue;
subnode = cur_div.appendChild(document.createElement('input'));
}
subnode.values = current.value;
cur_div = node.appendChild( document.createElement( 'div' ) );
subnode = cur_div.appendChildsetAttribute( document.createElement( 'inputvalue', ) current.value);
subnode.values =setAttribute('name', current.valuename || data.name);
subnode.setAttribute( 'valuetype', currentdata.value type);
subnode.setAttribute( 'nameid', current.name || data.name cur_id);
subnode.setAttribute( 'type', data.type );
subnode.setAttribute( 'id', cur_id );
 
if ( current.checked ) {
subnode.setAttribute( 'checked', 'checked' );
}
if ( current.disabled ) {
subnode.setAttribute( 'disabled', 'disabled' );
}
label = cur_div.appendChild( document.createElement( 'label' ) );
label.appendChild( document.createTextNode( current.label ) );
label.setAttribute( 'for', cur_id );
if ( current.tooltip ) {
Morebits.quickForm.element.generateTooltip( label, current );
}
// styles go on the label, doesn't make sense to style a checkbox/radio
if ( current.style ) {
label.setAttribute( 'style', current.style );
}
 
var event;
if ( current.subgroup ) {
var tmpgroup = current.subgroup;
 
if ( ! Array.isArray( tmpgroup ) ) {
tmpgroup = [ tmpgroup ];
}
 
var subgroupRaw = new Morebits.quickForm.element({
type: 'div',
id: id + '_' + i + '_subgroup'
});
$.each( tmpgroup, function( idx, el ) {
var newEl = $.extend( {}, el );
if( ! newEl.type ) {
newEl.type = data.type;
}
newEl.name = (current.name || data.name) + '.' + newEl.name;
subgroupRaw.append( newEl );
} );
 
var subgroupsubgroupRaw = subgroupRawnew Morebits.renderquickForm.element( cur_id );{
type: 'div',
subgroup.className = "quickformSubgroup";
id: id + '_' + i + '_subgroup'
subnode.subgroup = subgroup;
subnode.shown = false });
$.each(tmpgroup, function(idx, el) {
var newEl = $.extend({}, el);
if (!newEl.type) {
newEl.type = data.type;
}
newEl.name = (current.name || data.name) + '.' + newEl.name;
subgroupRaw.append(newEl);
});
 
event var subgroup = functionsubgroupRaw.render(ecur_id) {;
subgroup.className = 'quickformSubgroup';
if( e.target.checked ) {
esubnode.target.parentNode.appendChild(subgroup = e.target.subgroup );
if( esubnode.target.typeshown === 'radio' ) {false;
 
event = function(e) {
if (e.target.checked) {
e.target.parentNode.appendChild(e.target.subgroup);
if (e.target.type === 'radio') {
var name = e.target.name;
if (e.target.form.names[name] !== undefined) {
e.target.form.names[name].parentNode.removeChild(e.target.form.names[name].subgroup);
}
e.target.form.names[name] = e.target;
}
} else {
e.target.parentNode.removeChild(e.target.subgroup);
}
};
subnode.addEventListener('change', event, true);
if (current.checked) {
subnode.parentNode.appendChild(subgroup);
}
} else if (data.type === 'radio') {
event = function(e) {
if (e.target.checked) {
var name = e.target.name;
if( (e.target.form.names[name] !== undefined ) {
e.target.form.names[name].parentNode.removeChild( e.target.form.names[name].subgroup );
}
delete e.target.form.names[name] = e.target;
}
} else {;
subnode.addEventListener('change', event, true);
e.target.parentNode.removeChild( e.target.subgroup );
}
// add users' event last, so it can interact with the subgroup
};
subnodeif (data.addEventListener( 'change', event,) true );{
subnode.addEventListener('change', data.event, false);
if( current.checked ) {
} else if (current.event) {
subnode.parentNode.appendChild( subgroup );
subnode.addEventListener('change', current.event, true);
}
} else if( data.type === 'radio' ) {
event = function(e) {
if( e.target.checked ) {
var name = e.target.name;
if( e.target.form.names[name] !== undefined ) {
e.target.form.names[name].parentNode.removeChild( e.target.form.names[name].subgroup );
}
delete e.target.form.names[name];
}
};
subnode.addEventListener( 'change', event, true );
}
// add users' event last, so it can interact with the subgroup
if( data.event ) {
subnode.addEventListener( 'change', data.event, false );
} else if ( current.event ) {
subnode.addEventListener( 'change', current.event, true );
}
}
} break;
case 'input':
break;
node = document.createElement('div');
case 'input':
node = document.createElementsetAttribute('id', 'divdiv_' + id);
node.setAttribute( 'id', 'div_' + id );
 
if ( data.label ) {
label = node.appendChild( document.createElement( 'label' ) );
label.appendChild( document.createTextNode( data.label ) );
label.setAttribute( 'for', id );
}
 
subnode = node.appendChild( document.createElement( 'input' ) );
if ( data.value ) {
subnode.setAttribute( 'value', data.value );
}
subnode.setAttribute( 'name', data.name );
subnode.setAttribute( 'id', id );
subnode.setAttribute( 'type', 'text' );
if ( data.size ) {
subnode.setAttribute( 'size', data.size );
}
if ( data.disabled ) {
subnode.setAttribute( 'disabled', 'disabled' );
}
if ( data.readonly ) {
subnode.setAttribute( 'readonly', 'readonly' );
}
if ( data.maxlength ) {
subnode.setAttribute( 'maxlength', data.maxlength );
}
if ( data.event ) {
subnode.addEventListener( 'keyup', data.event, false );
}
break;
case 'dyninput':
var min = data.min || 1;
var max = data.max || Infinity;
 
node = document.createElement( 'div' );
 
label = node.appendChild( document.createElement( 'h5' ) );
label.appendChild( document.createTextNode( data.label ) );
 
var listNode = node.appendChild( document.createElement( 'div' ) );
 
var more = this.compute( {
type: 'button',
label: 'more',
disabled: min >= max,
event: function(e) {
var new_node = new Morebits.quickForm.element( e.target.sublist );
e.target.area.appendChild( new_node.render() );
 
if( (++e.target.counter >= e.target.max ) {
e.target.setAttribute( 'disabled', 'disabled' );
}
e.stopPropagation();
}
} );
 
node.appendChild( more[0] );
var moreButton = more[1];
 
var sublist = {
type: '_dyninput_element',
label: data.sublabel || data.label,
name: data.name,
value: data.value,
size: data.size,
remove: false,
maxlength: data.maxlength,
event: data.event
};
 
for( (i = 0; i < min; ++i ) {
var elem = new Morebits.quickForm.element( sublist );
listNode.appendChild( elem.render() );
}
sublist.remove = true;
sublist.morebutton = moreButton;
sublist.listnode = listNode;
 
moreButton.sublist = sublist;
moreButton.area = listNode;
moreButton.max = max - min;
moreButton.counter = 0;
break;
case '_dyninput_element': // Private, similar to normal input
node = document.createElement( 'div' );
 
if ( data.label ) {
label = node.appendChild( document.createElement( 'label' ) );
label.appendChild( document.createTextNode( data.label ) );
label.setAttribute( 'for', id );
}
 
subnode = node.appendChild( document.createElement( 'input' ) );
if ( data.value ) {
subnode.setAttribute( 'value', data.value );
}
subnode.setAttribute( 'name', data.name );
subnode.setAttribute( 'type', 'text' );
if ( data.size ) {
subnode.setAttribute( 'size', data.size );
}
if ( data.maxlength ) {
subnode.setAttribute( 'maxlength', data.maxlength );
}
if ( data.event ) {
subnode.addEventListener( 'keyup', data.event, false );
}
if ( data.remove ) {
var remove = this.compute( {
type: 'button',
label: 'remove',
Line 546:
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':
node = document.createElement( 'input' );
node.setAttribute( 'type', 'hidden' );
node.values = data.value;
node.setAttribute( 'value', data.value );
node.setAttribute( 'name', data.name );
break;
case 'header':
node = document.createElement( 'h5' );
node.appendChild( document.createTextNode( data.label ) );
break;
case 'div':
node = document.createElement( 'div' );
if (data.name) {
node.setAttribute( 'name', data.name );
}
if (data.label) {
if ( ! Array.isArray( data.label ) ) {
data.label = [ data.label ];
}
break;
var result = document.createElement( 'span' );
case 'hidden':
result.className = 'quickformDescription';
node = document.createElement('input');
for( i = 0; i < data.label.length; ++i ) {
node.setAttribute('type', 'hidden');
if( typeof data.label[i] === 'string' ) {
node.values = data.value;
result.appendChild( document.createTextNode( data.label[i] ) );
node.setAttribute('value', data.value);
} else if( data.label[i] instanceof Element ) {
resultnode.appendChildsetAttribute('name', data.label[i] name);
break;
case 'header':
node = document.createElement('h5');
node.appendChild(document.createTextNode(data.label));
break;
case 'div':
node = document.createElement('div');
if (data.name) {
node.setAttribute('name', data.name);
}
if (data.label) {
if (!Array.isArray(data.label)) {
data.label = [ data.label ];
}
var result = document.createElement('span');
result.className = 'quickformDescription';
for (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);
}
break;
node.appendChild( result );
case 'submit':
}
node = document.createElement('span');
break;
childContainder = node.appendChild(document.createElement('input'));
case 'submit':
childContainder.setAttribute('type', 'submit');
node = document.createElement( 'span' );
if (data.label) {
childContainder = node.appendChild(document.createElement( 'input' ));
childContainder.setAttribute( 'typevalue', 'submit' data.label);
}
if( data.label ) {
childContainder.setAttribute( 'valuename', data.labelname || 'submit');
if (data.disabled) {
}
childContainder.setAttribute( 'namedisabled', data.name || 'submitdisabled' );
}
if( data.disabled ) {
break;
childContainder.setAttribute( 'disabled', 'disabled' );
case 'button':
}
node = document.createElement('span');
break;
childContainder = node.appendChild(document.createElement('input'));
case 'button':
childContainder.setAttribute('type', 'button');
node = document.createElement( 'span' );
if (data.label) {
childContainder = node.appendChild(document.createElement( 'input' ));
childContainder.setAttribute( 'typevalue', 'button' data.label);
}
if( data.label ) {
childContainder.setAttribute( 'valuename', data.label name);
if (data.disabled) {
}
childContainder.setAttribute( 'namedisabled', data.name 'disabled');
}
if( data.disabled ) {
if (data.event) {
childContainder.setAttribute( 'disabled', 'disabled' );
childContainder.addEventListener('click', data.event, false);
}
}
if( data.event ) {
break;
childContainder.addEventListener( 'click', data.event, false );
case 'textarea':
}
node = document.createElement('div');
break;
node.setAttribute('id', 'div_' + id);
case 'textarea':
if (data.label) {
node = document.createElement( 'div' );
label = node.appendChild(document.createElement('h5'));
node.setAttribute( 'id', 'div_' + id );
if label.appendChild(document.createTextNode( data.label ) {);
label = node.appendChild( document.createElement( 'h5' ) );
label.appendChild( document.createTextNode( data.label ) );
// TODO need to nest a <label> tag in here without creating extra vertical space
// label.setAttribute( 'for', id );
}
subnode = node.appendChild( document.createElement( 'textarea' ) );
subnode.setAttribute( 'name', data.name );
if ( data.cols ) {
subnode.setAttribute( 'cols', data.cols );
}
if ( data.rows ) {
subnode.setAttribute( 'rows', data.rows );
}
if ( data.disabled ) {
subnode.setAttribute( 'disabled', 'disabled' );
}
if ( data.readonly ) {
subnode.setAttribute( 'readonly', 'readonly' );
}
if ( data.value ) {
subnode.value = data.value;
}
break;
default:
throw new Error("'Morebits.quickForm: unknown element type "' + data.type.toString());
}
 
if ( !childContainder ) {
childContainder = node;
}
if ( data.tooltip ) {
Morebits.quickForm.element.generateTooltip( label || node , data );
}
 
if ( data.extra ) {
childContainder.extra = data.extra;
}
if ( data.style ) {
childContainder.setAttribute( 'style', data.style );
}
if ( data.className ) {
childContainder.className = ( childContainder.className ?
childContainder.className + "' "' + data.className :
data.className );
}
childContainder.setAttribute( 'id', data.id || id );
 
return [ node, childContainder ];
Line 673:
 
Morebits.quickForm.element.autoNWSW = function() {
return $(this).offset().top > ($(document).scrollTop() + ($(window).height() / 2)) ? 'sw' : 'nw';
};
 
Line 680:
* @param {Object} data
*/
Morebits.quickForm.element.generateTooltip = function QuickFormElementGenerateTooltip( node, data ) {
$('<span/>', {
'class': 'ui-icon ui-icon-help ui-icon-inline morebits-tooltip'
}).appendTo(node).tipsy({
'fallback': data.tooltip,
'fade': true,
'gravity': (data.type === "'input"' || data.type === "'select")' ?
Morebits.quickForm.element.autoNWSW : $.fn.tipsy.autoWE,
'html': true,
'delayOut': 250
});
};
 
Line 757:
Morebits.quickForm.getElementLabelObject = function QuickFormGetElementLabelObject(element) {
// for buttons, divs and headers, the label is on the element itself
if (element.type === "'button"' || element.type === "'submit"' ||
element instanceof HTMLDivElement || element instanceof HTMLHeadingElement) {
return element;
 
// for fieldsets, the label is the child <legend> element
} else if (element instanceof HTMLFieldSetElement) {
return element.getElementsByTagName("'legend"')[0];
 
// for textareas, the label is the sibling <h5> element
} else if (element instanceof HTMLTextAreaElement) {
return element.parentNode.getElementsByTagName("'h5"')[0];
}
 
// for others, the label is the sibling <label> element
return element.parentNode.getElementsByTagName('label')[0];
} else {
return element.parentNode.getElementsByTagName("label")[0];
}
};
 
Line 812 ⟶ 808:
*/
Morebits.quickForm.overrideElementLabel = function QuickFormOverrideElementLabel(element, temporaryLabelText) {
if (!element.hasAttribute("'data-oldlabel"')) {
element.setAttribute("'data-oldlabel"', Morebits.quickForm.getElementLabel(element));
}
return Morebits.quickForm.setElementLabel(element, temporaryLabelText);
Line 824 ⟶ 820:
*/
Morebits.quickForm.resetElementLabel = function QuickFormResetElementLabel(element) {
if (element.hasAttribute("'data-oldlabel"')) {
return Morebits.quickForm.setElementLabel(element, element.getAttribute("'data-oldlabel"'));
}
return null;
Line 845 ⟶ 841:
*/
Morebits.quickForm.setElementTooltipVisibility = function QuickFormSetElementTooltipVisibility(element, visibility) {
$(Morebits.quickForm.getElementContainer(element)).find("'.morebits-tooltip"').toggle(visibility);
};
 
Line 865 ⟶ 861:
* in twinkleunlink.js, which is better
*/
HTMLFormElement.prototype.getChecked = function( name, type ) {
var elements = this.elements[name];
if ( !elements ) {
// if the element doesn't exists, return null.
return null;
Line 873 ⟶ 869:
var return_array = [];
var i;
if ( elements instanceof HTMLSelectElement ) {
var options = elements.options;
for( (i = 0; i < options.length; ++i ) {
if ( options[i].selected ) {
if ( options[i].values ) {
return_array.push( options[i].values );
} else {
return_array.push( options[i].value );
}
 
}
}
} else if ( elements instanceof HTMLInputElement ) {
if ( type && elements.type !== type ) {
return [];
} else if ( elements.checked ) {
return [ elements.value ];
}
} else {
for( (i = 0; i < elements.length; ++i ) {
if ( elements[i].checked ) {
if( (type && elements[i].type !== type ) {
continue;
}
if ( elements[i].values ) {
return_array.push( elements[i].values );
} else {
return_array.push( elements[i].value );
}
}
Line 913 ⟶ 909:
*/
 
HTMLFormElement.prototype.getUnchecked = function( name, type ) {
var elements = this.elements[name];
if ( !elements ) {
// if the element doesn't exists, return null.
return null;
Line 921 ⟶ 917:
var return_array = [];
var i;
if ( elements instanceof HTMLSelectElement ) {
var options = elements.options;
for( (i = 0; i < options.length; ++i ) {
if ( !options[i].selected ) {
if ( options[i].values ) {
return_array.push( options[i].values );
} else {
return_array.push( options[i].value );
}
 
}
}
} else if ( elements instanceof HTMLInputElement ) {
if ( type && elements.type !== type ) {
return [];
} else if ( !elements.checked ) {
return [ elements.value ];
}
} else {
for( (i = 0; i < elements.length; ++i ) {
if ( !elements[i].checked ) {
if( (type && elements[i].type !== type ) {
continue;
}
if ( elements[i].values ) {
return_array.push( elements[i].values );
} else {
return_array.push( elements[i].value );
}
}
Line 965 ⟶ 961:
*/
 
RegExp.escape = function( text, space_fix ) {
text = mw.RegExp.escape(text);
 
// Special MediaWiki escape - underscore/space are often equivalent
if ( space_fix ) {
text = text.replace( / |_/g, '[_ ]' );
}
 
Line 985 ⟶ 981:
toUpperCaseFirstChar: function(str) {
str = str.toString();
return str.substr( 0, 1 ).toUpperCase() + str.substr( 1 );
},
toLowerCaseFirstChar: function(str) {
str = str.toString();
return str.substr( 0, 1 ).toLowerCase() + str.substr( 1 );
},
 
Line 1,001 ⟶ 997:
* @returns {String[]}
*/
splitWeightedByKeys: function( str, start, end, skiplist ) {
if ( start.length !== end.length ) {
throw new Error( 'start marker and end marker must be of the same length' );
}
var level = 0;
var initial = null;
var result = [];
if ( ! Array.isArray( skiplist ) ) {
if ( skiplist === undefined ) {
skiplist = [];
} else if ( typeof skiplist === 'string' ) {
skiplist = [ skiplist ];
} else {
throw new Error( "'non-applicable skiplist parameter" ');
}
}
for( (var i = 0; i < str.length; ++i ) {
for( (var j = 0; j < skiplist.length; ++j ) {
if( (str.substr( i, skiplist[j].length ) === skiplist[j] ) {
i += skiplist[j].length - 1;
continue;
}
}
if( (str.substr( i, start.length ) === start ) {
if ( initial === null ) {
initial = i;
}
++level;
i += start.length - 1;
} else if( (str.substr( i, end.length ) === end ) {
--level;
i += end.length - 1;
}
if ( !level && initial !== null ) {
result.push( str.substring( initial, i + 1 ) );
initial = null;
}
Line 1,049 ⟶ 1,045:
* @returns {string}
*/
formatReasonText: function( str ) {
var result = str.toString().trim();
var unbinder = new Morebits.unbinder(result);
unbinder.unbind("'<no"' + "'wiki>"', "'</no"' + "'wiki>"');
unbinder.content = unbinder.content.replace(/\|/g, "'{{subst:!}}"');
return unbinder.rebind();
},
Line 1,063 ⟶ 1,059:
*/
safeReplace: function morebitsStringSafeReplace(string, pattern, replacement) {
return string.replace(pattern, replacement.replace(/\$/g, "'$$$$"'));
}
};
Line 1,077 ⟶ 1,073:
*/
uniq: function(arr) {
if ( ! Array.isArray( arr ) ) {
throw "'A non-array object passed to Morebits.array.uniq"';
}
var result = [];
for( (var i = 0; i < arr.length; ++i ) {
var current = arr[i];
if ( result.indexOf( current ) === -1 ) {
result.push( current );
}
}
Line 1,095 ⟶ 1,091:
*/
dups: function(arr) {
if ( ! Array.isArray( arr ) ) {
throw "'A non-array object passed to Morebits.array.dups"';
}
var uniques = [];
var result = [];
for( (var i = 0; i < arr.length; ++i ) {
var current = arr[i];
if ( uniques.indexOf( current ) === -1 ) {
uniques.push( current );
} else {
result.push( current );
}
}
Line 1,119 ⟶ 1,115:
* @returns {Array}
*/
chunk: function( arr, size ) {
if ( ! Array.isArray( arr ) ) {
throw "'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.
}
var result = [];
var current;
for( (var i = 0; i < arr.length; ++i ) {
if ( i % size === 0 ) { // when 'i' is 0, this is always true, so we start by creating one.
current = [];
result.push( current );
}
current.push( arr[i] );
}
return result;
Line 1,163 ⟶ 1,159:
*
* eg. var u = new Morebits.unbinder("Hello world <!-- world --> world");
* u.unbind('<!--','-->');
* u.content = u.content.replace(/world/g, 'earth');
* u.rebind() ; // gives "Hello earth <!-- world --> earth"
*
* Text within the 'unbinded' part (in this case, the HTML comment) remains intact
Line 1,177 ⟶ 1,173:
* @param {string} string
*/
Morebits.unbinder = function Unbinder( string ) {
if ( typeof string !== 'string' ) {
throw new Error( "'not a string" ');
}
this.content = string;
Line 1,193 ⟶ 1,189:
* @param {string} postfix
*/
unbind: function UnbinderUnbind( prefix, postfix ) {
var re = new RegExp( prefix + '(.*?)' + postfix, 'g' );
this.content = this.content.replace( re, Morebits.unbinder.getCallback( this ) );
},
 
Line 1,204 ⟶ 1,200:
var content = this.content;
content.self = this;
for ( var current in this.history ) {
if( this(Object.historyprototype.hasOwnProperty.call(this.history, current ) ) {
content = content.replace( current, this.history[current] );
}
}
Line 1,219 ⟶ 1,215:
 
Morebits.unbinder.getCallback = function UnbinderGetCallback(self) {
return function UnbinderCallback( match ) {
var current = self.prefix + self.counter + self.postfix;
self.history[current] = match;
Line 1,238 ⟶ 1,234:
 
Date.monthNames = ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December' ];
 
Date.monthNamesAbbrev = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
 
Date.prototype.getMonthName = function() {
return Date.monthNames[ this.getMonth() ];
};
 
Date.prototype.getMonthNameAbbrev = function() {
return Date.monthNamesAbbrev[ this.getMonth() ];
};
 
Date.prototype.getUTCMonthName = function() {
return Date.monthNames[ this.getUTCMonth() ];
};
 
Date.prototype.getUTCMonthNameAbbrev = function() {
return Date.monthNamesAbbrev[ this.getUTCMonth() ];
};
 
Line 1,272 ⟶ 1,268:
*/
Morebits.wiki.isPageRedirect = function wikipediaIsPageRedirect() {
return !!(mw.config.get("'wgIsRedirect"') || document.getElementById("'softredirect"'));
};
 
Line 1,309 ⟶ 1,305:
Morebits.wiki.nbrOfCheckpointsLeft = 0;
 
Morebits.wiki.actionCompleted = function( self ) {
if( (--Morebits.wiki.numberOfActionsLeft <= 0 && Morebits.wiki.nbrOfCheckpointsLeft <= 0 ) {
Morebits.wiki.actionCompleted.event( self );
}
};
Line 1,317 ⟶ 1,313:
// Change per action wanted
Morebits.wiki.actionCompleted.event = function() {
new Morebits.status( Morebits.wiki.actionCompleted.notice, Morebits.wiki.actionCompleted.postfix, 'info' );
if ( Morebits.wiki.actionCompleted.redirect ) {
// if it isn't a URL, make it one. TODO: This breaks on the articles 'http://', 'ftp://', and similar ones.
if( (!( (/^\w+:\/\//).test( Morebits.wiki.actionCompleted.redirect ) ) ) {
Morebits.wiki.actionCompleted.redirect = mw.util.getUrl( Morebits.wiki.actionCompleted.redirect );
if ( Morebits.wiki.actionCompleted.followRedirect === false ) {
Morebits.wiki.actionCompleted.redirect += "'?redirect=no"';
}
}
window.setTimeout( function() { window.location = Morebits.wiki.actionCompleted.redirect; }, Morebits.wiki.actionCompleted.timeOut );
window.location = Morebits.wiki.actionCompleted.redirect;
}, Morebits.wiki.actionCompleted.timeOut);
}
};
 
Morebits.wiki.actionCompleted.timeOut = ( typeof window.wpActionCompletedTimeOut === 'undefined' ? 5000 : window.wpActionCompletedTimeOut );
Morebits.wiki.actionCompleted.redirect = null;
Morebits.wiki.actionCompleted.notice = 'Action';
Line 1,340 ⟶ 1,338:
 
Morebits.wiki.removeCheckpoint = function() {
if( (--Morebits.wiki.nbrOfCheckpointsLeft <= 0 && Morebits.wiki.numberOfActionsLeft <= 0 ) {
Morebits.wiki.actionCompleted.event();
}
Line 1,358 ⟶ 1,356:
* @param {Function} [onError] - The function to call if an error occurs (optional)
*/
Morebits.wiki.api = function( currentAction, query, onSuccess, statusElement, onError ) {
this.currentAction = currentAction;
this.query = query;
Line 1,365 ⟶ 1,363:
this.onSuccess = onSuccess;
this.onError = onError;
if ( statusElement ) {
this.statelem = statusElement;
this.statelem.status( currentAction );
} else {
this.statelem = new Morebits.status( currentAction );
}
};
Line 1,380 ⟶ 1,378:
query: null,
responseXML: null,
setParent: function(parent) { this.parent = parent; }, // keep track of parent object for callbacks
this.parent = parent;
}, // keep track of parent object for callbacks
statelem: null, // this non-standard name kept for backwards compatibility
statusText: null, // result received from the API, normally "success" or "error"
Line 1,391:
* really want to give jQuery some extra parameters
*/
post: function( callerAjaxParameters ) {
 
++Morebits.wiki.numberOfActionsLeft;
 
var ajaxparams = $.extend( {}, {
context: this,
type: 'POST',
Line 1,404:
'Api-User-Agent': morebitsWikiApiUserAgent
}
}, callerAjaxParameters );
 
return $.ajax( ajaxparams ).done(
function(xml, statusText) {
this.statusText = statusText;
Line 1,413:
this.errorText = $(xml).find('error').attr('info');
 
if (typeof this.errorCode === "'string"') {
 
// the API didn't like what we told it, e.g., bad edit token or an error creating a page
Line 1,425:
// set the callback context to this.parent for new code and supply the API object
// as the first argument to the callback (for legacy code)
this.onSuccess.call( this.parent, this );
} else {
this.statelem.info("'done"');
}
 
Line 1,444:
 
returnError: function() {
if ( this.errorCode === "'badtoken" ') {
this.statelem.error( "'Invalid token. Refresh the page and try again" ');
} else {
this.statelem.error( this.errorText );
}
 
Line 1,455:
// set the callback context to this.parent for new code and supply the API object
// as the first argument to the callback for legacy code
this.onError.call( this.parent, this );
}
// don't complete the action so that the error remains displayed
Line 1,485:
* @param {string} ua User agent
*/
Morebits.wiki.api.setApiUserAgent = function( ua ) {
morebitsWikiApiUserAgent = ( ua ? ua + ' ' : '' ) + 'morebits.js/2.0 ([[w:WT:TW]])';
};
 
Line 1,725:
// Need to be able to do something after the page loads
if (!onSuccess) {
ctx.statusElement.error("'Internal error: no onSuccess callback provided to load()!"');
ctx.onLoadFailure(this);
return;
Line 1,756:
}
 
ctx.loadApi = new Morebits.wiki.api("'Retrieving page..."', ctx.loadQuery, fnLoadSuccess, ctx.statusElement, ctx.onLoadFailure);
ctx.loadApi.setParent(this);
ctx.loadApi.post();
Line 1,782:
 
if (!ctx.pageLoaded && !canUseMwUserToken) {
ctx.statusElement.error("'Internal error: attempt to save a page that has not been loaded!"');
ctx.onSaveFailure(this);
return;
}
if (!ctx.editSummary) {
ctx.statusElement.error("'Internal error: edit summary not set before save!"');
ctx.onSaveFailure(this);
return;
Line 1,795:
if (ctx.fullyProtected && !ctx.suppressProtectWarning &&
!confirm('You are about to make an edit to the fully protected page "' + ctx.pageName +
(ctx.fullyProtected === 'infinity' ? '" (protected indefinitely)' : ('" (protection expiring ' + ctx.fullyProtected + ')')) +
'. \n\nClick OK to proceed with the edit, or Cancel to skip this edit.')) {
ctx.statusElement.error("'Edit to fully protected page was aborted."');
ctx.onSaveFailure(this);
return;
Line 1,829:
 
switch (ctx.editMode) {
case 'append':
query.appendtext = ctx.appendText; // use mode to append to current page contents
break;
case 'prepend':
query.prependtext = ctx.prependText; // use mode to prepend to current page contents
break;
case 'revert':
query.undo = ctx.revertCurID;
query.undoafter = ctx.revertOldID;
if (ctx.lastEditTime) {
query.basetimestamp = ctx.lastEditTime; // check that page hasn't been edited since it was loaded
}
query.starttimestamp = ctx.loadTime; // check that page hasn't been deleted since it was loaded (don't recreate bad stuff)
break;
default:
query.text = ctx.pageText; // replace entire contents of the page
if (ctx.lastEditTime) {
query.basetimestamp = ctx.lastEditTime; // check that page hasn't been edited since it was loaded
}
query.starttimestamp = ctx.loadTime; // check that page hasn't been deleted since it was loaded (don't recreate bad stuff)
break;
}
 
Line 1,860:
}
 
ctx.saveApi = new Morebits.wiki.api( "'Saving page..."', query, fnSaveSuccess, ctx.statusElement, fnSaveError);
ctx.saveApi.setParent(this);
ctx.saveApi.post();
Line 2,050:
this.setFollowRedirect = function(followRedirect) {
if (ctx.pageLoaded) {
ctx.statusElement.error("'Internal error: cannot change redirect setting after the page has been loaded!"');
return;
}
Line 2,175:
this.lookupCreation = function(onSuccess) {
if (!onSuccess) {
ctx.statusElement.error("'Internal error: no onSuccess callback provided to lookupCreation()!"');
return;
}
Line 2,193:
}
 
ctx.lookupCreationApi = new Morebits.wiki.api("'Retrieving page creation information"', query, fnLookupCreationSuccess, ctx.statusElement);
ctx.lookupCreationApi.setParent(this);
ctx.lookupCreationApi.post();
Line 2,202:
this.lookupCreator = function(onSuccess) {
console.warn("NOTE: lookupCreator() from Twinkle's Morebits has been deprecated since May/June 2019, please use lookupCreation() instead"); // eslint-disable-line no-console
Morebits.status.warn("'NOTE"', "lookupCreator() from Twinkle's Morebits has been deprecated since May/June 2019, please use lookupCreation() instead");
return this.lookupCreation(onSuccess);
};
Line 2,211:
this.patrol = function() {
// There's no patrol link on page, so we can't patrol
if ( !$( '.patrollink' ).length ) {
return;
}
 
// Extract the rcid token from the "Mark page as patrolled" link on page
var patrolhref = $( '.patrollink a' ).attr( 'href' ),
rcid = mw.util.getParamValue( 'rcid', patrolhref );
 
if ( rcid ) {
 
var patrolstat = new Morebits.status( 'Marking page as patrolled' );
 
var wikipedia_api = new Morebits.wiki.api( 'doing...', {
action: 'patrol',
rcid: rcid,
token: mw.user.tokens.get( 'patrolToken' )
}, null, patrolstat );
 
// We don't really care about the response
Line 2,244:
 
if (!ctx.revertOldID) {
ctx.statusElement.error("'Internal error: revision ID to revert to was not set before revert!"');
ctx.onSaveFailure(this);
return;
Line 2,263:
 
if (!ctx.editSummary) {
ctx.statusElement.error("'Internal error: move reason not set before move (use setEditSummary function)!"');
ctx.onMoveFailure(this);
return;
}
if (!ctx.moveDestination) {
ctx.statusElement.error("'Internal error: destination page name was not set before move!"');
ctx.onMoveFailure(this);
return;
Line 2,286:
}
 
ctx.moveApi = new Morebits.wiki.api("'retrieving move token..."', query, fnProcessMove, ctx.statusElement, ctx.onMoveFailure);
ctx.moveApi.setParent(this);
ctx.moveApi.post();
Line 2,303:
// if a non-admin tries to do this, don't bother
if (!Morebits.userIsInGroup('sysop')) {
ctx.statusElement.error("'Cannot delete page: only admins can do that"');
ctx.onDeleteFailure(this);
return;
}
if (!ctx.editSummary) {
ctx.statusElement.error("'Internal error: delete reason not set before delete (use setEditSummary function)!"');
ctx.onDeleteFailure(this);
return;
Line 2,327:
}
 
ctx.deleteApi = new Morebits.wiki.api("'retrieving delete token..."', query, fnProcessDelete, ctx.statusElement, ctx.onDeleteFailure);
ctx.deleteApi.setParent(this);
ctx.deleteApi.post();
Line 2,344:
// if a non-admin tries to do this, don't bother
if (!Morebits.userIsInGroup('sysop')) {
ctx.statusElement.error("'Cannot undelete page: only admins can do that"');
ctx.onUndeleteFailure(this);
return;
}
if (!ctx.editSummary) {
ctx.statusElement.error("'Internal error: undelete reason not set before undelete (use setEditSummary function)!"');
ctx.onUndeleteFailure(this);
return;
Line 2,365:
};
 
ctx.undeleteApi = new Morebits.wiki.api("'retrieving undelete token..."', query, fnProcessUndelete, ctx.statusElement, ctx.onUndeleteFailure);
ctx.undeleteApi.setParent(this);
ctx.undeleteApi.post();
Line 2,382:
// if a non-admin tries to do this, don't bother
if (!Morebits.userIsInGroup('sysop')) {
ctx.statusElement.error("'Cannot protect page: only admins can do that"');
ctx.onProtectFailure(this);
return;
}
if (!ctx.protectEdit && !ctx.protectMove && !ctx.protectCreate) {
ctx.statusElement.error("'Internal error: you must set edit and/or move and/or create protection before calling protect()!"');
ctx.onProtectFailure(this);
return;
}
if (!ctx.editSummary) {
ctx.statusElement.error("'Internal error: protection reason not set before protect (use setEditSummary function)!"');
ctx.onProtectFailure(this);
return;
Line 2,411:
}
 
ctx.protectApi = new Morebits.wiki.api("'retrieving protect token..."', query, fnProcessProtect, ctx.statusElement, ctx.onProtectFailure);
ctx.protectApi.setParent(this);
ctx.protectApi.post();
Line 2,425:
// if a non-admin tries to do this, don't bother
if (!Morebits.userIsInGroup('sysop')) {
ctx.statusElement.error("'Cannot apply FlaggedRevs settings: only admins can do that"');
ctx.onStabilizeFailure(this);
return;
}
if (!ctx.flaggedRevs) {
ctx.statusElement.error("'Internal error: you must set flaggedRevs before calling stabilize()!"');
ctx.onStabilizeFailure(this);
return;
}
if (!ctx.editSummary) {
ctx.statusElement.error("'Internal error: reason not set before calling stabilize() (use setEditSummary function)!"');
ctx.onStabilizeFailure(this);
return;
Line 2,450:
}
 
ctx.stabilizeApi = new Morebits.wiki.api("'retrieving stabilize token..."', query, fnProcessStabilize, ctx.statusElement, ctx.onStabilizeFailure);
ctx.stabilizeApi.setParent(this);
ctx.stabilizeApi.post();
Line 2,504:
var xml = ctx.loadApi.getXML();
 
if ( !fnCheckPageName(xml, ctx.onLoadFailure) ) {
return; // abort
}
 
ctx.pageExists = ($(xml).find('page').attr('missing') !== "")'';
if (ctx.pageExists) {
ctx.pageText = $(xml).find('rev').text();
Line 2,527:
ctx.editToken = $(xml).find('page').attr('edittoken');
if (!ctx.editToken) {
ctx.statusElement.error("'Failed to retrieve edit token."');
ctx.onLoadFailure(this);
return;
Line 2,533:
ctx.loadTime = $(xml).find('page').attr('starttimestamp');
if (!ctx.loadTime) {
ctx.statusElement.error("'Failed to retrieve start timestamp."');
ctx.onLoadFailure(this);
return;
Line 2,543:
ctx.revertCurID = $(xml).find('rev').attr('revid');
if (!ctx.revertCurID) {
ctx.statusElement.error("'Failed to retrieve current revision ID."');
ctx.onLoadFailure(this);
return;
Line 2,549:
ctx.revertUser = $(xml).find('rev').attr('user');
if (!ctx.revertUser) {
if ($(xml).find('rev').attr('userhidden') === ""'') { // username was RevDel'd or oversighted
ctx.revertUser = "'<username hidden>"';
} else {
ctx.statusElement.error("'Failed to retrieve user who made the revision."');
ctx.onLoadFailure(this);
return;
Line 2,558:
}
// set revert edit summary
ctx.editSummary = "'[[Help:Revert|Reverted]] to revision "' + ctx.revertOldID + "' by "' + ctx.revertUser + "': "' + ctx.editSummary;
}
 
Line 2,574:
 
// check for invalid titles
if ( $(xml).find('page').attr('invalid') === "" '') {
ctx.statusElement.error("'The page title is invalid: "' + ctx.pageName);
onFailure(this);
return false; // abort
Line 2,581:
 
// retrieve actual title of the page after normalization and redirects
if ( $(xml).find('page').attr('title') ) {
var resolvedName = $(xml).find('page').attr('title');
 
// only notify user for redirects, not normalization
if ( $(xml).find('redirects').length > 0 ) {
Morebits.status.info("'Info"', "'Redirected from "' + ctx.pageName + "' to "' + resolvedName );
}
ctx.pageName = resolvedName; // always update in case of normalization
} else {
else {
// could be a circular redirect or other problem
ctx.statusElement.error("'Could not resolve redirects for: "' + ctx.pageName);
onFailure(this);
 
Line 2,608 ⟶ 2,607:
 
// see if the API thinks we were successful
if ($(xml).find('edit').attr('result') === "'Success"') {
 
// real success
// default on success action - display link for edited page
var link = document.createElement('a');
link.setAttribute('href', mw.util.getUrl(ctx.pageName) );
link.appendChild(document.createTextNode(ctx.pageName));
ctx.statusElement.info(['completed (', link, ')']);
Line 2,629 ⟶ 2,628:
if (blacklist) {
var code = document.createElement('code');
code.style.fontFamily = "'monospace"';
code.appendChild(document.createTextNode(blacklist));
ctx.statusElement.error(['Could not save the page because the URL ', code, ' is on the spam blacklist.']);
} else if ( $(xml).find('captcha').length > 0 ) {
ctx.statusElement.error("'Could not save the page because the wiki server wanted you to fill out a CAPTCHA."');
} else if ( $editNode.attr('code') === 'abusefilter-disallowed' ) {
ctx.statusElement.error('The edit was disallowed by the edit filter rule "' + $editNode.attr('info').substring(17) + '".');
} else if ( $editNode.attr('info').indexOf('Hit AbuseFilter:') === 0 ) {
var div = document.createElement('div');
div.className = "'toccolours"';
div.style.fontWeight = "'normal"';
div.style.color = "'black"';
div.innerHTML = $editNode.attr('warning');
ctx.statusElement.error([ 'The following warning was returned by the edit filter: ', div, 'If you wish to proceed with the edit, please carry it out again. This warning wil not appear a second time.' ]);
Line 2,646 ⟶ 2,645:
// I can't see how to do this without creating a UI dependency on Morebits.wiki.page though -- TTO
} else {
ctx.statusElement.error("'Unknown error received from API while saving page"');
}
 
Line 2,661 ⟶ 2,660:
 
// check for edit conflict
if ( errorCode === "'editconflict"' && ctx.conflictRetries++ < ctx.maxConflictRetries ) {
 
// edit conflicts can occur when the page needs to be purged from the server cache
Line 2,669 ⟶ 2,668:
};
 
var purgeApi = new Morebits.wiki.api("'Edit conflict detected, purging server cache"', purgeQuery, null, ctx.statusElement);
purgeApi.post( { async: false } ); // just wait for it, result is for debugging
 
--Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds
 
ctx.statusElement.info("'Edit conflict detected, reapplying edit"');
if (fnCanUseMwUserToken('edit')) {
ctx.saveApi.post(); // necessarily append or prepend, so this should work as desired
Line 2,683 ⟶ 2,682:
// check for loss of edit token
// it's impractical to request a new token here, so invoke edit conflict logic when this happens
} else if ( errorCode === "'notoken"' && ctx.conflictRetries++ < ctx.maxConflictRetries ) {
 
ctx.statusElement.info("'Edit token is invalid, retrying"');
--Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds
if (fnCanUseMwUserToken('edit')) {
Line 2,694 ⟶ 2,693:
 
// check for network or server error
} else if ( errorCode === "'undefined"' && ctx.retries++ < ctx.maxRetries ) {
 
// the error might be transient, so try again
ctx.statusElement.info("'Save failed, retrying"');
--Morebits.wiki.numberOfActionsLeft; // allow for normal completion if retry succeeds
ctx.saveApi.post(); // give it another go!
Line 2,705 ⟶ 2,704:
 
// non-admin attempting to edit a protected page - this gives a friendlier message than the default
if ( errorCode === "'protectedpage" ') {
ctx.statusElement.error( "'Failed to save edit: Page is protected" ');
} else {
ctx.statusElement.error( "'Failed to save edit: "' + ctx.saveApi.getErrorText() );
}
ctx.editMode = 'all'; // cancel append/prepend/revert modes
Line 2,720 ⟶ 2,719:
var xml = ctx.lookupCreationApi.getXML();
 
if ( !fnCheckPageName(xml) ) {
return; // abort
}
Line 2,726 ⟶ 2,725:
ctx.creator = $(xml).find('rev').attr('user');
if (!ctx.creator) {
ctx.statusElement.error("'Could not find name of page creator"');
return;
}
ctx.timestamp = $(xml).find('rev').attr('timestamp');
if (!ctx.timestamp) {
ctx.statusElement.error("'Could not find timestamp of page creation"');
return;
}
Line 2,741 ⟶ 2,740:
var xml = ctx.moveApi.getXML();
 
if ($(xml).find('page').attr('missing') === ""'') {
ctx.statusElement.error("'Cannot move the page, because it no longer exists"');
ctx.onMoveFailure(this);
return;
Line 2,752 ⟶ 2,751:
if (editprot.length > 0 && editprot.attr('level') === 'sysop' && !ctx.suppressProtectWarning &&
!confirm('You are about to move the fully protected page "' + ctx.pageName +
(editprot.attr('expiry') === 'infinity' ? '" (protected indefinitely)' : ('" (protection expiring ' + editprot.attr('expiry') + ')')) +
'. \n\nClick OK to proceed with the move, or Cancel to skip this move.')) {
ctx.statusElement.error("'Move of fully protected page was aborted."');
ctx.onMoveFailure(this);
return;
Line 2,762 ⟶ 2,761:
var moveToken = $(xml).find('page').attr('movetoken');
if (!moveToken) {
ctx.statusElement.error("'Failed to retrieve move token."');
ctx.onMoveFailure(this);
return;
Line 2,787 ⟶ 2,786:
}
 
ctx.moveProcessApi = new Morebits.wiki.api("'moving page..."', query, ctx.onMoveSuccess, ctx.statusElement, ctx.onMoveFailure);
ctx.moveProcessApi.setParent(this);
ctx.moveProcessApi.post();
Line 2,801 ⟶ 2,800:
var xml = ctx.deleteApi.getXML();
 
if ($(xml).find('page').attr('missing') === ""'') {
ctx.statusElement.error("'Cannot delete the page, because it no longer exists"');
ctx.onDeleteFailure(this);
return;
Line 2,811 ⟶ 2,810:
if (editprot.length > 0 && editprot.attr('level') === 'sysop' && !ctx.suppressProtectWarning &&
!confirm('You are about to delete the fully protected page "' + ctx.pageName +
(editprot.attr('expiry') === 'infinity' ? '" (protected indefinitely)' : ('" (protection expiring ' + editprot.attr('expiry') + ')')) +
'. \n\nClick OK to proceed with the deletion, or Cancel to skip this deletion.')) {
ctx.statusElement.error("'Deletion of fully protected page was aborted."');
ctx.onDeleteFailure(this);
return;
Line 2,820 ⟶ 2,819:
token = $(xml).find('page').attr('deletetoken');
if (!token) {
ctx.statusElement.error("'Failed to retrieve delete token."');
ctx.onDeleteFailure(this);
return;
Line 2,838 ⟶ 2,837:
}
 
ctx.deleteProcessApi = new Morebits.wiki.api("'deleting page..."', query, ctx.onDeleteSuccess, ctx.statusElement, fnProcessDeleteError);
ctx.deleteProcessApi.setParent(this);
ctx.deleteProcessApi.post();
Line 2,849 ⟶ 2,848:
 
// 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!
} else if ( errorCode === "'badtoken" ') {
// this is pathetic, but given the current state of Morebits.wiki.page it would
// be a dog's breakfast to try and fix this
ctx.statusElement.error("'Invalid token. Please refresh the page and try again."');
if (ctx.onDeleteFailure) {
ctx.onDeleteFailure.call(this, this, ctx.deleteProcessApi);
}
} else if ( errorCode === "'missingtitle" ') {
ctx.statusElement.error("'Cannot delete the page, because it no longer exists"');
if (ctx.onDeleteFailure) {
ctx.onDeleteFailure.call(this, ctx.deleteProcessApi); // invoke callback
Line 2,867 ⟶ 2,866:
// hard error, give up
} else {
ctx.statusElement.error( "'Failed to delete the page: "' + ctx.deleteProcessApi.getErrorText() );
if (ctx.onDeleteFailure) {
ctx.onDeleteFailure.call(this, ctx.deleteProcessApi); // invoke callback
Line 2,890 ⟶ 2,889:
var xml = ctx.undeleteApi.getXML();
 
if ($(xml).find('page').attr('missing') !== ""'') {
ctx.statusElement.error("'Cannot undelete the page, because it already exists"');
ctx.onUndeleteFailure(this);
return;
Line 2,900 ⟶ 2,899:
if (editprot.length > 0 && editprot.attr('level') === 'sysop' && !ctx.suppressProtectWarning &&
!confirm('You are about to undelete the fully create protected page "' + ctx.pageName +
(editprot.attr('expiry') === 'infinity' ? '" (protected indefinitely)' : ('" (protection expiring ' + editprot.attr('expiry') + ')')) +
'. \n\nClick OK to proceed with the undeletion, or Cancel to skip this undeletion.')) {
ctx.statusElement.error("'Undeletion of fully create protected page was aborted."');
ctx.onUndeleteFailure(this);
return;
Line 2,922 ⟶ 2,921:
}
 
ctx.undeleteProcessApi = new Morebits.wiki.api("'undeleting page..."', query, ctx.onUndeleteSuccess, ctx.statusElement, fnProcessUndeleteError);
ctx.undeleteProcessApi.setParent(this);
ctx.undeleteProcessApi.post();
Line 2,933 ⟶ 2,932:
 
// 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.undeleteProcessApi.post(); // give it another go!
} else if ( errorCode === "'badtoken" ') {
// this is pathetic, but given the current state of Morebits.wiki.page it would
// be a dog's breakfast to try and fix this
ctx.statusElement.error("'Invalid token. Please refresh the page and try again."');
if (ctx.onUndeleteFailure) {
ctx.onUndeleteFailure.call(this, this, ctx.undeleteProcessApi);
}
} else if ( errorCode === "'cantundelete" ') {
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
Line 2,951 ⟶ 2,950:
// hard error, give up
} else {
ctx.statusElement.error( "'Failed to undelete the page: "' + ctx.undeleteProcessApi.getErrorText() );
if (ctx.onUndeleteFailure) {
ctx.onUndeleteFailure.call(this, ctx.undeleteProcessApi); // invoke callback
Line 2,961 ⟶ 2,960:
var xml = ctx.protectApi.getXML();
 
var missing = ($(xml).find('page').attr('missing') === "")'';
if (((ctx.protectEdit || ctx.protectMove) && missing)) {
ctx.statusElement.error("'Cannot protect the page, because it no longer exists"');
ctx.onProtectFailure(this);
return;
}
if (ctx.protectCreate && !missing) {
ctx.statusElement.error("'Cannot create protect the page, because it already exists"');
ctx.onProtectFailure(this);
return;
Line 2,977 ⟶ 2,976:
var protectToken = $(xml).find('page').attr('protecttoken');
if (!protectToken) {
ctx.statusElement.error("'Failed to retrieve protect token."');
ctx.onProtectFailure(this);
return;
Line 2,995 ⟶ 2,994:
expirys.push(ctx.protectEdit.expiry);
} else if (editprot.length) {
protections.push('edit=' + editprot.attr("'level"'));
expirys.push(editprot.attr("'expiry"').replace("'infinity"', "'indefinite"'));
}
 
Line 3,003 ⟶ 3,002:
expirys.push(ctx.protectMove.expiry);
} else if (moveprot.length) {
protections.push('move=' + moveprot.attr("'level"'));
expirys.push(moveprot.attr("'expiry"').replace("'infinity"', "'indefinite"'));
}
 
Line 3,011 ⟶ 3,010:
expirys.push(ctx.protectCreate.expiry);
} else if (createprot.length) {
protections.push('create=' + createprot.attr("'level"'));
expirys.push(createprot.attr("'expiry"').replace("'infinity"', "'indefinite"'));
}
 
Line 3,030 ⟶ 3,029:
}
 
ctx.protectProcessApi = new Morebits.wiki.api("'protecting page..."', query, ctx.onProtectSuccess, ctx.statusElement, ctx.onProtectFailure);
ctx.protectProcessApi.setParent(this);
ctx.protectProcessApi.post();
Line 3,038 ⟶ 3,037:
var xml = ctx.stabilizeApi.getXML();
 
var missing = ($(xml).find('page').attr('missing') === "")'';
if (missing) {
ctx.statusElement.error("'Cannot protect the page, because it no longer exists"');
ctx.onStabilizeFailure(this);
return;
Line 3,047 ⟶ 3,046:
var stabilizeToken = $(xml).find('page').attr('edittoken');
if (!stabilizeToken) {
ctx.statusElement.error("'Failed to retrieve stabilize token."');
ctx.onStabilizeFailure(this);
return;
Line 3,064 ⟶ 3,063:
}
 
ctx.stabilizeProcessApi = new Morebits.wiki.api("'configuring stabilization settings..."', query, ctx.onStabilizeSuccess, ctx.statusElement, ctx.onStabilizeFailure);
ctx.stabilizeProcessApi.setParent(this);
ctx.stabilizeProcessApi.post();
Line 3,096 ⟶ 3,095:
Morebits.wiki.preview = function(previewbox) {
this.previewbox = previewbox;
$(previewbox).addClass("'morebits-previewbox"').hide();
 
/**
Line 3,118 ⟶ 3,117:
title: pageTitle || mw.config.get('wgPageName')
};
var renderApi = new Morebits.wiki.api("'loading..."', query, fnRenderSuccess, new Morebits.status("'Preview"'));
renderApi.post();
};
Line 3,126 ⟶ 3,125:
var html = $(xml).find('text').text();
if (!html) {
apiobj.statelem.error("'failed to retrieve preview, or template was blanked"');
return;
}
previewbox.innerHTML = html;
$(previewbox).find("'a"').attr("'target"', "'_blank"'); // this makes links open in new tab
};
 
Line 3,151 ⟶ 3,150:
 
Morebits.wikitext.template = {
parse: function( text, start ) {
var count = -1;
var level = -1;
Line 3,162 ⟶ 3,161:
var key, value;
 
for( (var i = start; i < text.length; ++i ) {
var test3 = text.substr( i, 3 );
if ( test3 === '{{{' ) {
current += '{{{';
i += 2;
Line 3,170 ⟶ 3,169:
continue;
}
if ( test3 === '}}}' ) {
current += '}}}';
i += 2;
Line 3,176 ⟶ 3,175:
continue;
}
var test2 = text.substr( i, 2 );
if( (test2 === '{{' || test2 === '[[' ) {
current += test2;
++i;
Line 3,183 ⟶ 3,182:
continue;
}
if ( test2 === ']]' ) {
current += ']]';
++i;
Line 3,189 ⟶ 3,188:
continue;
}
if ( test2 === '}}' ) {
current += test2;
++i;
--level;
 
if ( level <= 0 ) {
if ( count === -1 ) {
result.name = current.substring(2).trim();
++count;
} else {
if ( equals !== -1 ) {
key = current.substring( 0, equals ).trim();
value = current.substring( equals ).trim();
result.parameters[key] = value;
equals = -1;
Line 3,214 ⟶ 3,213:
}
 
if( (text.charAt(i) === '|' && level <= 0 ) {
if ( count === -1 ) {
result.name = current.substring(2).trim();
++count;
} else {
if ( equals !== -1 ) {
key = current.substring( 0, equals ).trim();
value = current.substring( equals + 1 ).trim();
result.parameters[key] = value;
equals = -1;
Line 3,230 ⟶ 3,229:
}
current = '';
} else if( (equals === -1 && text.charAt(i) === '=' && level <= 0 ) {
equals = current.length;
current += text.charAt(i);
Line 3,246 ⟶ 3,245:
* @param {string} text
*/
Morebits.wikitext.page = function mediawikiPage( text ) {
this.text = text;
};
Line 3,257 ⟶ 3,256:
* @param {string} link_target
*/
removeLink: function( link_target ) {
var first_char = link_target.substr( 0, 1 );
var link_re_string = "'["' + first_char.toUpperCase() + first_char.toLowerCase() + ']' + RegExp.escape( link_target.substr( 1 ), true );
 
// Files and Categories become links with a leading colon.
// e.g. [[:File:Test.png]]
var special_ns_re = /^(?:[Ff]ile|[Ii]mage|[Cc]ategory):/;
var colon = special_ns_re.test( link_target ) ? ':' : '';
 
var link_simple_re = new RegExp( "'\\[\\["' + colon + "'("' + link_re_string + "')\\]\\]"', 'g' );
var link_named_re = new RegExp( "'\\[\\["' + colon + link_re_string + "'\\|(.+?)\\]\\]"', 'g' );
this.text = this.text.replace( link_simple_re, "'$1" ').replace( link_named_re, "'$1" ');
},
 
Line 3,277 ⟶ 3,276:
* @param {string} reason - Reason to be included in comment, alongside the commented-out image
*/
commentOutImage: function( image, reason ) {
var unbinder = new Morebits.unbinder( this.text );
unbinder.unbind( '<!--', '-->' );
 
reason = reason ? (reason + ': ') : '';
var first_char = image.substr( 0, 1 );
var image_re_string = "'["' + first_char.toUpperCase() + first_char.toLowerCase() + ']' + RegExp.escape( image.substr( 1 ), true );
 
// Check for normal image links, i.e. [[File:Foobar.png|...]]
// Will eat the whole link
var links_re = new RegExp( "'\\[\\[(?:[Ii]mage|[Ff]ile):\\s*"' + image_re_string );
var allLinks = Morebits.array.uniq(Morebits.string.splitWeightedByKeys( unbinder.content, '[[', ']]' ));
for( (var i = 0; i < allLinks.length; ++i ) {
if ( links_re.test( allLinks[i] ) ) {
var replacement = '<!-- ' + reason + allLinks[i] + ' -->';
unbinder.content = unbinder.content.replace( allLinks[i], replacement, 'g' );
}
}
// 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.
var gallery_image_re = new RegExp( "'(^\\s*(?:[Ii]mage|[Ff]ile):\\s*"' + image_re_string + "'.*?$)"', 'mg' );
unbinder.content = unbinder.content.replace( gallery_image_re, "'<!-- "' + reason + "'$1 -->" ');
 
// unbind the newly created comments
unbinder.unbind( '<!--', '-->' );
 
// Check free image usages, for example as template arguments, might have the File: prefix excluded, but must be preceeded by an |
// Will only eat the image name and the preceeding bar and an eventual named parameter
var free_image_re = new RegExp( "'(\\|\\s*(?:[\\w\\s]+\\=)?\\s*(?:(?:[Ii]mage|[Ff]ile):\\s*)?"' + image_re_string + "')"', 'mg' );
unbinder.content = unbinder.content.replace( free_image_re, "'<!-- "' + reason + "'$1 -->" ');
// Rebind the content now, we are done!
this.text = unbinder.rebind();
Line 3,320 ⟶ 3,319:
* @param {string} data
*/
addToImageComment: function( image, data ) {
var first_char = image.substr( 0, 1 );
var first_char_regex = RegExp.escape( first_char, true );
if( (first_char.toUpperCase() !== first_char.toLowerCase() ) {
first_char_regex = '[' + RegExp.escape( first_char.toUpperCase(), true ) + RegExp.escape( first_char.toLowerCase(), true ) + ']';
}
var image_re_string = "'(?:[Ii]mage|[Ff]ile):\\s*"' + first_char_regex + RegExp.escape( image.substr( 1 ), true );
var links_re = new RegExp( "'\\[\\["' + image_re_string );
var allLinks = Morebits.array.uniq(Morebits.string.splitWeightedByKeys( this.text, '[[', ']]' ));
for( (var i = 0; i < allLinks.length; ++i ) {
if ( links_re.test( allLinks[i] ) ) {
var replacement = allLinks[i];
// just put it at the end?
replacement = replacement.replace( /\]\]$/, '|' + data + ']]' );
this.text = this.text.replace( allLinks[i], replacement, 'g' );
}
}
var gallery_re = new RegExp( "'^(\\s*"' + image_re_string + '.*?)\\|?(.*?)$', 'mg' );
var newtext = "'$1|$2 "' + data;
this.text = this.text.replace( gallery_re, newtext );
},
 
Line 3,347 ⟶ 3,346:
* include namespace prefix only if not in template namespace
*/
removeTemplate: function( template ) {
var first_char = template.substr( 0, 1 );
var template_re_string = "'(?:[Tt]emplate:)?\\s*["' + first_char.toUpperCase() + first_char.toLowerCase() + ']' + RegExp.escape( template.substr( 1 ), true );
var links_re = new RegExp( "'\\{\\{"' + template_re_string );
var allTemplates = Morebits.array.uniq(Morebits.string.splitWeightedByKeys( this.text, '{{', '}}', [ '{{{', '}}}' ] ));
for( (var i = 0; i < allTemplates.length; ++i ) {
if ( links_re.test( allTemplates[i] ) ) {
this.text = this.text.replace( allTemplates[i], '', 'g' );
}
}
Line 3,388 ⟶ 3,387:
this.params = {};
 
if ( !qString.length ) {
return;
}
Line 3,395 ⟶ 3,394:
var args = qString.split('&');
 
for( (var i = 0; i < args.length; ++i ) {
var pair = args[i].split( '=' );
var key = decodeURIComponent( pair[0] ), value = key;
 
if ( pair.length === 2 ) {
value = decodeURIComponent( pair[1] );
}
 
Line 3,410 ⟶ 3,409:
 
Morebits.queryString.staticInit = function() {
if ( !Morebits.queryString.staticstr ) {
Morebits.queryString.staticstr = new Morebits.queryString(location.search.substring(1));
}
Line 3,435 ⟶ 3,434:
};
 
Morebits.queryString.create = function( arr ) {
var resarr = [];
var editToken; // KLUGE: this should always be the last item in the query string (bug TW-B-0013)
for ( var i in arr ) {
if ( arr[i] === undefined ) {
continue;
}
var res;
if ( Array.isArray( arr[i] )) ){
var v = [];
for (var j = 0; j < arr[i].length; ++j ) {
v[j] = encodeURIComponent( arr[i][j] );
}
res = v.join('|');
} else {
res = encodeURIComponent( arr[i] );
}
if ( i === 'token' ) {
editToken = res;
} else {
resarr.push( encodeURIComponent( i ) + '=' + res );
}
}
if ( editToken !== undefined ) {
resarr.push( 'token=' + editToken );
}
return resarr.join('&');
Line 3,509 ⟶ 3,508:
*/
 
/**
* @constructor
* Morebits.status.init() must be called before any status object is created, otherwise
Line 3,520 ⟶ 3,519:
*/
 
Morebits.status = function Status( text, stat, type ) {
this.textRaw = text;
this.text = this.codify(text);
this.type = type || 'status';
this.generate();
if ( stat ) {
this.update( stat, type );
}
};
Line 3,534 ⟶ 3,533:
* @param {HTMLElement} root - usually a div element
*/
Morebits.status.init = function( root ) {
if ( !( root instanceof Element ) ) {
throw new Error( 'object not an instance of Element' );
}
while ( root.hasChildNodes() ) {
root.removeChild( root.firstChild );
}
Morebits.status.root = root;
Line 3,547 ⟶ 3,546:
Morebits.status.root = null;
 
Morebits.status.onError = function( handler ) {
if ( typeof handler === 'function' ) {
Morebits.status.errorEvent = handler;
} else {
throw "'Morebits.status.onError: handler is not a function"';
}
};
Line 3,568 ⟶ 3,567:
*/
link: function() {
if ( ! this.linked && Morebits.status.root ) {
Morebits.status.root.appendChild( this.node );
this.linked = true;
}
Line 3,578 ⟶ 3,577:
*/
unlink: function() {
if ( this.linked ) {
Morebits.status.root.removeChild( this.node );
this.linked = false;
}
Line 3,587 ⟶ 3,586:
* Create a document fragment with the status text
*/
codify: function( obj ) {
if ( ! Array.isArray( obj ) ) {
obj = [ obj ];
}
var result;
result = document.createDocumentFragment();
for( (var i = 0; i < obj.length; ++i ) {
if ( typeof obj[i] === 'string' ) {
result.appendChild( document.createTextNode( obj[i] ) );
} else if ( obj[i] instanceof Element ) {
result.appendChild( obj[i] );
} // Else cosmic radiation made something shit
}
Line 3,609 ⟶ 3,608:
* @param {String} type - 'status' (blue), 'info' (green), 'warn' (red), or 'error' (bold red)
*/
update: function( status, type ) {
this.stat = this.codify( status );
if ( type ) {
this.type = type;
if (type === 'error') {
Line 3,623 ⟶ 3,622:
 
// also log error messages in the browser console
console.error(this.textRaw + "': "' + status); // eslint-disable-line no-console
}
}
Line 3,633 ⟶ 3,632:
*/
generate: function() {
this.node = document.createElement( 'div' );
this.node.appendChild( document.createElement('span') ).appendChild( this.text );
this.node.appendChild( document.createElement('span') ).appendChild( document.createTextNode( ': ' ) );
this.target = this.node.appendChild( document.createElement( 'span' ) );
this.target.appendChild( document.createTextNode( '' ) ); // dummy node
},
 
Line 3,645 ⟶ 3,644:
render: function() {
this.node.className = 'tw_status_' + this.type;
while ( this.target.hasChildNodes() ) {
this.target.removeChild( this.target.firstChild );
}
this.target.appendChild( this.stat );
this.link();
},
status: function( status ) {
this.update( status, 'status');
},
info: function( status ) {
this.update( status, 'info');
},
warn: function( status ) {
this.update( status, 'warn');
},
error: function( status ) {
this.update( status, 'error');
}
};
 
Morebits.status.info = function( text, status ) {
return new Morebits.status( text, status, 'info' );
};
 
Morebits.status.warn = function( text, status ) {
return new Morebits.status( text, status, 'warn' );
};
 
Morebits.status.error = function( text, status ) {
return new Morebits.status( text, status, 'error' );
};
 
Line 3,683 ⟶ 3,682:
* @param {string} message
*/
Morebits.status.printUserText = function( comments, message ) {
var p = document.createElement( 'p' );
p.textContent = message;
var div = document.createElement( 'div' );
div.className = 'toccolours';
div.style.marginTop = '0';
div.style.whiteSpace = 'pre-wrap';
div.textContent = comments;
p.appendChild( div );
Morebits.status.root.appendChild( p );
};
 
Line 3,702 ⟶ 3,701:
*/
 
Morebits.htmlNode = function ( type, content, color ) {
var node = document.createElement( type );
if ( color ) {
node.style.color = color;
}
node.appendChild( document.createTextNode( content ) );
return node;
};
Line 3,726 ⟶ 3,725:
var thisCb = this;
if (event.shiftKey && lastCheckbox !== null) {
var cbs = $(jQuerySelector, jQueryContext); // can't cache them, obviously, if we want to support resorting
var index = -1, lastIndex = -1, i;
for (i = 0; i < cbs.length; i++) {
if (cbs[i] === thisCb) {
index = i;
if (lastIndex > -1) {
break;
}
}
if (cbs[i] === lastCheckbox) {
lastIndex = i;
if (index > -1) {
break;
}
}
}
 
if (index > -1 && lastIndex > -1) {
// inspired by wikibits
var endState = thisCb.checked;
var start, finish;
Line 3,816 ⟶ 3,817:
 
// internal counters, etc.
statusElement: new Morebits.status(currentAction || "'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
countStarted: 0,
countFinished: 0,
Line 3,843 ⟶ 3,844:
* Sets a known option:
* - chunkSize (integer):
* The size of chunks to break the array into (default 50).
* Setting this to a small value (<5) can cause problems.
* - preserveIndividualStatusLines (boolean):
* Keep each page's status element visible when worker is complete?
*/
this.setOption = function(optionName, optionValue) {
Line 3,861 ⟶ 3,862:
this.run = function(worker, postFinish) {
if (ctx.running) {
ctx.statusElement.error("'Batch operation is already running"');
return;
}
Line 3,876 ⟶ 3,877:
var total = ctx.pageList.length;
if (!total) {
ctx.statusElement.info("'nothing to do"');
ctx.running = false;
return;
Line 3,886 ⟶ 3,887:
// start the process
Morebits.wiki.addCheckpoint();
ctx.statusElement.status("'0%"');
fnStartNewChunk();
};
Line 3,898 ⟶ 3,899:
// we know the page title - display a relevant message
var pageName = apiobj.getPageName ? apiobj.getPageName() :
(apiobj.pageName || apiobj.query.title);
var link = document.createElement('a');
link.setAttribute('href', mw.util.getUrl(pageName));
Line 3,944 ⟶ 3,945:
var total = ctx.pageList.length;
if (ctx.countFinished === total) {
var statusString = "'Done ("' + ctx.countFinishedSuccess +
"'/"' + ctx.countFinished + "' actions completed successfully)"';
if (ctx.countFinishedSuccess < ctx.countFinished) {
ctx.statusElement.warn(statusString);
Line 3,961 ⟶ 3,962:
// just for giggles! (well, serious debugging, actually)
if (ctx.countFinished > total) {
ctx.statusElement.warn("'Done (overshot by "' + (ctx.countFinished - total) + "')"');
Morebits.wiki.removeCheckpoint();
ctx.running = false;
Line 3,967 ⟶ 3,968:
}
 
ctx.statusElement.status(parseInt(100 * ctx.countFinished / total, 10) + "'%"');
 
// start a new chunk if we're close enough to the end of the previous chunk, and
Line 3,991 ⟶ 3,992:
* @param {number} height The maximum allowable height for the content area.
*/
Morebits.simpleWindow = function SimpleWindow( width, height ) {
var content = document.createElement( 'div' );
this.content = content;
content.className = 'morebits-dialog-content';
Line 4,001 ⟶ 4,002:
$(this.content).dialog({
autoOpen: false,
buttons: { "'Placeholder button"': function() {} },
dialogClass: 'morebits-dialog',
width: Math.min(parseInt(window.innerWidth, 10), parseInt(width ? width : 800, 10)),
Line 4,011 ⟶ 4,012:
close: function(event) {
// dialogs and their content can be destroyed once closed
$(event.target).dialog("'destroy"').remove();
},
resizeStart: function() {
this.scrollbox = $(this).find("'.morebits-scrollbox"')[0];
if (this.scrollbox) {
this.scrollbox.style.maxHeight = "'none"';
}
},
Line 4,023 ⟶ 4,024:
},
resize: function() {
this.style.maxHeight = ""'';
if (this.scrollbox) {
this.scrollbox.style.width = ""'';
}
}
});
 
var $widget = $(this.content).dialog("'widget"');
 
// add background gradient to titlebar
var $titlebar = $widget.find("'.ui-dialog-titlebar"');
var oldstyle = $titlebar.attr("'style"');
$titlebar.attr("'style"', (oldstyle ? oldstyle : ""'') + '; background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAkCAMAAAB%2FqqA%2BAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAEhQTFRFr73ZobTPusjdsMHZp7nVwtDhzNbnwM3fu8jdq7vUt8nbxtDkw9DhpbfSvMrfssPZqLvVztbno7bRrr7W1d%2Fs1N7qydXk0NjpkW7Q%2BgAAADVJREFUeNoMwgESQCAAAMGLkEIi%2FP%2BnbnbpdB59app5Vdg0sXAoMZCpGoFbK6ciuy6FX4ABAEyoAef0BXOXAAAAAElFTkSuQmCC) !important;');
 
// 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)
var buttonspan = document.createElement("'span"');
buttonspan.className = "'morebits-dialog-buttons"';
var linksspan = document.createElement("'span"');
linksspan.className = "'morebits-dialog-footerlinks"';
$widget.find("'.ui-dialog-buttonpane"').append(buttonspan, linksspan);
 
// resize the scrollbox with the dialog, if one is present
$widget.resizable("'option"', "'alsoResize"', "'#"' + this.content.id + "' .morebits-scrollbox, #"' + this.content.id);
};
 
Line 4,064 ⟶ 4,065:
*/
focus: function() {
$(this.content).dialog("'moveToTop"');
return this;
},
Line 4,077 ⟶ 4,078:
event.preventDefault();
}
$(this.content).dialog("'close"');
return this;
},
Line 4,088 ⟶ 4,089:
display: function() {
if (this.scriptName) {
var $widget = $(this.content).dialog("'widget"');
$widget.find("'.morebits-dialog-scriptname"').remove();
var 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);
}
 
var 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 4,110 ⟶ 4,111:
* @returns {Morebits.simpleWindow}
*/
setTitle: function( title ) {
$(this.content).dialog("'option"', "'title"', title);
return this;
},
Line 4,121 ⟶ 4,122:
* @returns {Morebits.simpleWindow}
*/
setScriptName: function( name ) {
this.scriptName = name;
return this;
Line 4,131 ⟶ 4,132:
* @returns {Morebits.simpleWindow}
*/
setWidth: function( width ) {
$(this.content).dialog("'option"', "'width"', width);
return this;
},
Line 4,142 ⟶ 4,143:
* @returns {Morebits.simpleWindow}
*/
setHeight: function( height ) {
this.height = height;
 
Line 4,150 ⟶ 4,151:
// chrome has in height in addition to the height of an equivalent "classic"
// Morebits.simpleWindow
if (parseInt(getComputedStyle($(this.content).dialog("'widget"')[0], null).height, 10) > window.innerHeight) {
$(this.content).dialog("'option"', "'height"', window.innerHeight - 2).dialog("'option"', "'position"', "'top"');
} else {
$(this.content).dialog("'option"', "'height"', "'auto"');
}
$(this.content).dialog("'widget"').find("'.morebits-dialog-content"')[0].style.maxHeight = parseInt(this.height - 30, 10) + "'px"';
return this;
},
Line 4,167 ⟶ 4,168:
* @returns {Morebits.simpleWindow}
*/
setContent: function( content ) {
this.purgeContent();
this.addContent( content );
return this;
},
Line 4,178 ⟶ 4,179:
* @returns {Morebits.simpleWindow}
*/
addContent: function( content ) {
this.content.appendChild( content );
 
// look for submit buttons in the content, hide them, and add a proxy button to the button pane
var thisproxy = this;
$(this.content).find('input[type="submit"], button[type="submit"]').each(function(key, value) {
value.style.display = "'none"';
var button = document.createElement("'button"');
button.textContent = (value.hasAttribute("'value"') ? value.getAttribute("'value"') : (value.textContent ? value.textContent : "'Submit Query"))';
// here is an instance of cheap coding, probably a memory-usage hit in using a closure here
button.addEventListener("'click"', function() { value.click(); }, false);
value.click();
}, false);
thisproxy.buttons.push(button);
});
// remove all buttons from the button pane and re-add them
if (this.buttons.length > 0) {
$(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 4,207 ⟶ 4,210:
this.buttons = [];
// delete all buttons in the buttonpane
$(this.content).dialog("'widget"').find("'.morebits-dialog-buttons"').empty();
 
while ( this.content.hasChildNodes() ) {
this.content.removeChild( this.content.firstChild );
}
return this;
Line 4,220 ⟶ 4,223:
* For example, Twinkle's CSD module adds a link to the CSD policy page,
* as well as a link to Twinkle's documentation.
* @param {string} text Link's text content
* @param {string} wikiPage Link target
* @returns {Morebits.simpleWindow}
*/
addFooterLink: function( text, wikiPage ) {
var $footerlinks = $(this.content).dialog("'widget"').find("'.morebits-dialog-footerlinks"');
if (this.hasFooterLinks) {
var bullet = document.createElement("'span"');
bullet.textContent = "' \u2022 "'; // U+2022 BULLET
$footerlinks.append(bullet);
}
var link = document.createElement("'a"');
link.setAttribute("'href"', mw.util.getUrl(wikiPage) );
link.setAttribute("'title"', wikiPage);
link.setAttribute("'target"', "'_blank"');
link.textContent = text;
$footerlinks.append(link);
Line 4,251 ⟶ 4,254:
* @returns {Morebits.simpleWindow}
*/
setModality: function( modal ) {
$(this.content).dialog("'option"', "'modal"', modal);
return this;
}
Line 4,266 ⟶ 4,269:
* @param {boolean} enabled
*/
Morebits.simpleWindow.setButtonsEnabled = function( enabled ) {
$("'.morebits-dialog-buttons button"').prop("'disabled"', !enabled);
};
 
Line 4,275 ⟶ 4,278:
 
 
} ( window, document, jQuery )); // End wrap with anonymous function
 
 
Line 4,287 ⟶ 4,290:
*/
 
if ( typeof arguments === "'undefined" ') { // typeof is here for a reason...
/* global Morebits */
window.SimpleWindow = Morebits.simpleWindow;
Line 4,296 ⟶ 4,299:
}
 
// </nowiki>
Anonymous user