Merge "Improve documentation for "pipe trick""
[lhc/web/wiklou.git] / resources / 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, wgMonthNames, wgMonthNamesShort,
12 * wgDefaultDateFormat, wgContentLanguage)
13 * Uses 'tableSorterCollation' in mw.config (if available)
14 */
15 /**
16 *
17 * @description Create a sortable table with multi-column sorting capabilitys
18 *
19 * @example $( 'table' ).tablesorter();
20 * @desc Create a simple tablesorter interface.
21 *
22 * @example $( 'table' ).tablesorter( { sortList: [ { 0: 'desc' }, { 1: 'asc' } ] } );
23 * @desc Create a tablesorter interface initially sorting on the first and second column.
24 *
25 * @option String cssHeader ( optional ) A string of the class name to be appended
26 * to sortable tr elements in the thead of the table. Default value:
27 * "header"
28 *
29 * @option String cssAsc ( optional ) A string of the class name to be appended to
30 * sortable tr elements in the thead on a ascending sort. Default value:
31 * "headerSortUp"
32 *
33 * @option String cssDesc ( optional ) A string of the class name to be appended
34 * to sortable tr elements in the thead on a descending sort. Default
35 * value: "headerSortDown"
36 *
37 * @option String sortInitialOrder ( optional ) A string of the inital sorting
38 * order can be asc or desc. Default value: "asc"
39 *
40 * @option String sortMultisortKey ( optional ) A string of the multi-column sort
41 * key. Default value: "shiftKey"
42 *
43 * @option Boolean sortLocaleCompare ( optional ) Boolean flag indicating whatever
44 * to use String.localeCampare method or not. Set to false.
45 *
46 * @option Boolean cancelSelection ( optional ) Boolean flag indicating if
47 * tablesorter should cancel selection of the table headers text.
48 * Default value: true
49 *
50 * @option Array sortList ( optional ) An array containing objects specifying sorting.
51 * By passing more than one object, multi-sorting will be applied. Object structure:
52 * { <Integer column index>: <String 'asc' or 'desc'> }
53 * Default value: []
54 *
55 * @option Boolean debug ( optional ) Boolean flag indicating if tablesorter
56 * should display debuging information usefull for development.
57 *
58 * @event sortEnd.tablesorter: Triggered as soon as any sorting has been applied.
59 *
60 * @type jQuery
61 *
62 * @name tablesorter
63 *
64 * @cat Plugins/Tablesorter
65 *
66 * @author Christian Bach/christian.bach@polyester.se
67 */
68
69 ( function ( $, mw ) {
70 /*jshint onevar:false */
71
72 /* Local scope */
73
74 var ts,
75 parsers = [];
76
77 /* Parser utility functions */
78
79 function getParserById( name ) {
80 var len = parsers.length;
81 for ( var i = 0; i < len; i++ ) {
82 if ( parsers[i].id.toLowerCase() === name.toLowerCase() ) {
83 return parsers[i];
84 }
85 }
86 return false;
87 }
88
89 function getElementText( node ) {
90 var $node = $( node ),
91 // Use data-sort-value attribute.
92 // Use data() instead of attr() so that live value changes
93 // are processed as well (bug 38152).
94 data = $node.data( 'sortValue' );
95
96 if ( data !== null && data !== undefined ) {
97 // Cast any numbers or other stuff to a string, methods
98 // like charAt, toLowerCase and split are expected.
99 return String( data );
100 } else {
101 return $node.text();
102 }
103 }
104
105 function getTextFromRowAndCellIndex( rows, rowIndex, cellIndex ) {
106 if ( rows[rowIndex] && rows[rowIndex].cells[cellIndex] ) {
107 return $.trim( getElementText( rows[rowIndex].cells[cellIndex] ) );
108 } else {
109 return '';
110 }
111 }
112
113 function detectParserForColumn( table, rows, cellIndex ) {
114 var l = parsers.length,
115 nodeValue,
116 // Start with 1 because 0 is the fallback parser
117 i = 1,
118 rowIndex = 0,
119 concurrent = 0,
120 needed = ( rows.length > 4 ) ? 5 : rows.length;
121
122 while( i < l ) {
123 nodeValue = getTextFromRowAndCellIndex( rows, rowIndex, cellIndex );
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 rows = table.tBodies[0].rows,
154 sortType,
155 parsers = [];
156
157 if ( rows[0] ) {
158
159 var cells = rows[0].cells,
160 len = cells.length,
161 i, parser;
162
163 for ( i = 0; i < len; i++ ) {
164 parser = false;
165 sortType = $headers.eq( i ).data( 'sortType' );
166 if ( sortType !== undefined ) {
167 parser = getParserById( sortType );
168 }
169
170 if ( parser === false ) {
171 parser = detectParserForColumn( table, rows, i );
172 }
173
174 parsers.push( parser );
175 }
176 }
177 return parsers;
178 }
179
180 /* Other utility functions */
181
182 function buildCache( table ) {
183 var 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 parsers = table.config.parsers,
186 cache = {
187 row: [],
188 normalized: []
189 };
190
191 for ( var i = 0; i < totalRows; ++i ) {
192
193 // Add the table data to main data array
194 var $row = $( table.tBodies[0].rows[i] ),
195 cols = [];
196
197 // if this is a child row, add it to the last row's children and
198 // continue to the next row
199 if ( $row.hasClass( table.config.cssChildRow ) ) {
200 cache.row[cache.row.length - 1] = cache.row[cache.row.length - 1].add( $row );
201 // go to the next for loop
202 continue;
203 }
204
205 cache.row.push( $row );
206
207 for ( var j = 0; j < totalCells; ++j ) {
208 cols.push( parsers[j].format( getElementText( $row[0].cells[j] ), table, $row[0].cells[j] ) );
209 }
210
211 cols.push( cache.normalized.length ); // add position for rowCache
212 cache.normalized.push( cols );
213 cols = null;
214 }
215
216 return cache;
217 }
218
219 function appendToTable( table, cache ) {
220 var row = cache.row,
221 normalized = cache.normalized,
222 totalRows = normalized.length,
223 checkCell = ( normalized[0].length - 1 ),
224 fragment = document.createDocumentFragment();
225
226 for ( var i = 0; i < totalRows; i++ ) {
227 var pos = normalized[i][checkCell];
228
229 var l = row[pos].length;
230
231 for ( var j = 0; j < l; j++ ) {
232 fragment.appendChild( row[pos][j] );
233 }
234
235 }
236 table.tBodies[0].appendChild( fragment );
237
238 $( table ).trigger( 'sortEnd.tablesorter' );
239 }
240
241 /**
242 * Find all header rows in a thead-less table and put them in a <thead> tag.
243 * This only treats a row as a header row if it contains only <th>s (no <td>s)
244 * and if it is preceded entirely by header rows. The algorithm stops when
245 * it encounters the first non-header row.
246 *
247 * After this, it will look at all rows at the bottom for footer rows
248 * And place these in a tfoot using similar rules.
249 * @param $table jQuery object for a <table>
250 */
251 function emulateTHeadAndFoot( $table ) {
252 var $rows = $table.find( '> tbody > tr' );
253 if( !$table.get(0).tHead ) {
254 var $thead = $( '<thead>' );
255 $rows.each( function () {
256 if ( $(this).children( 'td' ).length > 0 ) {
257 // This row contains a <td>, so it's not a header row
258 // Stop here
259 return false;
260 }
261 $thead.append( this );
262 } );
263 $table.find(' > tbody:first').before( $thead );
264 }
265 if( !$table.get(0).tFoot ) {
266 var $tfoot = $( '<tfoot>' );
267 var len = $rows.length;
268 for ( var i = len-1; i >= 0; i-- ) {
269 if( $( $rows[i] ).children( 'td' ).length > 0 ){
270 break;
271 }
272 $tfoot.prepend( $( $rows[i] ));
273 }
274 $table.append( $tfoot );
275 }
276 }
277
278 function buildHeaders( table, msg ) {
279 var maxSeen = 0,
280 longest,
281 realCellIndex = 0,
282 $tableHeaders = $( 'thead:eq(0) > tr', table );
283 if ( $tableHeaders.length > 1 ) {
284 $tableHeaders.each( function () {
285 if ( this.cells.length > maxSeen ) {
286 maxSeen = this.cells.length;
287 longest = this;
288 }
289 });
290 $tableHeaders = $( longest );
291 }
292 $tableHeaders = $tableHeaders.children( 'th' ).each( function ( index ) {
293 this.column = realCellIndex;
294
295 var colspan = this.colspan;
296 colspan = colspan ? parseInt( colspan, 10 ) : 1;
297 realCellIndex += colspan;
298
299 this.order = 0;
300 this.count = 0;
301
302 if ( $( this ).is( '.unsortable' ) ) {
303 this.sortDisabled = true;
304 }
305
306 if ( !this.sortDisabled ) {
307 $( this ).addClass( table.config.cssHeader ).attr( 'title', msg[1] );
308 }
309
310 // add cell to headerList
311 table.config.headerList[index] = this;
312 } );
313
314 return $tableHeaders;
315
316 }
317
318 function isValueInArray( v, a ) {
319 var l = a.length;
320 for ( var i = 0; i < l; i++ ) {
321 if ( a[i][0] === v ) {
322 return true;
323 }
324 }
325 return false;
326 }
327
328 function setHeadersCss( table, $headers, list, css, msg, columnToHeader ) {
329 // Remove all header information and reset titles to default message
330 $headers.removeClass( css[0] ).removeClass( css[1] ).attr( 'title', msg[1] );
331
332 for ( var i = 0; i < list.length; i++ ) {
333 $headers.eq( columnToHeader[ list[i][0] ] )
334 .addClass( css[ list[i][1] ] )
335 .attr( 'title', msg[ list[i][1] ] );
336 }
337 }
338
339 function sortText( a, b ) {
340 return ( (a < b) ? -1 : ((a > b) ? 1 : 0) );
341 }
342
343 function sortTextDesc( a, b ) {
344 return ( (b < a) ? -1 : ((b > a) ? 1 : 0) );
345 }
346
347 function multisort( table, sortList, cache ) {
348 var sortFn = [];
349 var len = sortList.length;
350 for ( var i = 0; i < len; i++ ) {
351 sortFn[i] = ( sortList[i][1] ) ? sortTextDesc : sortText;
352 }
353 cache.normalized.sort( function ( array1, array2 ) {
354 var col, ret;
355 for ( var i = 0; i < len; i++ ) {
356 col = sortList[i][0];
357 ret = sortFn[i].call( this, array1[col], array2[col] );
358 if ( ret !== 0 ) {
359 return ret;
360 }
361 }
362 // Fall back to index number column to ensure stable sort
363 return sortText.call( this, array1[array1.length - 1], array2[array2.length - 1] );
364 } );
365 return cache;
366 }
367
368 function buildTransformTable() {
369 var digits = '0123456789,.'.split( '' );
370 var separatorTransformTable = mw.config.get( 'wgSeparatorTransformTable' );
371 var digitTransformTable = mw.config.get( 'wgDigitTransformTable' );
372 if ( separatorTransformTable === null || ( separatorTransformTable[0] === '' && digitTransformTable[2] === '' ) ) {
373 ts.transformTable = false;
374 } else {
375 ts.transformTable = {};
376
377 // Unpack the transform table
378 var ascii = separatorTransformTable[0].split( '\t' ).concat( digitTransformTable[0].split( '\t' ) );
379 var localised = separatorTransformTable[1].split( '\t' ).concat( digitTransformTable[1].split( '\t' ) );
380
381 // Construct regex for number identification
382 for ( var i = 0; i < ascii.length; i++ ) {
383 ts.transformTable[localised[i]] = ascii[i];
384 digits.push( $.escapeRE( localised[i] ) );
385 }
386 }
387 var digitClass = '[' + digits.join( '', digits ) + ']';
388
389 // We allow a trailing percent sign, which we just strip. This works fine
390 // if percents and regular numbers aren't being mixed.
391 ts.numberRegex = new RegExp('^(' + '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
392 '|' + '[-+\u2212]?' + digitClass + '+[\\s\\xa0]*%?' + // Generic localised
393 ')$', 'i');
394 }
395
396 function buildDateTable() {
397 var regex = [];
398 ts.monthNames = {};
399
400 for ( var i = 1; i < 13; i++ ) {
401 var name = mw.config.get( 'wgMonthNames' )[i].toLowerCase();
402 ts.monthNames[name] = i;
403 regex.push( $.escapeRE( name ) );
404 name = mw.config.get( 'wgMonthNamesShort' )[i].toLowerCase().replace( '.', '' );
405 ts.monthNames[name] = i;
406 regex.push( $.escapeRE( name ) );
407 }
408
409 // Build piped string
410 regex = regex.join( '|' );
411
412 // Build RegEx
413 // Any date formated with . , ' - or /
414 ts.dateRegex[0] = new RegExp( /^\s*(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{2,4})\s*?/i);
415
416 // Written Month name, dmy
417 ts.dateRegex[1] = new RegExp( '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]*(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]*(\\d{2,4})\\s*$', 'i' );
418
419 // Written Month name, mdy
420 ts.dateRegex[2] = new RegExp( '^\\s*(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]*(\\d{1,2})[\\,\\.\\-\\/\'\\s]*(\\d{2,4})\\s*$', 'i' );
421
422 }
423
424 function explodeRowspans( $table ) {
425 // Split multi row cells into multiple cells with the same content
426 $table.find( '> tbody > tr > [rowspan]' ).each(function () {
427 var rowSpan = this.rowSpan;
428 this.rowSpan = 1;
429 var cell = $( this );
430 var next = cell.parent().nextAll();
431 for ( var i = 0; i < rowSpan - 1; i++ ) {
432 var td = next.eq( i ).children( 'td' );
433 if ( !td.length ) {
434 next.eq( i ).append( cell.clone() );
435 } else if ( this.cellIndex === 0 ) {
436 td.eq( this.cellIndex ).before( cell.clone() );
437 } else {
438 td.eq( this.cellIndex - 1 ).after( cell.clone() );
439 }
440 }
441 });
442 }
443
444 function buildCollationTable() {
445 ts.collationTable = mw.config.get( 'tableSorterCollation' );
446 ts.collationRegex = null;
447 if ( ts.collationTable ) {
448 var keys = [];
449
450 // Build array of key names
451 for ( var key in ts.collationTable ) {
452 if ( ts.collationTable.hasOwnProperty(key) ) { //to be safe
453 keys.push(key);
454 }
455 }
456 if (keys.length) {
457 ts.collationRegex = new RegExp( '[' + keys.join( '' ) + ']', 'ig' );
458 }
459 }
460 }
461
462 function cacheRegexs() {
463 if ( ts.rgx ) {
464 return;
465 }
466 ts.rgx = {
467 IPAddress: [
468 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/)
469 ],
470 currency: [
471 new RegExp( /(^[£$€¥]|[£$€¥]$)/),
472 new RegExp( /[£$€¥]/g)
473 ],
474 url: [
475 new RegExp( /^(https?|ftp|file):\/\/$/),
476 new RegExp( /(https?|ftp|file):\/\//)
477 ],
478 isoDate: [
479 new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/)
480 ],
481 usLongDate: [
482 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)))$/)
483 ],
484 time: [
485 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/)
486 ]
487 };
488 }
489
490 /**
491 * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
492 * structure [ [ Integer , Integer ], ... ]
493 *
494 * @param sortObjects {Array} List of sort objects.
495 * @return {Array} List of internal sort definitions.
496 */
497
498 function convertSortList( sortObjects ) {
499 var sortList = [];
500 $.each( sortObjects, function( i, sortObject ) {
501 $.each ( sortObject, function( columnIndex, order ) {
502 var orderIndex = ( order === 'desc' ) ? 1 : 0;
503 sortList.push( [columnIndex, orderIndex] );
504 } );
505 } );
506 return sortList;
507 }
508
509 /* Public scope */
510
511 $.tablesorter = {
512
513 defaultOptions: {
514 cssHeader: 'headerSort',
515 cssAsc: 'headerSortUp',
516 cssDesc: 'headerSortDown',
517 cssChildRow: 'expand-child',
518 sortInitialOrder: 'asc',
519 sortMultiSortKey: 'shiftKey',
520 sortLocaleCompare: false,
521 parsers: {},
522 widgets: [],
523 headers: {},
524 cancelSelection: true,
525 sortList: [],
526 headerList: [],
527 selectorHeaders: 'thead tr:eq(0) th',
528 debug: false
529 },
530
531 dateRegex: [],
532 monthNames: {},
533
534 /**
535 * @param $tables {jQuery}
536 * @param settings {Object} (optional)
537 */
538 construct: function ( $tables, settings ) {
539 return $tables.each( function ( i, table ) {
540 // Declare and cache.
541 var $headers, cache, config,
542 headerToColumns, columnToHeader, colspanOffset,
543 $table = $( table ),
544 firstTime = true;
545
546 // Quit if no tbody
547 if ( !table.tBodies ) {
548 return;
549 }
550 if ( !table.tHead ) {
551 // No thead found. Look for rows with <th>s and
552 // move them into a <thead> tag or a <tfoot> tag
553 emulateTHeadAndFoot( $table );
554
555 // Still no thead? Then quit
556 if ( !table.tHead ) {
557 return;
558 }
559 }
560 $table.addClass( 'jquery-tablesorter' );
561
562 // FIXME config should probably not be stored in the plain table node
563 // New config object.
564 table.config = {};
565
566 // Merge and extend.
567 config = $.extend( table.config, $.tablesorter.defaultOptions, settings );
568
569 // Save the settings where they read
570 $.data( table, 'tablesorter', { config: config } );
571
572 // Get the CSS class names, could be done else where.
573 var sortCSS = [ config.cssDesc, config.cssAsc ];
574 var sortMsg = [ mw.msg( 'sort-descending' ), mw.msg( 'sort-ascending' ) ];
575
576 // Build headers
577 $headers = buildHeaders( table, sortMsg );
578
579 // Grab and process locale settings
580 buildTransformTable();
581 buildDateTable();
582 buildCollationTable();
583
584 // Precaching regexps can bring 10 fold
585 // performance improvements in some browsers.
586 cacheRegexs();
587
588 function setupForFirstSort() {
589 firstTime = false;
590
591 // Legacy fix of .sortbottoms
592 // Wrap them inside inside a tfoot (because that's what they actually want to be) &
593 // and put the <tfoot> at the end of the <table>
594 var $sortbottoms = $table.find( '> tbody > tr.sortbottom' );
595 if ( $sortbottoms.length ) {
596 var $tfoot = $table.children( 'tfoot' );
597 if ( $tfoot.length ) {
598 $tfoot.eq(0).prepend( $sortbottoms );
599 } else {
600 $table.append( $( '<tfoot>' ).append( $sortbottoms ) );
601 }
602 }
603
604 explodeRowspans( $table );
605
606 // try to auto detect column type, and store in tables config
607 table.config.parsers = buildParserCache( table, $headers );
608 }
609
610 // as each header can span over multiple columns (using colspan=N),
611 // we have to bidirectionally map headers to their columns and columns to their headers
612 headerToColumns = [];
613 columnToHeader = [];
614 colspanOffset = 0;
615 $headers.each( function ( headerIndex ) {
616 var columns = [];
617 for ( var i = 0; i < this.colSpan; i++ ) {
618 columnToHeader[ colspanOffset + i ] = headerIndex;
619 columns.push( colspanOffset + i );
620 }
621
622 headerToColumns[ headerIndex ] = columns;
623 colspanOffset += this.colSpan;
624 } );
625
626 // Apply event handling to headers
627 // this is too big, perhaps break it out?
628 $headers.filter( ':not(.unsortable)' ).click( function ( e ) {
629 if ( e.target.nodeName.toLowerCase() === 'a' ) {
630 // The user clicked on a link inside a table header
631 // Do nothing and let the default link click action continue
632 return true;
633 }
634
635 if ( firstTime ) {
636 setupForFirstSort();
637 }
638
639 // Build the cache for the tbody cells
640 // to share between calculations for this sort action.
641 // Re-calculated each time a sort action is performed due to possiblity
642 // that sort values change. Shouldn't be too expensive, but if it becomes
643 // too slow an event based system should be implemented somehow where
644 // cells get event .change() and bubbles up to the <table> here
645 cache = buildCache( table );
646
647 var totalRows = ( $table[0].tBodies[0] && $table[0].tBodies[0].rows.length ) || 0;
648 if ( !table.sortDisabled && totalRows > 0 ) {
649 // Get current column sort order
650 this.order = this.count % 2;
651 this.count++;
652
653 var cell = this;
654 // Get current column index
655 var columns = headerToColumns[this.column];
656 var newSortList = $.map( columns, function (c) {
657 // jQuery "helpfully" flattens the arrays...
658 return [[c, cell.order]];
659 });
660 // Index of first column belonging to this header
661 var i = columns[0];
662
663 if ( !e[config.sortMultiSortKey] ) {
664 // User only wants to sort on one column set
665 // Flush the sort list and add new columns
666 config.sortList = newSortList;
667 } else {
668 // Multi column sorting
669 // It is not possible for one column to belong to multiple headers,
670 // so this is okay - we don't need to check for every value in the columns array
671 if ( isValueInArray( i, config.sortList ) ) {
672 // The user has clicked on an already sorted column.
673 // Reverse the sorting direction for all tables.
674 for ( var j = 0; j < config.sortList.length; j++ ) {
675 var s = config.sortList[j],
676 o = config.headerList[s[0]];
677 if ( isValueInArray( s[0], newSortList ) ) {
678 o.count = s[1];
679 o.count++;
680 s[1] = o.count % 2;
681 }
682 }
683 } else {
684 // Add columns to sort list array
685 config.sortList = config.sortList.concat( newSortList );
686 }
687 }
688
689 // Set CSS for headers
690 setHeadersCss( $table[0], $headers, config.sortList, sortCSS, sortMsg, columnToHeader );
691 appendToTable(
692 $table[0], multisort( $table[0], config.sortList, cache )
693 );
694
695 // Stop normal event by returning false
696 return false;
697 }
698
699 // Cancel selection
700 } ).mousedown( function () {
701 if ( config.cancelSelection ) {
702 this.onselectstart = function () {
703 return false;
704 };
705 return false;
706 }
707 } );
708
709 /**
710 * Sorts the table. If no sorting is specified by passing a list of sort
711 * objects, the table is sorted according to the initial sorting order.
712 * Passing an empty array will reset sorting (basically just reset the headers
713 * making the table appear unsorted).
714 *
715 * @param sortList {Array} (optional) List of sort objects.
716 */
717 $table.data( 'tablesorter' ).sort = function( sortList ) {
718
719 if ( firstTime ) {
720 setupForFirstSort();
721 }
722
723 if ( sortList === undefined ) {
724 sortList = config.sortList;
725 } else if ( sortList.length > 0 ) {
726 sortList = convertSortList( sortList );
727 }
728
729 // re-build the cache for the tbody cells
730 cache = buildCache( table );
731
732 // set css for headers
733 setHeadersCss( table, $headers, sortList, sortCSS, sortMsg, columnToHeader );
734
735 // sort the table and append it to the dom
736 appendToTable( table, multisort( table, sortList, cache ) );
737 };
738
739 // sort initially
740 if ( config.sortList.length > 0 ) {
741 setupForFirstSort();
742 config.sortList = convertSortList( config.sortList );
743 $table.data( 'tablesorter' ).sort();
744 }
745
746 } );
747 },
748
749 addParser: function ( parser ) {
750 var l = parsers.length,
751 a = true;
752 for ( var i = 0; i < l; i++ ) {
753 if ( parsers[i].id.toLowerCase() === parser.id.toLowerCase() ) {
754 a = false;
755 }
756 }
757 if ( a ) {
758 parsers.push( parser );
759 }
760 },
761
762 formatDigit: function ( s ) {
763 var out, c, p, i;
764 if ( ts.transformTable !== false ) {
765 out = '';
766 for ( p = 0; p < s.length; p++ ) {
767 c = s.charAt(p);
768 if ( c in ts.transformTable ) {
769 out += ts.transformTable[c];
770 } else {
771 out += c;
772 }
773 }
774 s = out;
775 }
776 i = parseFloat( s.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
777 return isNaN( i ) ? 0 : i;
778 },
779
780 formatFloat: function ( s ) {
781 var i = parseFloat(s);
782 return isNaN( i ) ? 0 : i;
783 },
784
785 formatInt: function ( s ) {
786 var i = parseInt( s, 10 );
787 return isNaN( i ) ? 0 : i;
788 },
789
790 clearTableBody: function ( table ) {
791 $( table.tBodies[0] ).empty();
792 }
793 };
794
795 // Shortcut
796 ts = $.tablesorter;
797
798 // Register as jQuery prototype method
799 $.fn.tablesorter = function ( settings ) {
800 return ts.construct( this, settings );
801 };
802
803 // Add default parsers
804 ts.addParser( {
805 id: 'text',
806 is: function () {
807 return true;
808 },
809 format: function ( s ) {
810 s = $.trim( s.toLowerCase() );
811 if ( ts.collationRegex ) {
812 var tsc = ts.collationTable;
813 s = s.replace( ts.collationRegex, function ( match ) {
814 var r = tsc[match] ? tsc[match] : tsc[match.toUpperCase()];
815 return r.toLowerCase();
816 } );
817 }
818 return s;
819 },
820 type: 'text'
821 } );
822
823 ts.addParser( {
824 id: 'IPAddress',
825 is: function ( s ) {
826 return ts.rgx.IPAddress[0].test(s);
827 },
828 format: function ( s ) {
829 var a = s.split( '.' ),
830 r = '',
831 l = a.length;
832 for ( var i = 0; i < l; i++ ) {
833 var item = a[i];
834 if ( item.length === 1 ) {
835 r += '00' + item;
836 } else if ( item.length === 2 ) {
837 r += '0' + item;
838 } else {
839 r += item;
840 }
841 }
842 return $.tablesorter.formatFloat(r);
843 },
844 type: 'numeric'
845 } );
846
847 ts.addParser( {
848 id: 'currency',
849 is: function ( s ) {
850 return ts.rgx.currency[0].test(s);
851 },
852 format: function ( s ) {
853 return $.tablesorter.formatDigit( s.replace( ts.rgx.currency[1], '' ) );
854 },
855 type: 'numeric'
856 } );
857
858 ts.addParser( {
859 id: 'url',
860 is: function ( s ) {
861 return ts.rgx.url[0].test(s);
862 },
863 format: function ( s ) {
864 return $.trim( s.replace( ts.rgx.url[1], '' ) );
865 },
866 type: 'text'
867 } );
868
869 ts.addParser( {
870 id: 'isoDate',
871 is: function ( s ) {
872 return ts.rgx.isoDate[0].test(s);
873 },
874 format: function ( s ) {
875 return $.tablesorter.formatFloat((s !== '') ? new Date(s.replace(
876 new RegExp( /-/g), '/')).getTime() : '0' );
877 },
878 type: 'numeric'
879 } );
880
881 ts.addParser( {
882 id: 'usLongDate',
883 is: function ( s ) {
884 return ts.rgx.usLongDate[0].test(s);
885 },
886 format: function ( s ) {
887 return $.tablesorter.formatFloat( new Date(s).getTime() );
888 },
889 type: 'numeric'
890 } );
891
892 ts.addParser( {
893 id: 'date',
894 is: function ( s ) {
895 return ( ts.dateRegex[0].test(s) || ts.dateRegex[1].test(s) || ts.dateRegex[2].test(s ));
896 },
897 format: function ( s ) {
898 var match;
899 s = $.trim( s.toLowerCase() );
900
901 if ( ( match = s.match( ts.dateRegex[0] ) ) !== null ) {
902 if ( mw.config.get( 'wgDefaultDateFormat' ) === 'mdy' || mw.config.get( 'wgContentLanguage' ) === 'en' ) {
903 s = [ match[3], match[1], match[2] ];
904 } else if ( mw.config.get( 'wgDefaultDateFormat' ) === 'dmy' ) {
905 s = [ match[3], match[2], match[1] ];
906 } else {
907 // If we get here, we don't know which order the dd-dd-dddd
908 // date is in. So return something not entirely invalid.
909 return '99999999';
910 }
911 } else if ( ( match = s.match( ts.dateRegex[1] ) ) !== null ) {
912 s = [ match[3], '' + ts.monthNames[match[2]], match[1] ];
913 } else if ( ( match = s.match( ts.dateRegex[2] ) ) !== null ) {
914 s = [ match[3], '' + ts.monthNames[match[1]], match[2] ];
915 } else {
916 // Should never get here
917 return '99999999';
918 }
919
920 // Pad Month and Day
921 if ( s[1].length === 1 ) {
922 s[1] = '0' + s[1];
923 }
924 if ( s[2].length === 1 ) {
925 s[2] = '0' + s[2];
926 }
927
928 var y;
929 if ( ( y = parseInt( s[0], 10) ) < 100 ) {
930 // Guestimate years without centuries
931 if ( y < 30 ) {
932 s[0] = 2000 + y;
933 } else {
934 s[0] = 1900 + y;
935 }
936 }
937 while ( s[0].length < 4 ) {
938 s[0] = '0' + s[0];
939 }
940 return parseInt( s.join( '' ), 10 );
941 },
942 type: 'numeric'
943 } );
944
945 ts.addParser( {
946 id: 'time',
947 is: function ( s ) {
948 return ts.rgx.time[0].test(s);
949 },
950 format: function ( s ) {
951 return $.tablesorter.formatFloat( new Date( '2000/01/01 ' + s ).getTime() );
952 },
953 type: 'numeric'
954 } );
955
956 ts.addParser( {
957 id: 'number',
958 is: function ( s ) {
959 return $.tablesorter.numberRegex.test( $.trim( s ));
960 },
961 format: function ( s ) {
962 return $.tablesorter.formatDigit(s);
963 },
964 type: 'numeric'
965 } );
966
967 }( jQuery, mediaWiki ) );