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