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