Merge "selenium: invoke jobs to enforce eventual consistency"
[lhc/web/wiklou.git] / resources / src / jquery.tablesorter / jquery.tablesorter.js
1 /*!
2 * TableSorter for MediaWiki
3 *
4 * Written 2011 Leo Koppelkamm
5 * Based on tablesorter.com plugin, written (c) 2007 Christian Bach.
6 *
7 * Dual licensed under the MIT and GPL licenses:
8 * http://www.opensource.org/licenses/mit-license.php
9 * http://www.gnu.org/licenses/gpl.html
10 *
11 * Depends on mw.config (wgDigitTransformTable, wgDefaultDateFormat, wgPageContentLanguage)
12 * and mw.language.months.
13 *
14 * Uses 'tableSorterCollation' in mw.config (if available)
15 *
16 * Create a sortable table with multi-column sorting capabilities
17 *
18 * // Create a simple tablesorter interface
19 * $( 'table' ).tablesorter();
20 *
21 * // Create a tablesorter interface, initially sorting on the first and second column
22 * $( 'table' ).tablesorter( { sortList: [ { 0: 'desc' }, { 1: 'asc' } ] } );
23 *
24 * @param {string} [cssHeader="header"] A string of the class name to be appended to sortable
25 * tr elements in the thead of the table.
26 *
27 * @param {string} [cssAsc="headerSortUp"] A string of the class name to be appended to
28 * sortable tr elements in the thead on a ascending sort.
29 *
30 * @param {string} [cssDesc="headerSortDown"] A string of the class name to be appended to
31 * sortable tr elements in the thead on a descending sort.
32 *
33 * @param {string} [sortMultisortKey="shiftKey"] A string of the multi-column sort key.
34 *
35 * @param {boolean} [cancelSelection=true] Boolean flag indicating iftablesorter should cancel
36 * selection of the table headers text.
37 *
38 * @param {Array} [sortList] An array containing objects specifying sorting. By passing more
39 * than one object, multi-sorting will be applied. Object structure:
40 * { <Integer column index>: <String 'asc' or 'desc'> }
41 *
42 * @event sortEnd.tablesorter: Triggered as soon as any sorting has been applied.
43 *
44 * @author Christian Bach/christian.bach@polyester.se
45 */
46 ( function () {
47 var ts,
48 parsers = [];
49
50 /* Parser utility functions */
51
52 function getParserById( name ) {
53 var i;
54 for ( i = 0; i < parsers.length; i++ ) {
55 if ( parsers[ i ].id.toLowerCase() === name.toLowerCase() ) {
56 return parsers[ i ];
57 }
58 }
59 return false;
60 }
61
62 function getElementSortKey( node ) {
63 var $node = $( node ),
64 // Use data-sort-value attribute.
65 // Use data() instead of attr() so that live value changes
66 // are processed as well (T40152).
67 data = $node.data( 'sortValue' );
68
69 if ( data !== null && data !== undefined ) {
70 // Cast any numbers or other stuff to a string, methods
71 // like charAt, toLowerCase and split are expected.
72 return String( data );
73 }
74 if ( !node ) {
75 return $node.text();
76 }
77 if ( node.tagName.toLowerCase() === 'img' ) {
78 return $node.attr( 'alt' ) || ''; // handle undefined alt
79 }
80 return $.makeArray( node.childNodes ).map( function ( elem ) {
81 if ( elem.nodeType === Node.ELEMENT_NODE ) {
82 if ( $( elem ).hasClass( 'reference' ) ) {
83 return null;
84 } else {
85 return getElementSortKey( elem );
86 }
87 }
88 return $.text( elem );
89 } ).join( '' );
90 }
91
92 function detectParserForColumn( table, rows, column ) {
93 var l = parsers.length,
94 config = $( table ).data( 'tablesorter' ).config,
95 cellIndex,
96 nodeValue,
97 nextRow = false,
98 // Start with 1 because 0 is the fallback parser
99 i = 1,
100 lastRowIndex = -1,
101 rowIndex = 0,
102 concurrent = 0,
103 empty = 0,
104 needed = ( rows.length > 4 ) ? 5 : rows.length;
105
106 while ( i < l ) {
107 // if this is a child row, continue to the next row (as buildCache())
108 if ( rows[ rowIndex ] && !$( rows[ rowIndex ] ).hasClass( config.cssChildRow ) ) {
109 if ( rowIndex !== lastRowIndex ) {
110 lastRowIndex = rowIndex;
111 cellIndex = $( rows[ rowIndex ] ).data( 'columnToCell' )[ column ];
112 nodeValue = getElementSortKey( rows[ rowIndex ].cells[ cellIndex ] ).trim();
113 }
114 } else {
115 nodeValue = '';
116 }
117
118 if ( nodeValue !== '' ) {
119 if ( parsers[ i ].is( nodeValue, table ) ) {
120 concurrent++;
121 nextRow = true;
122 if ( concurrent >= needed ) {
123 // Confirmed the parser for multiple cells, let's return it
124 return parsers[ i ];
125 }
126 } else if ( parsers[ i ].id.match( /isoDate/ ) && /^\D*(\d{1,4}) ?(\[.+\])?$/.test( nodeValue ) ) {
127 // For 1-4 digits and maybe reference(s) parser "isoDate" or "number" is possible, check next row
128 empty++;
129 nextRow = true;
130 } else {
131 // Check next parser, reset rows
132 i++;
133 rowIndex = 0;
134 concurrent = 0;
135 empty = 0;
136 nextRow = false;
137 }
138 } else {
139 // Empty cell
140 empty++;
141 nextRow = true;
142 }
143
144 if ( nextRow ) {
145 nextRow = false;
146 rowIndex++;
147 if ( rowIndex >= rows.length ) {
148 if ( concurrent > 0 && concurrent >= rows.length - empty ) {
149 // Confirmed the parser for all filled cells
150 return parsers[ i ];
151 }
152 // Check next parser, reset rows
153 i++;
154 rowIndex = 0;
155 concurrent = 0;
156 empty = 0;
157 }
158 }
159 }
160
161 // 0 is always the generic parser (text)
162 return parsers[ 0 ];
163 }
164
165 function buildParserCache( table, $headers ) {
166 var sortType, len, j, parser,
167 rows = table.tBodies[ 0 ].rows,
168 config = $( table ).data( 'tablesorter' ).config,
169 parsers = [];
170
171 if ( rows[ 0 ] ) {
172 len = config.columns;
173 for ( j = 0; j < len; j++ ) {
174 parser = false;
175 sortType = $headers.eq( config.columnToHeader[ j ] ).data( 'sortType' );
176 if ( sortType !== undefined ) {
177 parser = getParserById( sortType );
178 }
179
180 if ( parser === false ) {
181 parser = detectParserForColumn( table, rows, j );
182 }
183
184 parsers.push( parser );
185 }
186 }
187 return parsers;
188 }
189
190 /* Other utility functions */
191
192 function buildCache( table ) {
193 var i, j, $row, cols,
194 totalRows = ( table.tBodies[ 0 ] && table.tBodies[ 0 ].rows.length ) || 0,
195 config = $( table ).data( 'tablesorter' ).config,
196 parsers = config.parsers,
197 len = parsers.length,
198 cellIndex,
199 cache = {
200 row: [],
201 normalized: []
202 };
203
204 for ( i = 0; i < totalRows; i++ ) {
205
206 // Add the table data to main data array
207 $row = $( table.tBodies[ 0 ].rows[ i ] );
208 cols = [];
209
210 // if this is a child row, add it to the last row's children and
211 // continue to the next row
212 if ( $row.hasClass( config.cssChildRow ) ) {
213 cache.row[ cache.row.length - 1 ] = cache.row[ cache.row.length - 1 ].add( $row );
214 // go to the next for loop
215 continue;
216 }
217
218 cache.row.push( $row );
219
220 for ( j = 0; j < len; j++ ) {
221 cellIndex = $row.data( 'columnToCell' )[ j ];
222 cols.push( parsers[ j ].format( getElementSortKey( $row[ 0 ].cells[ cellIndex ] ) ) );
223 }
224
225 cols.push( cache.normalized.length ); // add position for rowCache
226 cache.normalized.push( cols );
227 cols = null;
228 }
229
230 return cache;
231 }
232
233 function appendToTable( table, cache ) {
234 var i, pos, l, j,
235 row = cache.row,
236 normalized = cache.normalized,
237 totalRows = normalized.length,
238 checkCell = ( normalized[ 0 ].length - 1 ),
239 fragment = document.createDocumentFragment();
240
241 for ( i = 0; i < totalRows; i++ ) {
242 pos = normalized[ i ][ checkCell ];
243
244 l = row[ pos ].length;
245 for ( j = 0; j < l; j++ ) {
246 fragment.appendChild( row[ pos ][ j ] );
247 }
248
249 }
250 table.tBodies[ 0 ].appendChild( fragment );
251
252 $( table ).trigger( 'sortEnd.tablesorter' );
253 }
254
255 /**
256 * Find all header rows in a thead-less table and put them in a <thead> tag.
257 * This only treats a row as a header row if it contains only <th>s (no <td>s)
258 * and if it is preceded entirely by header rows. The algorithm stops when
259 * it encounters the first non-header row.
260 *
261 * After this, it will look at all rows at the bottom for footer rows
262 * And place these in a tfoot using similar rules.
263 *
264 * @param {jQuery} $table object for a <table>
265 */
266 function emulateTHeadAndFoot( $table ) {
267 var $thead, $tfoot, i, len,
268 $rows = $table.find( '> tbody > tr' );
269 if ( !$table.get( 0 ).tHead ) {
270 $thead = $( '<thead>' );
271 $rows.each( function () {
272 if ( $( this ).children( 'td' ).length ) {
273 // This row contains a <td>, so it's not a header row
274 // Stop here
275 return false;
276 }
277 $thead.append( this );
278 } );
279 $table.find( ' > tbody:first' ).before( $thead );
280 }
281 if ( !$table.get( 0 ).tFoot ) {
282 $tfoot = $( '<tfoot>' );
283 len = $rows.length;
284 for ( i = len - 1; i >= 0; i-- ) {
285 if ( $( $rows[ i ] ).children( 'td' ).length ) {
286 break;
287 }
288 $tfoot.prepend( $( $rows[ i ] ) );
289 }
290 $table.append( $tfoot );
291 }
292 }
293
294 function uniqueElements( array ) {
295 var uniques = [];
296 array.forEach( function ( elem ) {
297 if ( elem !== undefined && uniques.indexOf( elem ) === -1 ) {
298 uniques.push( elem );
299 }
300 } );
301 return uniques;
302 }
303
304 function buildHeaders( table, msg ) {
305 var config = $( table ).data( 'tablesorter' ).config,
306 maxSeen = 0,
307 colspanOffset = 0,
308 columns,
309 k,
310 $cell,
311 rowspan,
312 colspan,
313 headerCount,
314 longestTR,
315 headerIndex,
316 exploded,
317 $tableHeaders = $( [] ),
318 $tableRows = $( 'thead:eq(0) > tr', table );
319
320 if ( $tableRows.length <= 1 ) {
321 $tableHeaders = $tableRows.children( 'th' );
322 } else {
323 exploded = [];
324
325 // Loop through all the dom cells of the thead
326 $tableRows.each( function ( rowIndex, row ) {
327 // eslint-disable-next-line no-restricted-properties
328 $.each( row.cells, function ( columnIndex, cell ) {
329 var matrixRowIndex,
330 matrixColumnIndex;
331
332 rowspan = Number( cell.rowSpan );
333 colspan = Number( cell.colSpan );
334
335 // Skip the spots in the exploded matrix that are already filled
336 while ( exploded[ rowIndex ] && exploded[ rowIndex ][ columnIndex ] !== undefined ) {
337 ++columnIndex;
338 }
339
340 // Find the actual dimensions of the thead, by placing each cell
341 // in the exploded matrix rowspan times colspan times, with the proper offsets
342 for ( matrixColumnIndex = columnIndex; matrixColumnIndex < columnIndex + colspan; ++matrixColumnIndex ) {
343 for ( matrixRowIndex = rowIndex; matrixRowIndex < rowIndex + rowspan; ++matrixRowIndex ) {
344 if ( !exploded[ matrixRowIndex ] ) {
345 exploded[ matrixRowIndex ] = [];
346 }
347 exploded[ matrixRowIndex ][ matrixColumnIndex ] = cell;
348 }
349 }
350 } );
351 } );
352 // We want to find the row that has the most columns (ignoring colspan)
353 exploded.forEach( function ( cellArray, index ) {
354 headerCount = $( uniqueElements( cellArray ) ).filter( 'th' ).length;
355 if ( headerCount >= maxSeen ) {
356 maxSeen = headerCount;
357 longestTR = index;
358 }
359 } );
360 // We cannot use $.unique() here because it sorts into dom order, which is undesirable
361 $tableHeaders = $( uniqueElements( exploded[ longestTR ] ) ).filter( 'th' );
362 }
363
364 // as each header can span over multiple columns (using colspan=N),
365 // we have to bidirectionally map headers to their columns and columns to their headers
366 config.columnToHeader = [];
367 config.headerToColumns = [];
368 config.headerList = [];
369 headerIndex = 0;
370 $tableHeaders.each( function () {
371 $cell = $( this );
372 columns = [];
373
374 if ( !$cell.hasClass( config.unsortableClass ) ) {
375 $cell
376 .addClass( config.cssHeader )
377 .prop( 'tabIndex', 0 )
378 .attr( {
379 role: 'columnheader button',
380 title: msg[ 1 ]
381 } );
382
383 for ( k = 0; k < this.colSpan; k++ ) {
384 config.columnToHeader[ colspanOffset + k ] = headerIndex;
385 columns.push( colspanOffset + k );
386 }
387
388 config.headerToColumns[ headerIndex ] = columns;
389
390 $cell.data( {
391 headerIndex: headerIndex,
392 order: 0,
393 count: 0
394 } );
395
396 // add only sortable cells to headerList
397 config.headerList[ headerIndex ] = this;
398 headerIndex++;
399 }
400
401 colspanOffset += this.colSpan;
402 } );
403
404 // number of columns with extended colspan, inclusive unsortable
405 // parsers[j], cache[][j], columnToHeader[j], columnToCell[j] have so many elements
406 config.columns = colspanOffset;
407
408 return $tableHeaders.not( '.' + config.unsortableClass );
409 }
410
411 function isValueInArray( v, a ) {
412 var i;
413 for ( i = 0; i < a.length; i++ ) {
414 if ( a[ i ][ 0 ] === v ) {
415 return true;
416 }
417 }
418 return false;
419 }
420
421 /**
422 * Sets the sort count of the columns that are not affected by the sorting to have them sorted
423 * in default (ascending) order when their header cell is clicked the next time.
424 *
425 * @param {jQuery} $headers
426 * @param {Array} sortList 2D number array
427 * @param {Array} headerToColumns 2D number array
428 */
429 function setHeadersOrder( $headers, sortList, headerToColumns ) {
430 // Loop through all headers to retrieve the indices of the columns the header spans across:
431 headerToColumns.forEach( function ( columns, headerIndex ) {
432
433 columns.forEach( function ( columnIndex, i ) {
434 var header = $headers[ headerIndex ],
435 $header = $( header );
436
437 if ( !isValueInArray( columnIndex, sortList ) ) {
438 // Column shall not be sorted: Reset header count and order.
439 $header.data( {
440 order: 0,
441 count: 0
442 } );
443 } else {
444 // Column shall be sorted: Apply designated count and order.
445 sortList.forEach( function ( sortColumn ) {
446 if ( sortColumn[ 0 ] === i ) {
447 $header.data( {
448 order: sortColumn[ 1 ],
449 count: sortColumn[ 1 ] + 1
450 } );
451 return false;
452 }
453 } );
454 }
455 } );
456
457 } );
458 }
459
460 function setHeadersCss( table, $headers, list, css, msg, columnToHeader ) {
461 var i, len;
462 // Remove all header information and reset titles to default message
463 $headers.removeClass( css[ 0 ] ).removeClass( css[ 1 ] ).attr( 'title', msg[ 1 ] );
464
465 for ( i = 0, len = list.length; i < len; i++ ) {
466 $headers
467 .eq( columnToHeader[ list[ i ][ 0 ] ] )
468 .addClass( css[ list[ i ][ 1 ] ] )
469 .attr( 'title', msg[ list[ i ][ 1 ] ] );
470 }
471 }
472
473 function sortText( a, b ) {
474 return ( ( a < b ) ? -1 : ( ( a > b ) ? 1 : 0 ) );
475 }
476
477 function sortTextDesc( a, b ) {
478 return ( ( b < a ) ? -1 : ( ( b > a ) ? 1 : 0 ) );
479 }
480
481 function multisort( table, sortList, cache ) {
482 var i,
483 sortFn = [];
484
485 for ( i = 0; i < sortList.length; i++ ) {
486 sortFn[ i ] = ( sortList[ i ][ 1 ] ) ? sortTextDesc : sortText;
487 }
488 cache.normalized.sort( function ( array1, array2 ) {
489 var i, col, ret;
490 for ( i = 0; i < sortList.length; i++ ) {
491 col = sortList[ i ][ 0 ];
492 ret = sortFn[ i ].call( this, array1[ col ], array2[ col ] );
493 if ( ret !== 0 ) {
494 return ret;
495 }
496 }
497 // Fall back to index number column to ensure stable sort
498 return sortText.call( this, array1[ array1.length - 1 ], array2[ array2.length - 1 ] );
499 } );
500 return cache;
501 }
502
503 function buildTransformTable() {
504 var ascii, localised, i, digitClass,
505 digits = '0123456789,.'.split( '' ),
506 separatorTransformTable = mw.config.get( 'wgSeparatorTransformTable' ),
507 digitTransformTable = mw.config.get( 'wgDigitTransformTable' );
508
509 if ( separatorTransformTable === null || ( separatorTransformTable[ 0 ] === '' && digitTransformTable[ 2 ] === '' ) ) {
510 ts.transformTable = false;
511 } else {
512 ts.transformTable = {};
513
514 // Unpack the transform table
515 ascii = separatorTransformTable[ 0 ].split( '\t' ).concat( digitTransformTable[ 0 ].split( '\t' ) );
516 localised = separatorTransformTable[ 1 ].split( '\t' ).concat( digitTransformTable[ 1 ].split( '\t' ) );
517
518 // Construct regexes for number identification
519 for ( i = 0; i < ascii.length; i++ ) {
520 ts.transformTable[ localised[ i ] ] = ascii[ i ];
521 digits.push( mw.RegExp.escape( localised[ i ] ) );
522 }
523 }
524 digitClass = '[' + digits.join( '', digits ) + ']';
525
526 // We allow a trailing percent sign, which we just strip. This works fine
527 // if percents and regular numbers aren't being mixed.
528 ts.numberRegex = new RegExp(
529 '^(' +
530 '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
531 '|' +
532 '[-+\u2212]?' + digitClass + '+[\\s\\xa0]*%?' + // Generic localised
533 ')$',
534 'i'
535 );
536 }
537
538 function buildDateTable() {
539 var i, name,
540 regex = [];
541
542 ts.monthNames = {};
543
544 for ( i = 0; i < 12; i++ ) {
545 name = mw.language.months.names[ i ].toLowerCase();
546 ts.monthNames[ name ] = i + 1;
547 regex.push( mw.RegExp.escape( name ) );
548 name = mw.language.months.genitive[ i ].toLowerCase();
549 ts.monthNames[ name ] = i + 1;
550 regex.push( mw.RegExp.escape( name ) );
551 name = mw.language.months.abbrev[ i ].toLowerCase().replace( '.', '' );
552 ts.monthNames[ name ] = i + 1;
553 regex.push( mw.RegExp.escape( name ) );
554 }
555
556 // Build piped string
557 regex = regex.join( '|' );
558
559 // Build RegEx
560 // Any date formated with . , ' - or /
561 ts.dateRegex[ 0 ] = new RegExp( /^\s*(\d{1,2})[,.\-/'\s]{1,2}(\d{1,2})[,.\-/'\s]{1,2}(\d{2,4})\s*?/i );
562
563 // Written Month name, dmy
564 ts.dateRegex[ 1 ] = new RegExp(
565 '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(' +
566 regex +
567 ')' +
568 '[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$',
569 'i'
570 );
571
572 // Written Month name, mdy
573 ts.dateRegex[ 2 ] = new RegExp(
574 '^\\s*(' + regex + ')' +
575 '[\\,\\.\\-\\/\'\\s]+(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$',
576 'i'
577 );
578
579 }
580
581 /**
582 * Replace all rowspanned cells in the body with clones in each row, so sorting
583 * need not worry about them.
584 *
585 * @param {jQuery} $table jQuery object for a <table>
586 */
587 function explodeRowspans( $table ) {
588 var spanningRealCellIndex, rowSpan, colSpan,
589 cell, cellData, i, $tds, $clone, $nextRows,
590 rowspanCells = $table.find( '> tbody > tr > [rowspan]' ).get();
591
592 // Short circuit
593 if ( !rowspanCells.length ) {
594 return;
595 }
596
597 // First, we need to make a property like cellIndex but taking into
598 // account colspans. We also cache the rowIndex to avoid having to take
599 // cell.parentNode.rowIndex in the sorting function below.
600 $table.find( '> tbody > tr' ).each( function () {
601 var i,
602 col = 0,
603 len = this.cells.length;
604 for ( i = 0; i < len; i++ ) {
605 $( this.cells[ i ] ).data( 'tablesorter', {
606 realCellIndex: col,
607 realRowIndex: this.rowIndex
608 } );
609 col += this.cells[ i ].colSpan;
610 }
611 } );
612
613 // Split multi row cells into multiple cells with the same content.
614 // Sort by column then row index to avoid problems with odd table structures.
615 // Re-sort whenever a rowspanned cell's realCellIndex is changed, because it
616 // might change the sort order.
617 function resortCells() {
618 var cellAData,
619 cellBData,
620 ret;
621 rowspanCells = rowspanCells.sort( function ( a, b ) {
622 cellAData = $.data( a, 'tablesorter' );
623 cellBData = $.data( b, 'tablesorter' );
624 ret = cellAData.realCellIndex - cellBData.realCellIndex;
625 if ( !ret ) {
626 ret = cellAData.realRowIndex - cellBData.realRowIndex;
627 }
628 return ret;
629 } );
630 rowspanCells.forEach( function ( cell ) {
631 $.data( cell, 'tablesorter' ).needResort = false;
632 } );
633 }
634 resortCells();
635
636 function filterfunc() {
637 return $.data( this, 'tablesorter' ).realCellIndex >= spanningRealCellIndex;
638 }
639
640 function fixTdCellIndex() {
641 $.data( this, 'tablesorter' ).realCellIndex += colSpan;
642 if ( this.rowSpan > 1 ) {
643 $.data( this, 'tablesorter' ).needResort = true;
644 }
645 }
646
647 while ( rowspanCells.length ) {
648 if ( $.data( rowspanCells[ 0 ], 'tablesorter' ).needResort ) {
649 resortCells();
650 }
651
652 cell = rowspanCells.shift();
653 cellData = $.data( cell, 'tablesorter' );
654 rowSpan = cell.rowSpan;
655 colSpan = cell.colSpan;
656 spanningRealCellIndex = cellData.realCellIndex;
657 cell.rowSpan = 1;
658 $nextRows = $( cell ).parent().nextAll();
659 for ( i = 0; i < rowSpan - 1; i++ ) {
660 $tds = $( $nextRows[ i ].cells ).filter( filterfunc );
661 $clone = $( cell ).clone();
662 $clone.data( 'tablesorter', {
663 realCellIndex: spanningRealCellIndex,
664 realRowIndex: cellData.realRowIndex + i,
665 needResort: true
666 } );
667 if ( $tds.length ) {
668 $tds.each( fixTdCellIndex );
669 $tds.first().before( $clone );
670 } else {
671 $nextRows.eq( i ).append( $clone );
672 }
673 }
674 }
675 }
676
677 /**
678 * Build index to handle colspanned cells in the body.
679 * Set the cell index for each column in an array,
680 * so that colspaned cells set multiple in this array.
681 * columnToCell[collumnIndex] point at the real cell in this row.
682 *
683 * @param {jQuery} $table object for a <table>
684 */
685 function manageColspans( $table ) {
686 var i, j, k, $row,
687 $rows = $table.find( '> tbody > tr' ),
688 totalRows = $rows.length || 0,
689 config = $table.data( 'tablesorter' ).config,
690 columns = config.columns,
691 columnToCell, cellsInRow, index;
692
693 for ( i = 0; i < totalRows; i++ ) {
694
695 $row = $rows.eq( i );
696 // if this is a child row, continue to the next row (as buildCache())
697 if ( $row.hasClass( config.cssChildRow ) ) {
698 // go to the next for loop
699 continue;
700 }
701
702 columnToCell = [];
703 cellsInRow = ( $row[ 0 ].cells.length ) || 0; // all cells in this row
704 index = 0; // real cell index in this row
705 for ( j = 0; j < columns; index++ ) {
706 if ( index === cellsInRow ) {
707 // Row with cells less than columns: add empty cell
708 $row.append( '<td>' );
709 cellsInRow++;
710 }
711 for ( k = 0; k < $row[ 0 ].cells[ index ].colSpan; k++ ) {
712 columnToCell[ j++ ] = index;
713 }
714 }
715 // Store it in $row
716 $row.data( 'columnToCell', columnToCell );
717 }
718 }
719
720 function buildCollationTable() {
721 var key, keys = [];
722 ts.collationTable = mw.config.get( 'tableSorterCollation' );
723 ts.collationRegex = null;
724 if ( ts.collationTable ) {
725 // Build array of key names
726 for ( key in ts.collationTable ) {
727 keys.push( mw.RegExp.escape( key ) );
728 }
729 if ( keys.length ) {
730 ts.collationRegex = new RegExp( keys.join( '|' ), 'ig' );
731 }
732 }
733 }
734
735 function cacheRegexs() {
736 if ( ts.rgx ) {
737 return;
738 }
739 ts.rgx = {
740 IPAddress: [
741 new RegExp( /^\d{1,3}[.]\d{1,3}[.]\d{1,3}[.]\d{1,3}$/ )
742 ],
743 currency: [
744 new RegExp( /(^[£$€¥]|[£$€¥]$)/ ),
745 new RegExp( /[£$€¥]/g )
746 ],
747 url: [
748 new RegExp( /^(https?|ftp|file):\/\/$/ ),
749 new RegExp( /(https?|ftp|file):\/\// )
750 ],
751 isoDate: [
752 new RegExp( /^[^-\d]*(-?\d{1,4})-(0\d|1[0-2])(-([0-3]\d))?([T\s]([01]\d|2[0-4]):?(([0-5]\d):?(([0-5]\d|60)([.,]\d{1,3})?)?)?([zZ]|([-+])([01]\d|2[0-3]):?([0-5]\d)?)?)?/ ),
753 new RegExp( /^[^-\d]*(-?\d{1,4})-?(\d\d)?(-?(\d\d))?([T\s](\d\d):?((\d\d)?:?((\d\d)?([.,]\d{1,3})?)?)?([zZ]|([-+])(\d\d):?(\d\d)?)?)?/ )
754 ],
755 usLongDate: [
756 new RegExp( /^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/ )
757 ],
758 time: [
759 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/ )
760 ]
761 };
762 }
763
764 /**
765 * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
766 * structure [ [ Integer, Integer ], ... ]
767 *
768 * @param {Array} sortObjects List of sort objects.
769 * @return {Array} List of internal sort definitions.
770 */
771 function convertSortList( sortObjects ) {
772 var sortList = [];
773 sortObjects.forEach( function ( sortObject ) {
774 // eslint-disable-next-line no-restricted-properties
775 $.each( sortObject, function ( columnIndex, order ) {
776 var orderIndex = ( order === 'desc' ) ? 1 : 0;
777 sortList.push( [ parseInt( columnIndex, 10 ), orderIndex ] );
778 } );
779 } );
780 return sortList;
781 }
782
783 /* Public scope */
784
785 $.tablesorter = {
786 defaultOptions: {
787 cssHeader: 'headerSort',
788 cssAsc: 'headerSortUp',
789 cssDesc: 'headerSortDown',
790 cssChildRow: 'expand-child',
791 sortMultiSortKey: 'shiftKey',
792 unsortableClass: 'unsortable',
793 parsers: [],
794 cancelSelection: true,
795 sortList: [],
796 headerList: [],
797 headerToColumns: [],
798 columnToHeader: [],
799 columns: 0
800 },
801
802 dateRegex: [],
803 monthNames: {},
804
805 /**
806 * @param {jQuery} $tables
807 * @param {Object} [settings]
808 * @return {jQuery}
809 */
810 construct: function ( $tables, settings ) {
811 return $tables.each( function ( i, table ) {
812 // Declare and cache.
813 var $headers, cache, config, sortCSS, sortMsg,
814 $table = $( table ),
815 firstTime = true;
816
817 // Quit if no tbody
818 if ( !table.tBodies ) {
819 return;
820 }
821 if ( !table.tHead ) {
822 // No thead found. Look for rows with <th>s and
823 // move them into a <thead> tag or a <tfoot> tag
824 emulateTHeadAndFoot( $table );
825
826 // Still no thead? Then quit
827 if ( !table.tHead ) {
828 return;
829 }
830 }
831 // The `sortable` class is used to identify tables which will become sortable
832 // If not used it will create a FOUC but it should be added since the sortable class
833 // is responsible for certain crucial style elements. If the class is already present
834 // this action will be harmless.
835 $table.addClass( 'jquery-tablesorter sortable' );
836
837 // Merge and extend
838 config = $.extend( {}, $.tablesorter.defaultOptions, settings );
839
840 // Save the settings where they read
841 $.data( table, 'tablesorter', { config: config } );
842
843 // Get the CSS class names, could be done elsewhere
844 sortCSS = [ config.cssAsc, config.cssDesc ];
845 // Messages tell the user what the *next* state will be
846 // so are in reverse order to the CSS classes.
847 sortMsg = [ mw.msg( 'sort-descending' ), mw.msg( 'sort-ascending' ) ];
848
849 // Build headers
850 $headers = buildHeaders( table, sortMsg );
851
852 // Grab and process locale settings.
853 buildTransformTable();
854 buildDateTable();
855
856 // Precaching regexps can bring 10 fold
857 // performance improvements in some browsers.
858 cacheRegexs();
859
860 function setupForFirstSort() {
861 var $tfoot, $sortbottoms;
862
863 firstTime = false;
864
865 // Defer buildCollationTable to first sort. As user and site scripts
866 // may customize tableSorterCollation but load after $.ready(), other
867 // scripts may call .tablesorter() before they have done the
868 // tableSorterCollation customizations.
869 buildCollationTable();
870
871 // Legacy fix of .sortbottoms
872 // Wrap them inside a tfoot (because that's what they actually want to be)
873 // and put the <tfoot> at the end of the <table>
874 $sortbottoms = $table.find( '> tbody > tr.sortbottom' );
875 if ( $sortbottoms.length ) {
876 $tfoot = $table.children( 'tfoot' );
877 if ( $tfoot.length ) {
878 $tfoot.eq( 0 ).prepend( $sortbottoms );
879 } else {
880 $table.append( $( '<tfoot>' ).append( $sortbottoms ) );
881 }
882 }
883
884 explodeRowspans( $table );
885 manageColspans( $table );
886
887 // Try to auto detect column type, and store in tables config
888 config.parsers = buildParserCache( table, $headers );
889 }
890
891 // Apply event handling to headers
892 // this is too big, perhaps break it out?
893 $headers.on( 'keypress click', function ( e ) {
894 var cell, $cell, columns, newSortList, i,
895 totalRows,
896 j, s, o;
897
898 if ( e.type === 'click' && e.target.nodeName.toLowerCase() === 'a' ) {
899 // The user clicked on a link inside a table header.
900 // Do nothing and let the default link click action continue.
901 return true;
902 }
903
904 if ( e.type === 'keypress' && e.which !== 13 ) {
905 // Only handle keypresses on the "Enter" key.
906 return true;
907 }
908
909 if ( firstTime ) {
910 setupForFirstSort();
911 }
912
913 // Build the cache for the tbody cells
914 // to share between calculations for this sort action.
915 // Re-calculated each time a sort action is performed due to possibility
916 // that sort values change. Shouldn't be too expensive, but if it becomes
917 // too slow an event based system should be implemented somehow where
918 // cells get event .change() and bubbles up to the <table> here
919 cache = buildCache( table );
920
921 totalRows = ( $table[ 0 ].tBodies[ 0 ] && $table[ 0 ].tBodies[ 0 ].rows.length ) || 0;
922 if ( totalRows > 0 ) {
923 cell = this;
924 $cell = $( cell );
925
926 // Get current column sort order
927 $cell.data( {
928 order: $cell.data( 'count' ) % 2,
929 count: $cell.data( 'count' ) + 1
930 } );
931
932 cell = this;
933 // Get current column index
934 columns = config.headerToColumns[ $cell.data( 'headerIndex' ) ];
935 newSortList = columns.map( function ( c ) {
936 return [ c, $cell.data( 'order' ) ];
937 } );
938 // Index of first column belonging to this header
939 i = columns[ 0 ];
940
941 if ( !e[ config.sortMultiSortKey ] ) {
942 // User only wants to sort on one column set
943 // Flush the sort list and add new columns
944 config.sortList = newSortList;
945 } else {
946 // Multi column sorting
947 // It is not possible for one column to belong to multiple headers,
948 // so this is okay - we don't need to check for every value in the columns array
949 if ( isValueInArray( i, config.sortList ) ) {
950 // The user has clicked on an already sorted column.
951 // Reverse the sorting direction for all tables.
952 for ( j = 0; j < config.sortList.length; j++ ) {
953 s = config.sortList[ j ];
954 o = config.headerList[ config.columnToHeader[ s[ 0 ] ] ];
955 if ( isValueInArray( s[ 0 ], newSortList ) ) {
956 $( o ).data( 'count', s[ 1 ] + 1 );
957 s[ 1 ] = $( o ).data( 'count' ) % 2;
958 }
959 }
960 } else {
961 // Add columns to sort list array
962 config.sortList = config.sortList.concat( newSortList );
963 }
964 }
965
966 // Reset order/counts of cells not affected by sorting
967 setHeadersOrder( $headers, config.sortList, config.headerToColumns );
968
969 // Set CSS for headers
970 setHeadersCss( $table[ 0 ], $headers, config.sortList, sortCSS, sortMsg, config.columnToHeader );
971 appendToTable(
972 $table[ 0 ], multisort( $table[ 0 ], config.sortList, cache )
973 );
974
975 // Stop normal event by returning false
976 return false;
977 }
978
979 // Cancel selection
980 } ).mousedown( function () {
981 if ( config.cancelSelection ) {
982 this.onselectstart = function () {
983 return false;
984 };
985 return false;
986 }
987 } );
988
989 /**
990 * Sorts the table. If no sorting is specified by passing a list of sort
991 * objects, the table is sorted according to the initial sorting order.
992 * Passing an empty array will reset sorting (basically just reset the headers
993 * making the table appear unsorted).
994 *
995 * @param {Array} [sortList] List of sort objects.
996 */
997 $table.data( 'tablesorter' ).sort = function ( sortList ) {
998
999 if ( firstTime ) {
1000 setupForFirstSort();
1001 }
1002
1003 if ( sortList === undefined ) {
1004 sortList = config.sortList;
1005 } else if ( sortList.length > 0 ) {
1006 sortList = convertSortList( sortList );
1007 }
1008
1009 // Set each column's sort count to be able to determine the correct sort
1010 // order when clicking on a header cell the next time
1011 setHeadersOrder( $headers, sortList, config.headerToColumns );
1012
1013 // re-build the cache for the tbody cells
1014 cache = buildCache( table );
1015
1016 // set css for headers
1017 setHeadersCss( table, $headers, sortList, sortCSS, sortMsg, config.columnToHeader );
1018
1019 // sort the table and append it to the dom
1020 appendToTable( table, multisort( table, sortList, cache ) );
1021 };
1022
1023 // sort initially
1024 if ( config.sortList.length > 0 ) {
1025 config.sortList = convertSortList( config.sortList );
1026 $table.data( 'tablesorter' ).sort();
1027 }
1028
1029 } );
1030 },
1031
1032 addParser: function ( parser ) {
1033 if ( !getParserById( parser.id ) ) {
1034 parsers.push( parser );
1035 }
1036 },
1037
1038 formatDigit: function ( s ) {
1039 var out, c, p, i;
1040 if ( ts.transformTable !== false ) {
1041 out = '';
1042 for ( p = 0; p < s.length; p++ ) {
1043 c = s.charAt( p );
1044 if ( c in ts.transformTable ) {
1045 out += ts.transformTable[ c ];
1046 } else {
1047 out += c;
1048 }
1049 }
1050 s = out;
1051 }
1052 i = parseFloat( s.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
1053 return isNaN( i ) ? -Infinity : i;
1054 },
1055
1056 formatFloat: function ( s ) {
1057 var i = parseFloat( s );
1058 return isNaN( i ) ? -Infinity : i;
1059 },
1060
1061 formatInt: function ( s ) {
1062 var i = parseInt( s, 10 );
1063 return isNaN( i ) ? -Infinity : i;
1064 },
1065
1066 clearTableBody: function ( table ) {
1067 $( table.tBodies[ 0 ] ).empty();
1068 },
1069
1070 getParser: function ( id ) {
1071 buildTransformTable();
1072 buildDateTable();
1073 cacheRegexs();
1074 buildCollationTable();
1075
1076 return getParserById( id );
1077 },
1078
1079 getParsers: function () { // for table diagnosis
1080 return parsers;
1081 }
1082 };
1083
1084 // Shortcut
1085 ts = $.tablesorter;
1086
1087 // Register as jQuery prototype method
1088 $.fn.tablesorter = function ( settings ) {
1089 return ts.construct( this, settings );
1090 };
1091
1092 // Add default parsers
1093 ts.addParser( {
1094 id: 'text',
1095 is: function () {
1096 return true;
1097 },
1098 format: function ( s ) {
1099 var tsc;
1100 s = s.toLowerCase().trim();
1101 if ( ts.collationRegex ) {
1102 tsc = ts.collationTable;
1103 s = s.replace( ts.collationRegex, function ( match ) {
1104 var r = tsc[ match ] ? tsc[ match ] : tsc[ match.toUpperCase() ];
1105 return r.toLowerCase();
1106 } );
1107 }
1108 return s;
1109 },
1110 type: 'text'
1111 } );
1112
1113 ts.addParser( {
1114 id: 'IPAddress',
1115 is: function ( s ) {
1116 return ts.rgx.IPAddress[ 0 ].test( s );
1117 },
1118 format: function ( s ) {
1119 var i, item,
1120 a = s.split( '.' ),
1121 r = '';
1122 for ( i = 0; i < a.length; i++ ) {
1123 item = a[ i ];
1124 if ( item.length === 1 ) {
1125 r += '00' + item;
1126 } else if ( item.length === 2 ) {
1127 r += '0' + item;
1128 } else {
1129 r += item;
1130 }
1131 }
1132 return $.tablesorter.formatFloat( r );
1133 },
1134 type: 'numeric'
1135 } );
1136
1137 ts.addParser( {
1138 id: 'currency',
1139 is: function ( s ) {
1140 return ts.rgx.currency[ 0 ].test( s );
1141 },
1142 format: function ( s ) {
1143 return $.tablesorter.formatDigit( s.replace( ts.rgx.currency[ 1 ], '' ) );
1144 },
1145 type: 'numeric'
1146 } );
1147
1148 ts.addParser( {
1149 id: 'url',
1150 is: function ( s ) {
1151 return ts.rgx.url[ 0 ].test( s );
1152 },
1153 format: function ( s ) {
1154 return s.replace( ts.rgx.url[ 1 ], '' ).trim();
1155 },
1156 type: 'text'
1157 } );
1158
1159 ts.addParser( {
1160 id: 'isoDate',
1161 is: function ( s ) {
1162 return ts.rgx.isoDate[ 0 ].test( s );
1163 },
1164 format: function ( s ) {
1165 var match, i, isodate, ms, hOffset, mOffset;
1166 match = s.match( ts.rgx.isoDate[ 0 ] );
1167 if ( match === null ) {
1168 // Otherwise a signed number with 1-4 digit is parsed as isoDate
1169 match = s.match( ts.rgx.isoDate[ 1 ] );
1170 }
1171 if ( !match ) {
1172 return -Infinity;
1173 }
1174 // Month and day
1175 for ( i = 2; i <= 4; i += 2 ) {
1176 if ( !match[ i ] || match[ i ].length === 0 ) {
1177 match[ i ] = 1;
1178 }
1179 }
1180 // Time
1181 for ( i = 6; i <= 15; i++ ) {
1182 if ( !match[ i ] || match[ i ].length === 0 ) {
1183 match[ i ] = '0';
1184 }
1185 }
1186 ms = parseFloat( match[ 11 ].replace( /,/, '.' ) ) * 1000;
1187 hOffset = $.tablesorter.formatInt( match[ 13 ] + match[ 14 ] );
1188 mOffset = $.tablesorter.formatInt( match[ 13 ] + match[ 15 ] );
1189
1190 isodate = new Date( 0 );
1191 // Because Date constructor changes year 0-99 to 1900-1999, use setUTCFullYear()
1192 isodate.setUTCFullYear( match[ 1 ], match[ 2 ] - 1, match[ 4 ] );
1193 isodate.setUTCHours( match[ 6 ] - hOffset, match[ 8 ] - mOffset, match[ 10 ], ms );
1194 return isodate.getTime();
1195 },
1196 type: 'numeric'
1197 } );
1198
1199 ts.addParser( {
1200 id: 'usLongDate',
1201 is: function ( s ) {
1202 return ts.rgx.usLongDate[ 0 ].test( s );
1203 },
1204 format: function ( s ) {
1205 return $.tablesorter.formatFloat( new Date( s ).getTime() );
1206 },
1207 type: 'numeric'
1208 } );
1209
1210 ts.addParser( {
1211 id: 'date',
1212 is: function ( s ) {
1213 return ( ts.dateRegex[ 0 ].test( s ) || ts.dateRegex[ 1 ].test( s ) || ts.dateRegex[ 2 ].test( s ) );
1214 },
1215 format: function ( s ) {
1216 var match, y;
1217 s = s.toLowerCase().trim();
1218
1219 if ( ( match = s.match( ts.dateRegex[ 0 ] ) ) !== null ) {
1220 if ( mw.config.get( 'wgDefaultDateFormat' ) === 'mdy' || mw.config.get( 'wgPageContentLanguage' ) === 'en' ) {
1221 s = [ match[ 3 ], match[ 1 ], match[ 2 ] ];
1222 } else if ( mw.config.get( 'wgDefaultDateFormat' ) === 'dmy' ) {
1223 s = [ match[ 3 ], match[ 2 ], match[ 1 ] ];
1224 } else {
1225 // If we get here, we don't know which order the dd-dd-dddd
1226 // date is in. So return something not entirely invalid.
1227 return '99999999';
1228 }
1229 } else if ( ( match = s.match( ts.dateRegex[ 1 ] ) ) !== null ) {
1230 s = [ match[ 3 ], String( ts.monthNames[ match[ 2 ] ] ), match[ 1 ] ];
1231 } else if ( ( match = s.match( ts.dateRegex[ 2 ] ) ) !== null ) {
1232 s = [ match[ 3 ], String( ts.monthNames[ match[ 1 ] ] ), match[ 2 ] ];
1233 } else {
1234 // Should never get here
1235 return '99999999';
1236 }
1237
1238 // Pad Month and Day
1239 if ( s[ 1 ].length === 1 ) {
1240 s[ 1 ] = '0' + s[ 1 ];
1241 }
1242 if ( s[ 2 ].length === 1 ) {
1243 s[ 2 ] = '0' + s[ 2 ];
1244 }
1245
1246 if ( ( y = parseInt( s[ 0 ], 10 ) ) < 100 ) {
1247 // Guestimate years without centuries
1248 if ( y < 30 ) {
1249 s[ 0 ] = 2000 + y;
1250 } else {
1251 s[ 0 ] = 1900 + y;
1252 }
1253 }
1254 while ( s[ 0 ].length < 4 ) {
1255 s[ 0 ] = '0' + s[ 0 ];
1256 }
1257 return parseInt( s.join( '' ), 10 );
1258 },
1259 type: 'numeric'
1260 } );
1261
1262 ts.addParser( {
1263 id: 'time',
1264 is: function ( s ) {
1265 return ts.rgx.time[ 0 ].test( s );
1266 },
1267 format: function ( s ) {
1268 return $.tablesorter.formatFloat( new Date( '2000/01/01 ' + s ).getTime() );
1269 },
1270 type: 'numeric'
1271 } );
1272
1273 ts.addParser( {
1274 id: 'number',
1275 is: function ( s ) {
1276 return $.tablesorter.numberRegex.test( s.trim() );
1277 },
1278 format: function ( s ) {
1279 return $.tablesorter.formatDigit( s );
1280 },
1281 type: 'numeric'
1282 } );
1283
1284 }() );