2 * TableSorter for MediaWiki
4 * Written 2011 Leo Koppelkamm
5 * Based on tablesorter.com plugin, written (c) 2007 Christian Bach.
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
11 * Depends on mw.config (wgDigitTransformTable, wgMonthNames, wgMonthNamesShort,
12 * wgDefaultDateFormat, wgContentLanguage)
13 * Uses 'tableSorterCollation' in mw.config (if available)
17 * @description Create a sortable table with multi-column sorting capabilitys
19 * @example $( 'table' ).tablesorter();
20 * @desc Create a simple tablesorter interface.
22 * @option String cssHeader ( optional ) A string of the class name to be appended
23 * to sortable tr elements in the thead of the table. Default value:
26 * @option String cssAsc ( optional ) A string of the class name to be appended to
27 * sortable tr elements in the thead on a ascending sort. Default value:
30 * @option String cssDesc ( optional ) A string of the class name to be appended
31 * to sortable tr elements in the thead on a descending sort. Default
32 * value: "headerSortDown"
34 * @option String sortInitialOrder ( optional ) A string of the inital sorting
35 * order can be asc or desc. Default value: "asc"
37 * @option String sortMultisortKey ( optional ) A string of the multi-column sort
38 * key. Default value: "shiftKey"
40 * @option Boolean sortLocaleCompare ( optional ) Boolean flag indicating whatever
41 * to use String.localeCampare method or not. Set to false.
43 * @option Boolean cancelSelection ( optional ) Boolean flag indicating if
44 * tablesorter should cancel selection of the table headers text.
47 * @option Boolean debug ( optional ) Boolean flag indicating if tablesorter
48 * should display debuging information usefull for development.
54 * @cat Plugins/Tablesorter
56 * @author Christian Bach/christian.bach@polyester.se
66 /* Parser utility functions */
68 function getParserById( name ) {
69 var len = parsers.length;
70 for ( var i = 0; i < len; i++ ) {
71 if ( parsers[i].id.toLowerCase() === name.toLowerCase() ) {
78 function getElementText( node ) {
79 var $node = $( node ),
80 data = $node.attr( 'data-sort-value' );
81 if ( data !== undefined ) {
88 function getTextFromRowAndCellIndex( rows, rowIndex, cellIndex ) {
89 if ( rows[rowIndex] && rows[rowIndex].cells[cellIndex] ) {
90 return $.trim( getElementText( rows[rowIndex].cells[cellIndex] ) );
96 function detectParserForColumn( table, rows, cellIndex ) {
97 var l = parsers.length,
99 // Start with 1 because 0 is the fallback parser
103 needed = ( rows.length > 4 ) ? 5 : rows.length;
106 nodeValue = getTextFromRowAndCellIndex( rows, rowIndex, cellIndex );
107 if ( nodeValue !== '') {
108 if ( parsers[i].is( nodeValue, table ) ) {
111 if ( concurrent >= needed ) {
112 // Confirmed the parser for multiple cells, let's return it
116 // Check next parser, reset rows
124 if ( rowIndex > rows.length ) {
131 // 0 is always the generic parser (text)
135 function buildParserCache( table, $headers ) {
136 var rows = table.tBodies[0].rows,
142 var cells = rows[0].cells,
146 for ( i = 0; i < len; i++ ) {
148 sortType = $headers.eq( i ).data( 'sort-type' );
149 if ( sortType !== undefined ) {
150 parser = getParserById( sortType );
153 if ( parser === false ) {
154 parser = detectParserForColumn( table, rows, i );
157 parsers.push( parser );
163 /* Other utility functions */
165 function buildCache( table ) {
166 var totalRows = ( table.tBodies[0] && table.tBodies[0].rows.length ) || 0,
167 totalCells = ( table.tBodies[0].rows[0] && table.tBodies[0].rows[0].cells.length ) || 0,
168 parsers = table.config.parsers,
174 for ( var i = 0; i < totalRows; ++i ) {
176 // Add the table data to main data array
177 var $row = $( table.tBodies[0].rows[i] ),
180 // if this is a child row, add it to the last row's children and
181 // continue to the next row
182 if ( $row.hasClass( table.config.cssChildRow ) ) {
183 cache.row[cache.row.length - 1] = cache.row[cache.row.length - 1].add( $row );
184 // go to the next for loop
188 cache.row.push( $row );
190 for ( var j = 0; j < totalCells; ++j ) {
191 cols.push( parsers[j].format( getElementText( $row[0].cells[j] ), table, $row[0].cells[j] ) );
194 cols.push( cache.normalized.length ); // add position for rowCache
195 cache.normalized.push( cols );
202 function appendToTable( table, cache ) {
204 normalized = cache.normalized,
205 totalRows = normalized.length,
206 checkCell = ( normalized[0].length - 1 ),
207 fragment = document.createDocumentFragment();
209 for ( var i = 0; i < totalRows; i++ ) {
210 var pos = normalized[i][checkCell];
212 var l = row[pos].length;
214 for ( var j = 0; j < l; j++ ) {
215 fragment.appendChild( row[pos][j] );
219 table.tBodies[0].appendChild( fragment );
223 * Find all header rows in a thead-less table and put them in a <thead> tag.
224 * This only treats a row as a header row if it contains only <th>s (no <td>s)
225 * and if it is preceded entirely by header rows. The algorithm stops when
226 * it encounters the first non-header row.
227 * @param $table jQuery object for a <table>
229 function emulateTHead( $table ) {
230 var $thead = $( '<thead>' );
231 $table.find( 'tr' ).each( function() {
232 if ( $(this).find( 'td' ).length > 0 ) {
233 // This row contains a <td>, so it's not a header row
237 $thead.append( this );
239 $table.prepend( $thead );
242 function buildHeaders( table, msg ) {
246 $tableHeaders = $( 'thead:eq(0) tr', table );
247 if ( $tableHeaders.length > 1 ) {
248 $tableHeaders.each( function() {
249 if ( this.cells.length > maxSeen ) {
250 maxSeen = this.cells.length;
254 $tableHeaders = $( longest );
256 $tableHeaders = $tableHeaders.find( 'th' ).each( function( index ) {
257 this.column = realCellIndex;
259 var colspan = this.colspan;
260 colspan = colspan ? parseInt( colspan, 10 ) : 1;
261 realCellIndex += colspan;
266 if ( $( this ).is( '.unsortable' ) ) {
267 this.sortDisabled = true;
270 if ( !this.sortDisabled ) {
271 var $th = $( this ).addClass( table.config.cssHeader ).attr( 'title', msg[1] );
274 // add cell to headerList
275 table.config.headerList[index] = this;
278 return $tableHeaders;
282 function isValueInArray( v, a ) {
284 for ( var i = 0; i < l; i++ ) {
285 if ( a[i][0] == v ) {
292 function setHeadersCss( table, $headers, list, css, msg ) {
293 // Remove all header information
294 $headers.removeClass( css[0] ).removeClass( css[1] );
297 $headers.each( function( offset ) {
298 if ( !this.sortDisabled ) {
299 h[this.column] = $( this );
304 for ( var i = 0; i < l; i++ ) {
305 h[ list[i][0] ].addClass( css[ list[i][1] ] ).attr( 'title', msg[ list[i][1] ] );
309 function sortText( a, b ) {
310 return ( (a < b) ? false : ((a > b) ? true : 0) );
313 function sortTextDesc( a, b ) {
314 return ( (b < a) ? false : ((b > a) ? true : 0) );
317 function checkSorting( array1, array2, sortList ) {
319 for ( var i = 0, len = sortList.length; i < len; i++ ) {
320 col = sortList[i][0];
321 fn = ( sortList[i][1] ) ? sortTextDesc : sortText;
322 ret = fn.call( this, array1[col], array2[col] );
330 // Merge sort algorithm
331 // Based on http://en.literateprograms.org/Merge_sort_(JavaScript)
332 function mergeSortHelper( array, begin, beginRight, end, sortList ) {
333 for ( ; begin < beginRight; ++begin ) {
334 if ( checkSorting( array[begin], array[beginRight], sortList ) ) {
335 var v = array[begin];
336 array[begin] = array[beginRight];
337 var begin2 = beginRight;
338 while ( begin2 + 1 < end && checkSorting( v, array[begin2 + 1], sortList ) ) {
339 var tmp = array[begin2];
340 array[begin2] = array[begin2 + 1];
341 array[begin2 + 1] = tmp;
349 function mergeSort(array, begin, end, sortList) {
350 var size = end - begin;
355 var beginRight = begin + Math.floor(size / 2);
357 mergeSort( array, begin, beginRight, sortList );
358 mergeSort( array, beginRight, end, sortList );
359 mergeSortHelper( array, begin, beginRight, end, sortList );
362 function multisort( table, sortList, cache ) {
363 var i = sortList.length;
364 mergeSort( cache.normalized, 0, cache.normalized.length, sortList );
369 function buildTransformTable() {
370 var digits = '0123456789,.'.split( '' );
371 var separatorTransformTable = mw.config.get( 'wgSeparatorTransformTable' );
372 var digitTransformTable = mw.config.get( 'wgDigitTransformTable' );
373 if ( separatorTransformTable === null || ( separatorTransformTable[0] === '' && digitTransformTable[2] === '' ) ) {
374 ts.transformTable = false;
376 ts.transformTable = {};
378 // Unpack the transform table
379 var ascii = separatorTransformTable[0].split( "\t" ).concat( digitTransformTable[0].split( "\t" ) );
380 var localised = separatorTransformTable[1].split( "\t" ).concat( digitTransformTable[1].split( "\t" ) );
382 // Construct regex for number identification
383 for ( var i = 0; i < ascii.length; i++ ) {
384 ts.transformTable[localised[i]] = ascii[i];
385 digits.push( $.escapeRE( localised[i] ) );
388 var digitClass = '[' + digits.join( '', digits ) + ']';
390 // We allow a trailing percent sign, which we just strip. This works fine
391 // if percents and regular numbers aren't being mixed.
392 ts.numberRegex = new RegExp("^(" + "[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?" + // Fortran-style scientific
393 "|" + "[-+\u2212]?" + digitClass + "+[\\s\\xa0]*%?" + // Generic localised
397 function buildDateTable() {
404 for ( var i = 1; i < 13; i++ ) {
405 ts.monthNames[0][i] = mw.config.get( 'wgMonthNames' )[i].toLowerCase();
406 ts.monthNames[1][i] = mw.config.get( 'wgMonthNamesShort' )[i].toLowerCase().replace( '.', '' );
407 regex.push( $.escapeRE( ts.monthNames[0][i] ) );
408 regex.push( $.escapeRE( ts.monthNames[1][i] ) );
411 // Build piped string
412 regex = regex.join( '|' );
415 // Any date formated with . , ' - or /
416 ts.dateRegex[0] = new RegExp( /^\s*\d{1,2}[\,\.\-\/'\s]{1,2}\d{1,2}[\,\.\-\/'\s]{1,2}\d{2,4}\s*?/i);
418 // Written Month name, dmy
419 ts.dateRegex[1] = new RegExp( '^\\s*\\d{1,2}[\\,\\.\\-\\/\'\\s]*(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]*\\d{2,4}\\s*$', 'i' );
421 // Written Month name, mdy
422 ts.dateRegex[2] = new RegExp( '^\\s*(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]*\\d{1,2}[\\,\\.\\-\\/\'\\s]*\\d{2,4}\\s*$', 'i' );
426 function explodeRowspans( $table ) {
427 // Split multi row cells into multiple cells with the same content
428 $table.find( '[rowspan]' ).each(function() {
429 var rowSpan = this.rowSpan;
431 var cell = $( this );
432 var next = cell.parent().nextAll();
433 for ( var i = 0; i < rowSpan - 1; i++ ) {
434 var td = next.eq( i ).find( 'td' );
436 next.eq( i ).append( cell.clone() );
437 } else if ( this.cellIndex === 0 ) {
438 td.eq( this.cellIndex ).before( cell.clone() );
440 td.eq( this.cellIndex - 1 ).after( cell.clone() );
446 function buildCollationTable() {
447 ts.collationTable = mw.config.get( 'tableSorterCollation' );
448 ts.collationRegex = null;
449 if ( ts.collationTable ) {
452 // Build array of key names
453 for ( var key in ts.collationTable ) {
454 if ( ts.collationTable.hasOwnProperty(key) ) { //to be safe
459 ts.collationRegex = new RegExp( '[' + keys.join( '' ) + ']', 'ig' );
464 function cacheRegexs() {
470 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/)
473 new RegExp( /^[£$€?.]/),
474 new RegExp( /[£$€]/g)
477 new RegExp( /^(https?|ftp|file):\/\/$/),
478 new RegExp( /(https?|ftp|file):\/\//)
481 new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/)
484 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)))$/)
487 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/)
497 cssHeader: 'headerSort',
498 cssAsc: 'headerSortUp',
499 cssDesc: 'headerSortDown',
500 cssChildRow: 'expand-child',
501 sortInitialOrder: 'asc',
502 sortMultiSortKey: 'shiftKey',
503 sortLocaleCompare: false,
507 cancelSelection: true,
510 selectorHeaders: 'thead tr:eq(0) th',
518 * @param $tables {jQuery}
519 * @param settings {Object} (optional)
521 construct: function( $tables, settings ) {
522 return $tables.each( function( i, table ) {
523 // Declare and cache.
524 var $document, $headers, cache, config, sortOrder,
530 if ( !table.tBodies ) {
533 if ( !table.tHead ) {
534 // No thead found. Look for rows with <th>s and
535 // move them into a <thead> tag
536 emulateTHead( $table );
538 // Still no thead? Then quit
539 if ( !table.tHead ) {
544 // New config object.
548 config = $.extend( table.config, $.tablesorter.defaultOptions, settings );
550 // Save the settings where they read
551 $.data( table, 'tablesorter', config );
553 // Get the CSS class names, could be done else where.
554 var sortCSS = [ config.cssDesc, config.cssAsc ];
555 var sortMsg = [ mw.msg( 'sort-descending' ), mw.msg( 'sort-ascending' ) ];
558 $headers = buildHeaders( table, sortMsg );
560 // Grab and process locale settings
561 buildTransformTable();
563 buildCollationTable();
565 // Precaching regexps can bring 10 fold
566 // performance improvements in some browsers.
569 // Apply event handling to headers
570 // this is to big, perhaps break it out?
571 $headers.click( function( e ) {
576 // Legacy fix of .sortbottoms
577 // Wrap them inside inside a tfoot (because that's what they actually want to be) &
578 // and put the <tfoot> at the end of the <table>
579 var $sortbottoms = $table.find( 'tr.sortbottom' );
580 if ( $sortbottoms.length ) {
581 $table.append( $( '<tfoot>' ).append( $sortbottoms ) )
584 explodeRowspans( $table );
585 // try to auto detect column type, and store in tables config
586 table.config.parsers = buildParserCache( table, $headers );
587 // build the cache for the tbody cells
588 cache = buildCache( table );
590 var totalRows = ( $table[0].tBodies[0] && $table[0].tBodies[0].rows.length ) || 0;
591 if ( !table.sortDisabled && totalRows > 0 ) {
593 // Cache jQuery object
594 var $cell = $( this );
596 // Get current column index
599 // Get current column sort order
600 this.order = this.count % 2;
603 // User only wants to sort on one column
604 if ( !e[config.sortMultiSortKey] ) {
605 // Flush the sort list
606 config.sortList = [];
607 // Add column to sort list
608 config.sortList.push( [i, this.order] );
610 // Multi column sorting
612 // The user has clicked on an already sorted column.
613 if ( isValueInArray( i, config.sortList ) ) {
614 // Reverse the sorting direction for all tables.
615 for ( var j = 0; j < config.sortList.length; j++ ) {
616 var s = config.sortList[j],
617 o = config.headerList[s[0]];
625 // Add column to sort list array
626 config.sortList.push( [i, this.order] );
630 // Set CSS for headers
631 setHeadersCss( $table[0], $headers, config.sortList, sortCSS, sortMsg );
633 $table[0], multisort( $table[0], config.sortList, cache )
636 // Stop normal event by returning false
641 } ).mousedown( function() {
642 if ( config.cancelSelection ) {
643 this.onselectstart = function() {
653 addParser: function( parser ) {
654 var l = parsers.length,
656 for ( var i = 0; i < l; i++ ) {
657 if ( parsers[i].id.toLowerCase() == parser.id.toLowerCase() ) {
662 parsers.push( parser );
666 formatDigit: function( s ) {
667 if ( ts.transformTable !== false ) {
670 for ( var p = 0; p < s.length; p++ ) {
672 if ( c in ts.transformTable ) {
673 out += ts.transformTable[c];
680 var i = parseFloat( s.replace( /[, ]/g, '' ).replace( "\u2212", '-' ) );
681 return ( isNaN(i)) ? 0 : i;
684 formatFloat: function( s ) {
685 var i = parseFloat(s);
686 return ( isNaN(i)) ? 0 : i;
689 formatInt: function( s ) {
690 var i = parseInt( s, 10 );
691 return ( isNaN(i)) ? 0 : i;
694 clearTableBody: function( table ) {
695 if ( $.browser.msie ) {
696 var empty = function( el ) {
697 while ( el.firstChild ) {
698 el.removeChild( el.firstChild );
701 empty( table.tBodies[0] );
703 table.tBodies[0].innerHTML = '';
711 // Register as jQuery prototype method
712 $.fn.tablesorter = function( settings ) {
713 return ts.construct( this, settings );
716 // Add default parsers
722 format: function( s ) {
723 s = $.trim( s.toLowerCase() );
724 if ( ts.collationRegex ) {
725 var tsc = ts.collationTable;
726 s = s.replace( ts.collationRegex, function( match ) {
727 var r = tsc[match] ? tsc[match] : tsc[match.toUpperCase()];
728 return r.toLowerCase();
739 return ts.rgx.IPAddress[0].test(s);
741 format: function( s ) {
742 var a = s.split( '.' ),
745 for ( var i = 0; i < l; i++ ) {
747 if ( item.length == 1 ) {
749 } else if ( item.length == 2 ) {
755 return $.tablesorter.formatFloat(r);
763 return ts.rgx.currency[0].test(s);
765 format: function( s ) {
766 return $.tablesorter.formatDigit( s.replace( ts.rgx.currency[1], '' ) );
774 return ts.rgx.url[0].test(s);
776 format: function( s ) {
777 return $.trim( s.replace( ts.rgx.url[1], '' ) );
785 return ts.rgx.isoDate[0].test(s);
787 format: function( s ) {
788 return $.tablesorter.formatFloat((s !== '') ? new Date(s.replace(
789 new RegExp( /-/g), '/')).getTime() : '0' );
797 return ts.rgx.usLongDate[0].test(s);
799 format: function( s ) {
800 return $.tablesorter.formatFloat( new Date(s).getTime() );
808 return ( ts.dateRegex[0].test(s) || ts.dateRegex[1].test(s) || ts.dateRegex[2].test(s ));
810 format: function( s, table ) {
811 s = $.trim( s.toLowerCase() );
813 for ( var i = 1, j = 0; i < 13 && j < 2; i++ ) {
814 s = s.replace( ts.monthNames[j][i], i );
821 s = s.replace( /[\-\.\,' ]/g, '/' );
823 // Replace double slashes
824 s = s.replace( /\/\//g, '/' );
825 s = s.replace( /\/\//g, '/' );
829 if ( s[0] && s[0].length == 1 ) {
832 if ( s[1] && s[1].length == 1 ) {
838 // Fix yearless dates
840 } else if ( ( y = parseInt( s[2], 10) ) < 100 ) {
841 // Guestimate years without centuries
848 // Resort array depending on preferences
849 if ( mw.config.get( 'wgDefaultDateFormat' ) == 'mdy' || mw.config.get( 'wgContentLanguage' ) == 'en' ) {
852 } else if ( mw.config.get( 'wgDefaultDateFormat' ) == 'dmy' ) {
857 return parseInt( s.join( '' ), 10 );
865 return ts.rgx.time[0].test(s);
867 format: function( s ) {
868 return $.tablesorter.formatFloat( new Date( '2000/01/01 ' + s ).getTime() );
875 is: function( s, table ) {
876 return $.tablesorter.numberRegex.test( $.trim( s ));
878 format: function( s ) {
879 return $.tablesorter.formatDigit(s);