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