Merge "Drop zh-tw message "saveprefs""
[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{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/ )
744 ],
745 usLongDate: [
746 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)))$/ )
747 ],
748 time: [
749 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/ )
750 ]
751 };
752 }
753
754 /**
755 * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
756 * structure [ [ Integer , Integer ], ... ]
757 *
758 * @param sortObjects {Array} List of sort objects.
759 * @return {Array} List of internal sort definitions.
760 */
761
762 function convertSortList( sortObjects ) {
763 var sortList = [];
764 $.each( sortObjects, function ( i, sortObject ) {
765 $.each( sortObject, function ( columnIndex, order ) {
766 var orderIndex = ( order === 'desc' ) ? 1 : 0;
767 sortList.push( [ parseInt( columnIndex, 10 ), orderIndex ] );
768 } );
769 } );
770 return sortList;
771 }
772
773 /* Public scope */
774
775 $.tablesorter = {
776 defaultOptions: {
777 cssHeader: 'headerSort',
778 cssAsc: 'headerSortUp',
779 cssDesc: 'headerSortDown',
780 cssChildRow: 'expand-child',
781 sortMultiSortKey: 'shiftKey',
782 unsortableClass: 'unsortable',
783 parsers: [],
784 cancelSelection: true,
785 sortList: [],
786 headerList: [],
787 headerToColumns: [],
788 columnToHeader: [],
789 columns: 0
790 },
791
792 dateRegex: [],
793 monthNames: {},
794
795 /**
796 * @param {jQuery} $tables
797 * @param {Object} [settings]
798 */
799 construct: function ( $tables, settings ) {
800 return $tables.each( function ( i, table ) {
801 // Declare and cache.
802 var $headers, cache, config, sortCSS, sortMsg,
803 $table = $( table ),
804 firstTime = true;
805
806 // Quit if no tbody
807 if ( !table.tBodies ) {
808 return;
809 }
810 if ( !table.tHead ) {
811 // No thead found. Look for rows with <th>s and
812 // move them into a <thead> tag or a <tfoot> tag
813 emulateTHeadAndFoot( $table );
814
815 // Still no thead? Then quit
816 if ( !table.tHead ) {
817 return;
818 }
819 }
820 $table.addClass( 'jquery-tablesorter' );
821
822 // Merge and extend
823 config = $.extend( {}, $.tablesorter.defaultOptions, settings );
824
825 // Save the settings where they read
826 $.data( table, 'tablesorter', { config: config } );
827
828 // Get the CSS class names, could be done elsewhere
829 sortCSS = [ config.cssDesc, config.cssAsc ];
830 sortMsg = [ mw.msg( 'sort-descending' ), mw.msg( 'sort-ascending' ) ];
831
832 // Build headers
833 $headers = buildHeaders( table, sortMsg );
834
835 // Grab and process locale settings.
836 buildTransformTable();
837 buildDateTable();
838
839 // Precaching regexps can bring 10 fold
840 // performance improvements in some browsers.
841 cacheRegexs();
842
843 function setupForFirstSort() {
844 firstTime = false;
845
846 // Defer buildCollationTable to first sort. As user and site scripts
847 // may customize tableSorterCollation but load after $.ready(), other
848 // scripts may call .tablesorter() before they have done the
849 // tableSorterCollation customizations.
850 buildCollationTable();
851
852 // Legacy fix of .sortbottoms
853 // Wrap them inside a tfoot (because that's what they actually want to be)
854 // and put the <tfoot> at the end of the <table>
855 var $tfoot,
856 $sortbottoms = $table.find( '> tbody > tr.sortbottom' );
857 if ( $sortbottoms.length ) {
858 $tfoot = $table.children( 'tfoot' );
859 if ( $tfoot.length ) {
860 $tfoot.eq( 0 ).prepend( $sortbottoms );
861 } else {
862 $table.append( $( '<tfoot>' ).append( $sortbottoms ) );
863 }
864 }
865
866 explodeRowspans( $table );
867 manageColspans( $table );
868
869 // Try to auto detect column type, and store in tables config
870 config.parsers = buildParserCache( table, $headers );
871 }
872
873 // Apply event handling to headers
874 // this is too big, perhaps break it out?
875 $headers.on( 'keypress click', function ( e ) {
876 var cell, $cell, columns, newSortList, i,
877 totalRows,
878 j, s, o;
879
880 if ( e.type === 'click' && e.target.nodeName.toLowerCase() === 'a' ) {
881 // The user clicked on a link inside a table header.
882 // Do nothing and let the default link click action continue.
883 return true;
884 }
885
886 if ( e.type === 'keypress' && e.which !== 13 ) {
887 // Only handle keypresses on the "Enter" key.
888 return true;
889 }
890
891 if ( firstTime ) {
892 setupForFirstSort();
893 }
894
895 // Build the cache for the tbody cells
896 // to share between calculations for this sort action.
897 // Re-calculated each time a sort action is performed due to possiblity
898 // that sort values change. Shouldn't be too expensive, but if it becomes
899 // too slow an event based system should be implemented somehow where
900 // cells get event .change() and bubbles up to the <table> here
901 cache = buildCache( table );
902
903 totalRows = ( $table[ 0 ].tBodies[ 0 ] && $table[ 0 ].tBodies[ 0 ].rows.length ) || 0;
904 if ( totalRows > 0 ) {
905 cell = this;
906 $cell = $( cell );
907
908 // Get current column sort order
909 $cell.data( {
910 order: $cell.data( 'count' ) % 2,
911 count: $cell.data( 'count' ) + 1
912 } );
913
914 cell = this;
915 // Get current column index
916 columns = config.headerToColumns[ $cell.data( 'headerIndex' ) ];
917 newSortList = $.map( columns, function ( c ) {
918 // jQuery "helpfully" flattens the arrays...
919 return [ [ c, $cell.data( 'order' ) ] ];
920 } );
921 // Index of first column belonging to this header
922 i = columns[ 0 ];
923
924 if ( !e[ config.sortMultiSortKey ] ) {
925 // User only wants to sort on one column set
926 // Flush the sort list and add new columns
927 config.sortList = newSortList;
928 } else {
929 // Multi column sorting
930 // It is not possible for one column to belong to multiple headers,
931 // so this is okay - we don't need to check for every value in the columns array
932 if ( isValueInArray( i, config.sortList ) ) {
933 // The user has clicked on an already sorted column.
934 // Reverse the sorting direction for all tables.
935 for ( j = 0; j < config.sortList.length; j++ ) {
936 s = config.sortList[ j ];
937 o = config.headerList[ config.columnToHeader[ s[ 0 ] ] ];
938 if ( isValueInArray( s[ 0 ], newSortList ) ) {
939 $( o ).data( 'count', s[ 1 ] + 1 );
940 s[ 1 ] = $( o ).data( 'count' ) % 2;
941 }
942 }
943 } else {
944 // Add columns to sort list array
945 config.sortList = config.sortList.concat( newSortList );
946 }
947 }
948
949 // Reset order/counts of cells not affected by sorting
950 setHeadersOrder( $headers, config.sortList, config.headerToColumns );
951
952 // Set CSS for headers
953 setHeadersCss( $table[ 0 ], $headers, config.sortList, sortCSS, sortMsg, config.columnToHeader );
954 appendToTable(
955 $table[ 0 ], multisort( $table[ 0 ], config.sortList, cache )
956 );
957
958 // Stop normal event by returning false
959 return false;
960 }
961
962 // Cancel selection
963 } ).mousedown( function () {
964 if ( config.cancelSelection ) {
965 this.onselectstart = function () {
966 return false;
967 };
968 return false;
969 }
970 } );
971
972 /**
973 * Sorts the table. If no sorting is specified by passing a list of sort
974 * objects, the table is sorted according to the initial sorting order.
975 * Passing an empty array will reset sorting (basically just reset the headers
976 * making the table appear unsorted).
977 *
978 * @param {Array} [sortList] List of sort objects.
979 */
980 $table.data( 'tablesorter' ).sort = function ( sortList ) {
981
982 if ( firstTime ) {
983 setupForFirstSort();
984 }
985
986 if ( sortList === undefined ) {
987 sortList = config.sortList;
988 } else if ( sortList.length > 0 ) {
989 sortList = convertSortList( sortList );
990 }
991
992 // Set each column's sort count to be able to determine the correct sort
993 // order when clicking on a header cell the next time
994 setHeadersOrder( $headers, sortList, config.headerToColumns );
995
996 // re-build the cache for the tbody cells
997 cache = buildCache( table );
998
999 // set css for headers
1000 setHeadersCss( table, $headers, sortList, sortCSS, sortMsg, config.columnToHeader );
1001
1002 // sort the table and append it to the dom
1003 appendToTable( table, multisort( table, sortList, cache ) );
1004 };
1005
1006 // sort initially
1007 if ( config.sortList.length > 0 ) {
1008 config.sortList = convertSortList( config.sortList );
1009 $table.data( 'tablesorter' ).sort();
1010 }
1011
1012 } );
1013 },
1014
1015 addParser: function ( parser ) {
1016 var i,
1017 len = parsers.length,
1018 a = true;
1019 for ( i = 0; i < len; i++ ) {
1020 if ( parsers[ i ].id.toLowerCase() === parser.id.toLowerCase() ) {
1021 a = false;
1022 }
1023 }
1024 if ( a ) {
1025 parsers.push( parser );
1026 }
1027 },
1028
1029 formatDigit: function ( s ) {
1030 var out, c, p, i;
1031 if ( ts.transformTable !== false ) {
1032 out = '';
1033 for ( p = 0; p < s.length; p++ ) {
1034 c = s.charAt( p );
1035 if ( c in ts.transformTable ) {
1036 out += ts.transformTable[ c ];
1037 } else {
1038 out += c;
1039 }
1040 }
1041 s = out;
1042 }
1043 i = parseFloat( s.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
1044 return isNaN( i ) ? 0 : i;
1045 },
1046
1047 formatFloat: function ( s ) {
1048 var i = parseFloat( s );
1049 return isNaN( i ) ? 0 : i;
1050 },
1051
1052 formatInt: function ( s ) {
1053 var i = parseInt( s, 10 );
1054 return isNaN( i ) ? 0 : i;
1055 },
1056
1057 clearTableBody: function ( table ) {
1058 $( table.tBodies[ 0 ] ).empty();
1059 },
1060
1061 getParser: function ( id ) {
1062 buildTransformTable();
1063 buildDateTable();
1064 cacheRegexs();
1065 buildCollationTable();
1066
1067 return getParserById( id );
1068 },
1069
1070 getParsers: function () { // for table diagnosis
1071 return parsers;
1072 }
1073 };
1074
1075 // Shortcut
1076 ts = $.tablesorter;
1077
1078 // Register as jQuery prototype method
1079 $.fn.tablesorter = function ( settings ) {
1080 return ts.construct( this, settings );
1081 };
1082
1083 // Add default parsers
1084 ts.addParser( {
1085 id: 'text',
1086 is: function () {
1087 return true;
1088 },
1089 format: function ( s ) {
1090 s = $.trim( s.toLowerCase() );
1091 if ( ts.collationRegex ) {
1092 var tsc = ts.collationTable;
1093 s = s.replace( ts.collationRegex, function ( match ) {
1094 var r = tsc[ match ] ? tsc[ match ] : tsc[ match.toUpperCase() ];
1095 return r.toLowerCase();
1096 } );
1097 }
1098 return s;
1099 },
1100 type: 'text'
1101 } );
1102
1103 ts.addParser( {
1104 id: 'IPAddress',
1105 is: function ( s ) {
1106 return ts.rgx.IPAddress[ 0 ].test( s );
1107 },
1108 format: function ( s ) {
1109 var i, item,
1110 a = s.split( '.' ),
1111 r = '',
1112 len = a.length;
1113 for ( i = 0; i < len; i++ ) {
1114 item = a[ i ];
1115 if ( item.length === 1 ) {
1116 r += '00' + item;
1117 } else if ( item.length === 2 ) {
1118 r += '0' + item;
1119 } else {
1120 r += item;
1121 }
1122 }
1123 return $.tablesorter.formatFloat( r );
1124 },
1125 type: 'numeric'
1126 } );
1127
1128 ts.addParser( {
1129 id: 'currency',
1130 is: function ( s ) {
1131 return ts.rgx.currency[ 0 ].test( s );
1132 },
1133 format: function ( s ) {
1134 return $.tablesorter.formatDigit( s.replace( ts.rgx.currency[ 1 ], '' ) );
1135 },
1136 type: 'numeric'
1137 } );
1138
1139 ts.addParser( {
1140 id: 'url',
1141 is: function ( s ) {
1142 return ts.rgx.url[ 0 ].test( s );
1143 },
1144 format: function ( s ) {
1145 return $.trim( s.replace( ts.rgx.url[ 1 ], '' ) );
1146 },
1147 type: 'text'
1148 } );
1149
1150 ts.addParser( {
1151 id: 'isoDate',
1152 is: function ( s ) {
1153 return ts.rgx.isoDate[ 0 ].test( s );
1154 },
1155 format: function ( s ) {
1156 return $.tablesorter.formatFloat( ( s !== '' ) ? new Date( s.replace(
1157 new RegExp( /-/g ), '/' ) ).getTime() : '0' );
1158 },
1159 type: 'numeric'
1160 } );
1161
1162 ts.addParser( {
1163 id: 'usLongDate',
1164 is: function ( s ) {
1165 return ts.rgx.usLongDate[ 0 ].test( s );
1166 },
1167 format: function ( s ) {
1168 return $.tablesorter.formatFloat( new Date( s ).getTime() );
1169 },
1170 type: 'numeric'
1171 } );
1172
1173 ts.addParser( {
1174 id: 'date',
1175 is: function ( s ) {
1176 return ( ts.dateRegex[ 0 ].test( s ) || ts.dateRegex[ 1 ].test( s ) || ts.dateRegex[ 2 ].test( s ) );
1177 },
1178 format: function ( s ) {
1179 var match, y;
1180 s = $.trim( s.toLowerCase() );
1181
1182 if ( ( match = s.match( ts.dateRegex[ 0 ] ) ) !== null ) {
1183 if ( mw.config.get( 'wgDefaultDateFormat' ) === 'mdy' || mw.config.get( 'wgPageContentLanguage' ) === 'en' ) {
1184 s = [ match[ 3 ], match[ 1 ], match[ 2 ] ];
1185 } else if ( mw.config.get( 'wgDefaultDateFormat' ) === 'dmy' ) {
1186 s = [ match[ 3 ], match[ 2 ], match[ 1 ] ];
1187 } else {
1188 // If we get here, we don't know which order the dd-dd-dddd
1189 // date is in. So return something not entirely invalid.
1190 return '99999999';
1191 }
1192 } else if ( ( match = s.match( ts.dateRegex[ 1 ] ) ) !== null ) {
1193 s = [ match[ 3 ], String( ts.monthNames[ match[ 2 ] ] ), match[ 1 ] ];
1194 } else if ( ( match = s.match( ts.dateRegex[ 2 ] ) ) !== null ) {
1195 s = [ match[ 3 ], String( ts.monthNames[ match[ 1 ] ] ), match[ 2 ] ];
1196 } else {
1197 // Should never get here
1198 return '99999999';
1199 }
1200
1201 // Pad Month and Day
1202 if ( s[ 1 ].length === 1 ) {
1203 s[ 1 ] = '0' + s[ 1 ];
1204 }
1205 if ( s[ 2 ].length === 1 ) {
1206 s[ 2 ] = '0' + s[ 2 ];
1207 }
1208
1209 if ( ( y = parseInt( s[ 0 ], 10 ) ) < 100 ) {
1210 // Guestimate years without centuries
1211 if ( y < 30 ) {
1212 s[ 0 ] = 2000 + y;
1213 } else {
1214 s[ 0 ] = 1900 + y;
1215 }
1216 }
1217 while ( s[ 0 ].length < 4 ) {
1218 s[ 0 ] = '0' + s[ 0 ];
1219 }
1220 return parseInt( s.join( '' ), 10 );
1221 },
1222 type: 'numeric'
1223 } );
1224
1225 ts.addParser( {
1226 id: 'time',
1227 is: function ( s ) {
1228 return ts.rgx.time[ 0 ].test( s );
1229 },
1230 format: function ( s ) {
1231 return $.tablesorter.formatFloat( new Date( '2000/01/01 ' + s ).getTime() );
1232 },
1233 type: 'numeric'
1234 } );
1235
1236 ts.addParser( {
1237 id: 'number',
1238 is: function ( s ) {
1239 return $.tablesorter.numberRegex.test( $.trim( s ) );
1240 },
1241 format: function ( s ) {
1242 return $.tablesorter.formatDigit( s );
1243 },
1244 type: 'numeric'
1245 } );
1246
1247 }( jQuery, mediaWiki ) );