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