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