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