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