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