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