Merge "Cache redirects from Special:Redirect"
[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 jquery/no-each-util
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 j, sortColumn,
435 header = $headers[ headerIndex ],
436 $header = $( header );
437
438 if ( !isValueInArray( columnIndex, sortList ) ) {
439 // Column shall not be sorted: Reset header count and order.
440 $header.data( {
441 order: 0,
442 count: 0
443 } );
444 } else {
445 // Column shall be sorted: Apply designated count and order.
446 for ( j = 0; j < sortList.length; j++ ) {
447 sortColumn = sortList[ j ];
448 if ( sortColumn[ 0 ] === i ) {
449 $header.data( {
450 order: sortColumn[ 1 ],
451 count: sortColumn[ 1 ] + 1
452 } );
453 break;
454 }
455 }
456 }
457 } );
458
459 } );
460 }
461
462 function setHeadersCss( table, $headers, list, css, msg, columnToHeader ) {
463 var i, len;
464 // Remove all header information and reset titles to default message
465 $headers.removeClass( css ).attr( 'title', msg[ 1 ] );
466
467 for ( i = 0, len = list.length; i < len; i++ ) {
468 $headers
469 .eq( columnToHeader[ list[ i ][ 0 ] ] )
470 .addClass( css[ list[ i ][ 1 ] ] )
471 .attr( 'title', msg[ list[ i ][ 1 ] ] );
472 }
473 }
474
475 function sortText( a, b ) {
476 return ( ( a < b ) ? -1 : ( ( a > b ) ? 1 : 0 ) );
477 }
478
479 function sortTextDesc( a, b ) {
480 return ( ( b < a ) ? -1 : ( ( b > a ) ? 1 : 0 ) );
481 }
482
483 function multisort( table, sortList, cache ) {
484 var i,
485 sortFn = [];
486
487 for ( i = 0; i < sortList.length; i++ ) {
488 sortFn[ i ] = ( sortList[ i ][ 1 ] ) ? sortTextDesc : sortText;
489 }
490 cache.normalized.sort( function ( array1, array2 ) {
491 var i, col, ret;
492 for ( i = 0; i < sortList.length; i++ ) {
493 col = sortList[ i ][ 0 ];
494 ret = sortFn[ i ].call( this, array1[ col ], array2[ col ] );
495 if ( ret !== 0 ) {
496 return ret;
497 }
498 }
499 // Fall back to index number column to ensure stable sort
500 return sortText.call( this, array1[ array1.length - 1 ], array2[ array2.length - 1 ] );
501 } );
502 return cache;
503 }
504
505 function buildTransformTable() {
506 var ascii, localised, i, digitClass,
507 digits = '0123456789,.'.split( '' ),
508 separatorTransformTable = mw.config.get( 'wgSeparatorTransformTable' ),
509 digitTransformTable = mw.config.get( 'wgDigitTransformTable' );
510
511 if ( separatorTransformTable === null || ( separatorTransformTable[ 0 ] === '' && digitTransformTable[ 2 ] === '' ) ) {
512 ts.transformTable = false;
513 } else {
514 ts.transformTable = {};
515
516 // Unpack the transform table
517 ascii = separatorTransformTable[ 0 ].split( '\t' ).concat( digitTransformTable[ 0 ].split( '\t' ) );
518 localised = separatorTransformTable[ 1 ].split( '\t' ).concat( digitTransformTable[ 1 ].split( '\t' ) );
519
520 // Construct regexes for number identification
521 for ( i = 0; i < ascii.length; i++ ) {
522 ts.transformTable[ localised[ i ] ] = ascii[ i ];
523 digits.push( mw.RegExp.escape( localised[ i ] ) );
524 }
525 }
526 digitClass = '[' + digits.join( '', digits ) + ']';
527
528 // We allow a trailing percent sign, which we just strip. This works fine
529 // if percents and regular numbers aren't being mixed.
530 ts.numberRegex = new RegExp(
531 '^(' +
532 '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
533 '|' +
534 '[-+\u2212]?' + digitClass + '+[\\s\\xa0]*%?' + // Generic localised
535 ')$',
536 'i'
537 );
538 }
539
540 function buildDateTable() {
541 var i, name,
542 regex = [];
543
544 ts.monthNames = {};
545
546 for ( i = 0; i < 12; i++ ) {
547 name = mw.language.months.names[ i ].toLowerCase();
548 ts.monthNames[ name ] = i + 1;
549 regex.push( mw.RegExp.escape( name ) );
550 name = mw.language.months.genitive[ i ].toLowerCase();
551 ts.monthNames[ name ] = i + 1;
552 regex.push( mw.RegExp.escape( name ) );
553 name = mw.language.months.abbrev[ i ].toLowerCase().replace( '.', '' );
554 ts.monthNames[ name ] = i + 1;
555 regex.push( mw.RegExp.escape( name ) );
556 }
557
558 // Build piped string
559 regex = regex.join( '|' );
560
561 // Build RegEx
562 // Any date formated with . , ' - or /
563 ts.dateRegex[ 0 ] = new RegExp( /^\s*(\d{1,2})[,.\-/'\s]{1,2}(\d{1,2})[,.\-/'\s]{1,2}(\d{2,4})\s*?/i );
564
565 // Written Month name, dmy
566 ts.dateRegex[ 1 ] = new RegExp(
567 '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(' +
568 regex +
569 ')' +
570 '[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$',
571 'i'
572 );
573
574 // Written Month name, mdy
575 ts.dateRegex[ 2 ] = new RegExp(
576 '^\\s*(' + regex + ')' +
577 '[\\,\\.\\-\\/\'\\s]+(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$',
578 'i'
579 );
580
581 }
582
583 /**
584 * Replace all rowspanned cells in the body with clones in each row, so sorting
585 * need not worry about them.
586 *
587 * @param {jQuery} $table jQuery object for a <table>
588 */
589 function explodeRowspans( $table ) {
590 var spanningRealCellIndex, rowSpan, colSpan,
591 cell, cellData, i, $tds, $clone, $nextRows,
592 rowspanCells = $table.find( '> tbody > tr > [rowspan]' ).get();
593
594 // Short circuit
595 if ( !rowspanCells.length ) {
596 return;
597 }
598
599 // First, we need to make a property like cellIndex but taking into
600 // account colspans. We also cache the rowIndex to avoid having to take
601 // cell.parentNode.rowIndex in the sorting function below.
602 $table.find( '> tbody > tr' ).each( function () {
603 var i,
604 col = 0,
605 len = this.cells.length;
606 for ( i = 0; i < len; i++ ) {
607 $( this.cells[ i ] ).data( 'tablesorter', {
608 realCellIndex: col,
609 realRowIndex: this.rowIndex
610 } );
611 col += this.cells[ i ].colSpan;
612 }
613 } );
614
615 // Split multi row cells into multiple cells with the same content.
616 // Sort by column then row index to avoid problems with odd table structures.
617 // Re-sort whenever a rowspanned cell's realCellIndex is changed, because it
618 // might change the sort order.
619 function resortCells() {
620 var cellAData,
621 cellBData,
622 ret;
623 rowspanCells = rowspanCells.sort( function ( a, b ) {
624 cellAData = $.data( a, 'tablesorter' );
625 cellBData = $.data( b, 'tablesorter' );
626 ret = cellAData.realCellIndex - cellBData.realCellIndex;
627 if ( !ret ) {
628 ret = cellAData.realRowIndex - cellBData.realRowIndex;
629 }
630 return ret;
631 } );
632 rowspanCells.forEach( function ( cell ) {
633 $.data( cell, 'tablesorter' ).needResort = false;
634 } );
635 }
636 resortCells();
637
638 function filterfunc() {
639 return $.data( this, 'tablesorter' ).realCellIndex >= spanningRealCellIndex;
640 }
641
642 function fixTdCellIndex() {
643 $.data( this, 'tablesorter' ).realCellIndex += colSpan;
644 if ( this.rowSpan > 1 ) {
645 $.data( this, 'tablesorter' ).needResort = true;
646 }
647 }
648
649 while ( rowspanCells.length ) {
650 if ( $.data( rowspanCells[ 0 ], 'tablesorter' ).needResort ) {
651 resortCells();
652 }
653
654 cell = rowspanCells.shift();
655 cellData = $.data( cell, 'tablesorter' );
656 rowSpan = cell.rowSpan;
657 colSpan = cell.colSpan;
658 spanningRealCellIndex = cellData.realCellIndex;
659 cell.rowSpan = 1;
660 $nextRows = $( cell ).parent().nextAll();
661 for ( i = 0; i < rowSpan - 1; i++ ) {
662 $tds = $( $nextRows[ i ].cells ).filter( filterfunc );
663 $clone = $( cell ).clone();
664 $clone.data( 'tablesorter', {
665 realCellIndex: spanningRealCellIndex,
666 realRowIndex: cellData.realRowIndex + i,
667 needResort: true
668 } );
669 if ( $tds.length ) {
670 $tds.each( fixTdCellIndex );
671 $tds.first().before( $clone );
672 } else {
673 $nextRows.eq( i ).append( $clone );
674 }
675 }
676 }
677 }
678
679 /**
680 * Build index to handle colspanned cells in the body.
681 * Set the cell index for each column in an array,
682 * so that colspaned cells set multiple in this array.
683 * columnToCell[collumnIndex] point at the real cell in this row.
684 *
685 * @param {jQuery} $table object for a <table>
686 */
687 function manageColspans( $table ) {
688 var i, j, k, $row,
689 $rows = $table.find( '> tbody > tr' ),
690 totalRows = $rows.length || 0,
691 config = $table.data( 'tablesorter' ).config,
692 columns = config.columns,
693 columnToCell, cellsInRow, index;
694
695 for ( i = 0; i < totalRows; i++ ) {
696
697 $row = $rows.eq( i );
698 // if this is a child row, continue to the next row (as buildCache())
699 if ( $row.hasClass( config.cssChildRow ) ) {
700 // go to the next for loop
701 continue;
702 }
703
704 columnToCell = [];
705 cellsInRow = ( $row[ 0 ].cells.length ) || 0; // all cells in this row
706 index = 0; // real cell index in this row
707 for ( j = 0; j < columns; index++ ) {
708 if ( index === cellsInRow ) {
709 // Row with cells less than columns: add empty cell
710 $row.append( '<td>' );
711 cellsInRow++;
712 }
713 for ( k = 0; k < $row[ 0 ].cells[ index ].colSpan; k++ ) {
714 columnToCell[ j++ ] = index;
715 }
716 }
717 // Store it in $row
718 $row.data( 'columnToCell', columnToCell );
719 }
720 }
721
722 function buildCollationTable() {
723 var key, keys = [];
724 ts.collationTable = mw.config.get( 'tableSorterCollation' );
725 ts.collationRegex = null;
726 if ( ts.collationTable ) {
727 // Build array of key names
728 for ( key in ts.collationTable ) {
729 keys.push( mw.RegExp.escape( key ) );
730 }
731 if ( keys.length ) {
732 ts.collationRegex = new RegExp( keys.join( '|' ), 'ig' );
733 }
734 }
735 }
736
737 function cacheRegexs() {
738 if ( ts.rgx ) {
739 return;
740 }
741 ts.rgx = {
742 IPAddress: [
743 new RegExp( /^\d{1,3}[.]\d{1,3}[.]\d{1,3}[.]\d{1,3}$/ )
744 ],
745 currency: [
746 new RegExp( /(^[£$€¥]|[£$€¥]$)/ ),
747 new RegExp( /[£$€¥]/g )
748 ],
749 url: [
750 new RegExp( /^(https?|ftp|file):\/\/$/ ),
751 new RegExp( /(https?|ftp|file):\/\// )
752 ],
753 isoDate: [
754 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)?)?)?/ ),
755 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)?)?)?/ )
756 ],
757 usLongDate: [
758 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)))$/ )
759 ],
760 time: [
761 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/ )
762 ]
763 };
764 }
765
766 /**
767 * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
768 * structure [ [ Integer, Integer ], ... ]
769 *
770 * @param {Array} sortObjects List of sort objects.
771 * @return {Array} List of internal sort definitions.
772 */
773 function convertSortList( sortObjects ) {
774 var sortList = [];
775 sortObjects.forEach( function ( sortObject ) {
776 // eslint-disable-next-line jquery/no-each-util
777 $.each( sortObject, function ( columnIndex, order ) {
778 var orderIndex = ( order === 'desc' ) ? 1 : 0;
779 sortList.push( [ parseInt( columnIndex, 10 ), orderIndex ] );
780 } );
781 } );
782 return sortList;
783 }
784
785 /* Public scope */
786
787 $.tablesorter = {
788 defaultOptions: {
789 cssHeader: 'headerSort',
790 cssAsc: 'headerSortUp',
791 cssDesc: 'headerSortDown',
792 cssChildRow: 'expand-child',
793 sortMultiSortKey: 'shiftKey',
794 unsortableClass: 'unsortable',
795 parsers: [],
796 cancelSelection: true,
797 sortList: [],
798 headerList: [],
799 headerToColumns: [],
800 columnToHeader: [],
801 columns: 0
802 },
803
804 dateRegex: [],
805 monthNames: {},
806
807 /**
808 * @param {jQuery} $tables
809 * @param {Object} [settings]
810 * @return {jQuery}
811 */
812 construct: function ( $tables, settings ) {
813 return $tables.each( function ( i, table ) {
814 // Declare and cache.
815 var $headers, cache, config, sortCSS, sortMsg,
816 $table = $( table ),
817 firstTime = true;
818
819 // Quit if no tbody
820 if ( !table.tBodies ) {
821 return;
822 }
823 if ( !table.tHead ) {
824 // No thead found. Look for rows with <th>s and
825 // move them into a <thead> tag or a <tfoot> tag
826 emulateTHeadAndFoot( $table );
827
828 // Still no thead? Then quit
829 if ( !table.tHead ) {
830 return;
831 }
832 }
833 // The `sortable` class is used to identify tables which will become sortable
834 // If not used it will create a FOUC but it should be added since the sortable class
835 // is responsible for certain crucial style elements. If the class is already present
836 // this action will be harmless.
837 $table.addClass( 'jquery-tablesorter sortable' );
838
839 // Merge and extend
840 config = $.extend( {}, $.tablesorter.defaultOptions, settings );
841
842 // Save the settings where they read
843 $.data( table, 'tablesorter', { config: config } );
844
845 // Get the CSS class names, could be done elsewhere
846 sortCSS = [ config.cssAsc, config.cssDesc ];
847 // Messages tell the user what the *next* state will be
848 // so are in reverse order to the CSS classes.
849 sortMsg = [ mw.msg( 'sort-descending' ), mw.msg( 'sort-ascending' ) ];
850
851 // Build headers
852 $headers = buildHeaders( table, sortMsg );
853
854 // Grab and process locale settings.
855 buildTransformTable();
856 buildDateTable();
857
858 // Precaching regexps can bring 10 fold
859 // performance improvements in some browsers.
860 cacheRegexs();
861
862 function setupForFirstSort() {
863 var $tfoot, $sortbottoms;
864
865 firstTime = false;
866
867 // Defer buildCollationTable to first sort. As user and site scripts
868 // may customize tableSorterCollation but load after $.ready(), other
869 // scripts may call .tablesorter() before they have done the
870 // tableSorterCollation customizations.
871 buildCollationTable();
872
873 // Legacy fix of .sortbottoms
874 // Wrap them inside a tfoot (because that's what they actually want to be)
875 // and put the <tfoot> at the end of the <table>
876 $sortbottoms = $table.find( '> tbody > tr.sortbottom' );
877 if ( $sortbottoms.length ) {
878 $tfoot = $table.children( 'tfoot' );
879 if ( $tfoot.length ) {
880 $tfoot.eq( 0 ).prepend( $sortbottoms );
881 } else {
882 $table.append( $( '<tfoot>' ).append( $sortbottoms ) );
883 }
884 }
885
886 explodeRowspans( $table );
887 manageColspans( $table );
888
889 // Try to auto detect column type, and store in tables config
890 config.parsers = buildParserCache( table, $headers );
891 }
892
893 // Apply event handling to headers
894 // this is too big, perhaps break it out?
895 $headers.on( 'keypress click', function ( e ) {
896 var cell, $cell, columns, newSortList, i,
897 totalRows,
898 j, s, o;
899
900 if ( e.type === 'click' && e.target.nodeName.toLowerCase() === 'a' ) {
901 // The user clicked on a link inside a table header.
902 // Do nothing and let the default link click action continue.
903 return true;
904 }
905
906 if ( e.type === 'keypress' && e.which !== 13 ) {
907 // Only handle keypresses on the "Enter" key.
908 return true;
909 }
910
911 if ( firstTime ) {
912 setupForFirstSort();
913 }
914
915 // Build the cache for the tbody cells
916 // to share between calculations for this sort action.
917 // Re-calculated each time a sort action is performed due to possibility
918 // that sort values change. Shouldn't be too expensive, but if it becomes
919 // too slow an event based system should be implemented somehow where
920 // cells get event .change() and bubbles up to the <table> here
921 cache = buildCache( table );
922
923 totalRows = ( $table[ 0 ].tBodies[ 0 ] && $table[ 0 ].tBodies[ 0 ].rows.length ) || 0;
924 if ( totalRows > 0 ) {
925 cell = this;
926 $cell = $( cell );
927
928 // Get current column sort order
929 $cell.data( {
930 order: $cell.data( 'count' ) % 2,
931 count: $cell.data( 'count' ) + 1
932 } );
933
934 cell = this;
935 // Get current column index
936 columns = config.headerToColumns[ $cell.data( 'headerIndex' ) ];
937 newSortList = columns.map( function ( c ) {
938 return [ c, $cell.data( 'order' ) ];
939 } );
940 // Index of first column belonging to this header
941 i = columns[ 0 ];
942
943 if ( !e[ config.sortMultiSortKey ] ) {
944 // User only wants to sort on one column set
945 // Flush the sort list and add new columns
946 config.sortList = newSortList;
947 } else {
948 // Multi column sorting
949 // It is not possible for one column to belong to multiple headers,
950 // so this is okay - we don't need to check for every value in the columns array
951 if ( isValueInArray( i, config.sortList ) ) {
952 // The user has clicked on an already sorted column.
953 // Reverse the sorting direction for all tables.
954 for ( j = 0; j < config.sortList.length; j++ ) {
955 s = config.sortList[ j ];
956 o = config.headerList[ config.columnToHeader[ s[ 0 ] ] ];
957 if ( isValueInArray( s[ 0 ], newSortList ) ) {
958 $( o ).data( 'count', s[ 1 ] + 1 );
959 s[ 1 ] = $( o ).data( 'count' ) % 2;
960 }
961 }
962 } else {
963 // Add columns to sort list array
964 config.sortList = config.sortList.concat( newSortList );
965 }
966 }
967
968 // Reset order/counts of cells not affected by sorting
969 setHeadersOrder( $headers, config.sortList, config.headerToColumns );
970
971 // Set CSS for headers
972 setHeadersCss( $table[ 0 ], $headers, config.sortList, sortCSS, sortMsg, config.columnToHeader );
973 appendToTable(
974 $table[ 0 ], multisort( $table[ 0 ], config.sortList, cache )
975 );
976
977 // Stop normal event by returning false
978 return false;
979 }
980
981 // Cancel selection
982 } ).on( 'mousedown', function () {
983 if ( config.cancelSelection ) {
984 this.onselectstart = function () {
985 return false;
986 };
987 return false;
988 }
989 } );
990
991 /**
992 * Sorts the table. If no sorting is specified by passing a list of sort
993 * objects, the table is sorted according to the initial sorting order.
994 * Passing an empty array will reset sorting (basically just reset the headers
995 * making the table appear unsorted).
996 *
997 * @param {Array} [sortList] List of sort objects.
998 */
999 $table.data( 'tablesorter' ).sort = function ( sortList ) {
1000
1001 if ( firstTime ) {
1002 setupForFirstSort();
1003 }
1004
1005 if ( sortList === undefined ) {
1006 sortList = config.sortList;
1007 } else if ( sortList.length > 0 ) {
1008 sortList = convertSortList( sortList );
1009 }
1010
1011 // Set each column's sort count to be able to determine the correct sort
1012 // order when clicking on a header cell the next time
1013 setHeadersOrder( $headers, sortList, config.headerToColumns );
1014
1015 // re-build the cache for the tbody cells
1016 cache = buildCache( table );
1017
1018 // set css for headers
1019 setHeadersCss( table, $headers, sortList, sortCSS, sortMsg, config.columnToHeader );
1020
1021 // sort the table and append it to the dom
1022 appendToTable( table, multisort( table, sortList, cache ) );
1023 };
1024
1025 // sort initially
1026 if ( config.sortList.length > 0 ) {
1027 config.sortList = convertSortList( config.sortList );
1028 $table.data( 'tablesorter' ).sort();
1029 }
1030
1031 } );
1032 },
1033
1034 addParser: function ( parser ) {
1035 if ( !getParserById( parser.id ) ) {
1036 parsers.push( parser );
1037 }
1038 },
1039
1040 formatDigit: function ( s ) {
1041 var out, c, p, i;
1042 if ( ts.transformTable !== false ) {
1043 out = '';
1044 for ( p = 0; p < s.length; p++ ) {
1045 c = s.charAt( p );
1046 if ( c in ts.transformTable ) {
1047 out += ts.transformTable[ c ];
1048 } else {
1049 out += c;
1050 }
1051 }
1052 s = out;
1053 }
1054 i = parseFloat( s.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
1055 return isNaN( i ) ? -Infinity : i;
1056 },
1057
1058 formatFloat: function ( s ) {
1059 var i = parseFloat( s );
1060 return isNaN( i ) ? -Infinity : i;
1061 },
1062
1063 formatInt: function ( s ) {
1064 var i = parseInt( s, 10 );
1065 return isNaN( i ) ? -Infinity : i;
1066 },
1067
1068 clearTableBody: function ( table ) {
1069 $( table.tBodies[ 0 ] ).empty();
1070 },
1071
1072 getParser: function ( id ) {
1073 buildTransformTable();
1074 buildDateTable();
1075 cacheRegexs();
1076 buildCollationTable();
1077
1078 return getParserById( id );
1079 },
1080
1081 getParsers: function () { // for table diagnosis
1082 return parsers;
1083 }
1084 };
1085
1086 // Shortcut
1087 ts = $.tablesorter;
1088
1089 // Register as jQuery prototype method
1090 $.fn.tablesorter = function ( settings ) {
1091 return ts.construct( this, settings );
1092 };
1093
1094 // Add default parsers
1095 ts.addParser( {
1096 id: 'text',
1097 is: function () {
1098 return true;
1099 },
1100 format: function ( s ) {
1101 var tsc;
1102 s = s.toLowerCase().trim();
1103 if ( ts.collationRegex ) {
1104 tsc = ts.collationTable;
1105 s = s.replace( ts.collationRegex, function ( match ) {
1106 var r = tsc[ match ] ? tsc[ match ] : tsc[ match.toUpperCase() ];
1107 return r.toLowerCase();
1108 } );
1109 }
1110 return s;
1111 },
1112 type: 'text'
1113 } );
1114
1115 ts.addParser( {
1116 id: 'IPAddress',
1117 is: function ( s ) {
1118 return ts.rgx.IPAddress[ 0 ].test( s );
1119 },
1120 format: function ( s ) {
1121 var i, item,
1122 a = s.split( '.' ),
1123 r = '';
1124 for ( i = 0; i < a.length; i++ ) {
1125 item = a[ i ];
1126 if ( item.length === 1 ) {
1127 r += '00' + item;
1128 } else if ( item.length === 2 ) {
1129 r += '0' + item;
1130 } else {
1131 r += item;
1132 }
1133 }
1134 return $.tablesorter.formatFloat( r );
1135 },
1136 type: 'numeric'
1137 } );
1138
1139 ts.addParser( {
1140 id: 'currency',
1141 is: function ( s ) {
1142 return ts.rgx.currency[ 0 ].test( s );
1143 },
1144 format: function ( s ) {
1145 return $.tablesorter.formatDigit( s.replace( ts.rgx.currency[ 1 ], '' ) );
1146 },
1147 type: 'numeric'
1148 } );
1149
1150 ts.addParser( {
1151 id: 'url',
1152 is: function ( s ) {
1153 return ts.rgx.url[ 0 ].test( s );
1154 },
1155 format: function ( s ) {
1156 return s.replace( ts.rgx.url[ 1 ], '' ).trim();
1157 },
1158 type: 'text'
1159 } );
1160
1161 ts.addParser( {
1162 id: 'isoDate',
1163 is: function ( s ) {
1164 return ts.rgx.isoDate[ 0 ].test( s );
1165 },
1166 format: function ( s ) {
1167 var match, i, isodate, ms, hOffset, mOffset;
1168 match = s.match( ts.rgx.isoDate[ 0 ] );
1169 if ( match === null ) {
1170 // Otherwise a signed number with 1-4 digit is parsed as isoDate
1171 match = s.match( ts.rgx.isoDate[ 1 ] );
1172 }
1173 if ( !match ) {
1174 return -Infinity;
1175 }
1176 // Month and day
1177 for ( i = 2; i <= 4; i += 2 ) {
1178 if ( !match[ i ] || match[ i ].length === 0 ) {
1179 match[ i ] = 1;
1180 }
1181 }
1182 // Time
1183 for ( i = 6; i <= 15; i++ ) {
1184 if ( !match[ i ] || match[ i ].length === 0 ) {
1185 match[ i ] = '0';
1186 }
1187 }
1188 ms = parseFloat( match[ 11 ].replace( /,/, '.' ) ) * 1000;
1189 hOffset = $.tablesorter.formatInt( match[ 13 ] + match[ 14 ] );
1190 mOffset = $.tablesorter.formatInt( match[ 13 ] + match[ 15 ] );
1191
1192 isodate = new Date( 0 );
1193 // Because Date constructor changes year 0-99 to 1900-1999, use setUTCFullYear()
1194 isodate.setUTCFullYear( match[ 1 ], match[ 2 ] - 1, match[ 4 ] );
1195 isodate.setUTCHours( match[ 6 ] - hOffset, match[ 8 ] - mOffset, match[ 10 ], ms );
1196 return isodate.getTime();
1197 },
1198 type: 'numeric'
1199 } );
1200
1201 ts.addParser( {
1202 id: 'usLongDate',
1203 is: function ( s ) {
1204 return ts.rgx.usLongDate[ 0 ].test( s );
1205 },
1206 format: function ( s ) {
1207 return $.tablesorter.formatFloat( new Date( s ).getTime() );
1208 },
1209 type: 'numeric'
1210 } );
1211
1212 ts.addParser( {
1213 id: 'date',
1214 is: function ( s ) {
1215 return ( ts.dateRegex[ 0 ].test( s ) || ts.dateRegex[ 1 ].test( s ) || ts.dateRegex[ 2 ].test( s ) );
1216 },
1217 format: function ( s ) {
1218 var match, y;
1219 s = s.toLowerCase().trim();
1220
1221 if ( ( match = s.match( ts.dateRegex[ 0 ] ) ) !== null ) {
1222 if ( mw.config.get( 'wgDefaultDateFormat' ) === 'mdy' || mw.config.get( 'wgPageContentLanguage' ) === 'en' ) {
1223 s = [ match[ 3 ], match[ 1 ], match[ 2 ] ];
1224 } else if ( mw.config.get( 'wgDefaultDateFormat' ) === 'dmy' ) {
1225 s = [ match[ 3 ], match[ 2 ], match[ 1 ] ];
1226 } else {
1227 // If we get here, we don't know which order the dd-dd-dddd
1228 // date is in. So return something not entirely invalid.
1229 return '99999999';
1230 }
1231 } else if ( ( match = s.match( ts.dateRegex[ 1 ] ) ) !== null ) {
1232 s = [ match[ 3 ], String( ts.monthNames[ match[ 2 ] ] ), match[ 1 ] ];
1233 } else if ( ( match = s.match( ts.dateRegex[ 2 ] ) ) !== null ) {
1234 s = [ match[ 3 ], String( ts.monthNames[ match[ 1 ] ] ), match[ 2 ] ];
1235 } else {
1236 // Should never get here
1237 return '99999999';
1238 }
1239
1240 // Pad Month and Day
1241 if ( s[ 1 ].length === 1 ) {
1242 s[ 1 ] = '0' + s[ 1 ];
1243 }
1244 if ( s[ 2 ].length === 1 ) {
1245 s[ 2 ] = '0' + s[ 2 ];
1246 }
1247
1248 if ( ( y = parseInt( s[ 0 ], 10 ) ) < 100 ) {
1249 // Guestimate years without centuries
1250 if ( y < 30 ) {
1251 s[ 0 ] = 2000 + y;
1252 } else {
1253 s[ 0 ] = 1900 + y;
1254 }
1255 }
1256 while ( s[ 0 ].length < 4 ) {
1257 s[ 0 ] = '0' + s[ 0 ];
1258 }
1259 return parseInt( s.join( '' ), 10 );
1260 },
1261 type: 'numeric'
1262 } );
1263
1264 ts.addParser( {
1265 id: 'time',
1266 is: function ( s ) {
1267 return ts.rgx.time[ 0 ].test( s );
1268 },
1269 format: function ( s ) {
1270 return $.tablesorter.formatFloat( new Date( '2000/01/01 ' + s ).getTime() );
1271 },
1272 type: 'numeric'
1273 } );
1274
1275 ts.addParser( {
1276 id: 'number',
1277 is: function ( s ) {
1278 return $.tablesorter.numberRegex.test( s.trim() );
1279 },
1280 format: function ( s ) {
1281 return $.tablesorter.formatDigit( s );
1282 },
1283 type: 'numeric'
1284 } );
1285
1286 }() );