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 // Use data-sort-value attribute.
81 // Use data() instead of attr() so that live value changes
82 // are processed as well (bug 38152).
83 data
= $node
.data( 'sortValue' );
85 if ( data
!== null && data
!== undefined ) {
86 // Cast any numbers or other stuff to a string, methods
87 // like charAt, toLowerCase and split are expected.
88 return String( data
);
94 function getTextFromRowAndCellIndex( rows
, rowIndex
, cellIndex
) {
95 if ( rows
[rowIndex
] && rows
[rowIndex
].cells
[cellIndex
] ) {
96 return $.trim( getElementText( rows
[rowIndex
].cells
[cellIndex
] ) );
102 function detectParserForColumn( table
, rows
, cellIndex
) {
103 var l
= parsers
.length
,
105 // Start with 1 because 0 is the fallback parser
109 needed
= ( rows
.length
> 4 ) ? 5 : rows
.length
;
112 nodeValue
= getTextFromRowAndCellIndex( rows
, rowIndex
, cellIndex
);
113 if ( nodeValue
!== '') {
114 if ( parsers
[i
].is( nodeValue
, table
) ) {
117 if ( concurrent
>= needed
) {
118 // Confirmed the parser for multiple cells, let's return it
122 // Check next parser, reset rows
130 if ( rowIndex
> rows
.length
) {
137 // 0 is always the generic parser (text)
141 function buildParserCache( table
, $headers
) {
142 var rows
= table
.tBodies
[0].rows
,
148 var cells
= rows
[0].cells
,
152 for ( i
= 0; i
< len
; i
++ ) {
154 sortType
= $headers
.eq( i
).data( 'sort-type' );
155 if ( sortType
!== undefined ) {
156 parser
= getParserById( sortType
);
159 if ( parser
=== false ) {
160 parser
= detectParserForColumn( table
, rows
, i
);
163 parsers
.push( parser
);
169 /* Other utility functions */
171 function buildCache( table
) {
172 var totalRows
= ( table
.tBodies
[0] && table
.tBodies
[0].rows
.length
) || 0,
173 totalCells
= ( table
.tBodies
[0].rows
[0] && table
.tBodies
[0].rows
[0].cells
.length
) || 0,
174 parsers
= table
.config
.parsers
,
180 for ( var i
= 0; i
< totalRows
; ++i
) {
182 // Add the table data to main data array
183 var $row
= $( table
.tBodies
[0].rows
[i
] ),
186 // if this is a child row, add it to the last row's children and
187 // continue to the next row
188 if ( $row
.hasClass( table
.config
.cssChildRow
) ) {
189 cache
.row
[cache
.row
.length
- 1] = cache
.row
[cache
.row
.length
- 1].add( $row
);
190 // go to the next for loop
194 cache
.row
.push( $row
);
196 for ( var j
= 0; j
< totalCells
; ++j
) {
197 cols
.push( parsers
[j
].format( getElementText( $row
[0].cells
[j
] ), table
, $row
[0].cells
[j
] ) );
200 cols
.push( cache
.normalized
.length
); // add position for rowCache
201 cache
.normalized
.push( cols
);
208 function appendToTable( table
, cache
) {
210 normalized
= cache
.normalized
,
211 totalRows
= normalized
.length
,
212 checkCell
= ( normalized
[0].length
- 1 ),
213 fragment
= document
.createDocumentFragment();
215 for ( var i
= 0; i
< totalRows
; i
++ ) {
216 var pos
= normalized
[i
][checkCell
];
218 var l
= row
[pos
].length
;
220 for ( var j
= 0; j
< l
; j
++ ) {
221 fragment
.appendChild( row
[pos
][j
] );
225 table
.tBodies
[0].appendChild( fragment
);
229 * Find all header rows in a thead-less table and put them in a <thead> tag.
230 * This only treats a row as a header row if it contains only <th>s (no <td>s)
231 * and if it is preceded entirely by header rows. The algorithm stops when
232 * it encounters the first non-header row.
234 * After this, it will look at all rows at the bottom for footer rows
235 * And place these in a tfoot using similar rules.
236 * @param $table jQuery object for a <table>
238 function emulateTHeadAndFoot( $table
) {
239 var $rows
= $table
.find( '> tbody > tr' );
240 if( !$table
.get(0).tHead
) {
241 var $thead
= $( '<thead>' );
242 $rows
.each( function() {
243 if ( $(this).children( 'td' ).length
> 0 ) {
244 // This row contains a <td>, so it's not a header row
248 $thead
.append( this );
250 $table
.find(' > tbody:first').before( $thead
);
252 if( !$table
.get(0).tFoot
) {
253 var $tfoot
= $( '<tfoot>' );
254 var len
= $rows
.length
;
255 for ( var i
= len
-1; i
>= 0; i
-- ) {
256 if( $( $rows
[i
] ).children( 'td' ).length
> 0 ){
259 $tfoot
.prepend( $( $rows
[i
] ));
261 $table
.append( $tfoot
);
265 function buildHeaders( table
, msg
) {
269 $tableHeaders
= $( 'thead:eq(0) > tr', table
);
270 if ( $tableHeaders
.length
> 1 ) {
271 $tableHeaders
.each( function() {
272 if ( this.cells
.length
> maxSeen
) {
273 maxSeen
= this.cells
.length
;
277 $tableHeaders
= $( longest
);
279 $tableHeaders
= $tableHeaders
.children( 'th' ).each( function( index
) {
280 this.column
= realCellIndex
;
282 var colspan
= this.colspan
;
283 colspan
= colspan
? parseInt( colspan
, 10 ) : 1;
284 realCellIndex
+= colspan
;
289 if ( $( this ).is( '.unsortable' ) ) {
290 this.sortDisabled
= true;
293 if ( !this.sortDisabled
) {
294 var $th
= $( this ).addClass( table
.config
.cssHeader
).attr( 'title', msg
[1] );
297 // add cell to headerList
298 table
.config
.headerList
[index
] = this;
301 return $tableHeaders
;
305 function isValueInArray( v
, a
) {
307 for ( var i
= 0; i
< l
; i
++ ) {
308 if ( a
[i
][0] == v
) {
315 function setHeadersCss( table
, $headers
, list
, css
, msg
) {
316 // Remove all header information
317 $headers
.removeClass( css
[0] ).removeClass( css
[1] );
320 $headers
.each( function( offset
) {
321 if ( !this.sortDisabled
) {
322 h
[this.column
] = $( this );
327 for ( var i
= 0; i
< l
; i
++ ) {
328 h
[ list
[i
][0] ].addClass( css
[ list
[i
][1] ] ).attr( 'title', msg
[ list
[i
][1] ] );
332 function sortText( a
, b
) {
333 return ( (a
< b
) ? false : ((a
> b
) ? true : 0) );
336 function sortTextDesc( a
, b
) {
337 return ( (b
< a
) ? false : ((b
> a
) ? true : 0) );
340 function checkSorting( array1
, array2
, sortList
) {
342 for ( var i
= 0, len
= sortList
.length
; i
< len
; i
++ ) {
343 col
= sortList
[i
][0];
344 fn
= ( sortList
[i
][1] ) ? sortTextDesc
: sortText
;
345 ret
= fn
.call( this, array1
[col
], array2
[col
] );
353 // Merge sort algorithm
354 // Based on http://en.literateprograms.org/Merge_sort_(JavaScript)
355 function mergeSortHelper( array
, begin
, beginRight
, end
, sortList
) {
356 for ( ; begin
< beginRight
; ++begin
) {
357 if ( checkSorting( array
[begin
], array
[beginRight
], sortList
) ) {
358 var v
= array
[begin
];
359 array
[begin
] = array
[beginRight
];
360 var begin2
= beginRight
;
361 while ( begin2
+ 1 < end
&& checkSorting( v
, array
[begin2
+ 1], sortList
) ) {
362 var tmp
= array
[begin2
];
363 array
[begin2
] = array
[begin2
+ 1];
364 array
[begin2
+ 1] = tmp
;
372 function mergeSort(array
, begin
, end
, sortList
) {
373 var size
= end
- begin
;
378 var beginRight
= begin
+ Math
.floor(size
/ 2);
380 mergeSort( array
, begin
, beginRight
, sortList
);
381 mergeSort( array
, beginRight
, end
, sortList
);
382 mergeSortHelper( array
, begin
, beginRight
, end
, sortList
);
385 function multisort( table
, sortList
, cache
) {
386 var i
= sortList
.length
;
387 mergeSort( cache
.normalized
, 0, cache
.normalized
.length
, sortList
);
392 function buildTransformTable() {
393 var digits
= '0123456789,.'.split( '' );
394 var separatorTransformTable
= mw
.config
.get( 'wgSeparatorTransformTable' );
395 var digitTransformTable
= mw
.config
.get( 'wgDigitTransformTable' );
396 if ( separatorTransformTable
=== null || ( separatorTransformTable
[0] === '' && digitTransformTable
[2] === '' ) ) {
397 ts
.transformTable
= false;
399 ts
.transformTable
= {};
401 // Unpack the transform table
402 var ascii
= separatorTransformTable
[0].split( "\t" ).concat( digitTransformTable
[0].split( "\t" ) );
403 var localised
= separatorTransformTable
[1].split( "\t" ).concat( digitTransformTable
[1].split( "\t" ) );
405 // Construct regex for number identification
406 for ( var i
= 0; i
< ascii
.length
; i
++ ) {
407 ts
.transformTable
[localised
[i
]] = ascii
[i
];
408 digits
.push( $.escapeRE( localised
[i
] ) );
411 var digitClass
= '[' + digits
.join( '', digits
) + ']';
413 // We allow a trailing percent sign, which we just strip. This works fine
414 // if percents and regular numbers aren't being mixed.
415 ts
.numberRegex
= new RegExp("^(" + "[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?" + // Fortran-style scientific
416 "|" + "[-+\u2212]?" + digitClass
+ "+[\\s\\xa0]*%?" + // Generic localised
420 function buildDateTable() {
424 for ( var i
= 1; i
< 13; i
++ ) {
425 var name
= mw
.config
.get( 'wgMonthNames' )[i
].toLowerCase();
426 ts
.monthNames
[name
] = i
;
427 regex
.push( $.escapeRE( name
) );
428 name
= mw
.config
.get( 'wgMonthNamesShort' )[i
].toLowerCase().replace( '.', '' );
429 ts
.monthNames
[name
] = i
;
430 regex
.push( $.escapeRE( name
) );
433 // Build piped string
434 regex
= regex
.join( '|' );
437 // Any date formated with . , ' - or /
438 ts
.dateRegex
[0] = new RegExp( /^\s*(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{2,4})\s*?/i);
440 // Written Month name, dmy
441 ts
.dateRegex
[1] = new RegExp( '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]*(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]*(\\d{2,4})\\s*$', 'i' );
443 // Written Month name, mdy
444 ts
.dateRegex
[2] = new RegExp( '^\\s*(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]*(\\d{1,2})[\\,\\.\\-\\/\'\\s]*(\\d{2,4})\\s*$', 'i' );
448 function explodeRowspans( $table
) {
449 // Split multi row cells into multiple cells with the same content
450 $table
.find( '> tbody > tr > [rowspan]' ).each(function() {
451 var rowSpan
= this.rowSpan
;
453 var cell
= $( this );
454 var next
= cell
.parent().nextAll();
455 for ( var i
= 0; i
< rowSpan
- 1; i
++ ) {
456 var td
= next
.eq( i
).children( 'td' );
458 next
.eq( i
).append( cell
.clone() );
459 } else if ( this.cellIndex
=== 0 ) {
460 td
.eq( this.cellIndex
).before( cell
.clone() );
462 td
.eq( this.cellIndex
- 1 ).after( cell
.clone() );
468 function buildCollationTable() {
469 ts
.collationTable
= mw
.config
.get( 'tableSorterCollation' );
470 ts
.collationRegex
= null;
471 if ( ts
.collationTable
) {
474 // Build array of key names
475 for ( var key
in ts
.collationTable
) {
476 if ( ts
.collationTable
.hasOwnProperty(key
) ) { //to be safe
481 ts
.collationRegex
= new RegExp( '[' + keys
.join( '' ) + ']', 'ig' );
486 function cacheRegexs() {
492 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/)
495 new RegExp( /^[£$€?.]/),
496 new RegExp( /[£$€]/g)
499 new RegExp( /^(https?|ftp|file):\/\/$/),
500 new RegExp( /(https?|ftp|file):\/\//)
503 new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/)
506 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)))$/)
509 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/)
519 cssHeader
: 'headerSort',
520 cssAsc
: 'headerSortUp',
521 cssDesc
: 'headerSortDown',
522 cssChildRow
: 'expand-child',
523 sortInitialOrder
: 'asc',
524 sortMultiSortKey
: 'shiftKey',
525 sortLocaleCompare
: false,
529 cancelSelection
: true,
532 selectorHeaders
: 'thead tr:eq(0) th',
540 * @param $tables {jQuery}
541 * @param settings {Object} (optional)
543 construct: function( $tables
, settings
) {
544 return $tables
.each( function( i
, table
) {
545 // Declare and cache.
546 var $document
, $headers
, cache
, config
, sortOrder
,
552 if ( !table
.tBodies
) {
555 if ( !table
.tHead
) {
556 // No thead found. Look for rows with <th>s and
557 // move them into a <thead> tag or a <tfoot> tag
558 emulateTHeadAndFoot( $table
);
560 // Still no thead? Then quit
561 if ( !table
.tHead
) {
565 $table
.addClass( "jquery-tablesorter" );
567 // New config object.
571 config
= $.extend( table
.config
, $.tablesorter
.defaultOptions
, settings
);
573 // Save the settings where they read
574 $.data( table
, 'tablesorter', config
);
576 // Get the CSS class names, could be done else where.
577 var sortCSS
= [ config
.cssDesc
, config
.cssAsc
];
578 var sortMsg
= [ mw
.msg( 'sort-descending' ), mw
.msg( 'sort-ascending' ) ];
581 $headers
= buildHeaders( table
, sortMsg
);
583 // Grab and process locale settings
584 buildTransformTable();
586 buildCollationTable();
588 // Precaching regexps can bring 10 fold
589 // performance improvements in some browsers.
592 // Apply event handling to headers
593 // this is too big, perhaps break it out?
594 $headers
.click( function( e
) {
595 if ( e
.target
.nodeName
.toLowerCase() == 'a' ) {
596 // The user clicked on a link inside a table header
597 // Do nothing and let the default link click action continue
604 // Legacy fix of .sortbottoms
605 // Wrap them inside inside a tfoot (because that's what they actually want to be) &
606 // and put the <tfoot> at the end of the <table>
607 var $sortbottoms
= $table
.find( '> tbody > tr.sortbottom' );
608 if ( $sortbottoms
.length
) {
609 var $tfoot
= $table
.children( 'tfoot' );
610 if ( $tfoot
.length
) {
611 $tfoot
.eq(0).prepend( $sortbottoms
);
613 $table
.append( $( '<tfoot>' ).append( $sortbottoms
) );
617 explodeRowspans( $table
);
618 // try to auto detect column type, and store in tables config
619 table
.config
.parsers
= buildParserCache( table
, $headers
);
622 // Build the cache for the tbody cells
623 // to share between calculations for this sort action.
624 // Re-calculated each time a sort action is performed due to possiblity
625 // that sort values change. Shouldn't be too expensive, but if it becomes
626 // too slow an event based system should be implemented somehow where
627 // cells get event .change() and bubbles up to the <table> here
628 cache
= buildCache( table
);
630 var totalRows
= ( $table
[0].tBodies
[0] && $table
[0].tBodies
[0].rows
.length
) || 0;
631 if ( !table
.sortDisabled
&& totalRows
> 0 ) {
633 // Cache jQuery object
634 var $cell
= $( this );
636 // Get current column index
639 // Get current column sort order
640 this.order
= this.count
% 2;
643 // User only wants to sort on one column
644 if ( !e
[config
.sortMultiSortKey
] ) {
645 // Flush the sort list
646 config
.sortList
= [];
647 // Add column to sort list
648 config
.sortList
.push( [i
, this.order
] );
650 // Multi column sorting
652 // The user has clicked on an already sorted column.
653 if ( isValueInArray( i
, config
.sortList
) ) {
654 // Reverse the sorting direction for all tables.
655 for ( var j
= 0; j
< config
.sortList
.length
; j
++ ) {
656 var s
= config
.sortList
[j
],
657 o
= config
.headerList
[s
[0]];
665 // Add column to sort list array
666 config
.sortList
.push( [i
, this.order
] );
670 // Set CSS for headers
671 setHeadersCss( $table
[0], $headers
, config
.sortList
, sortCSS
, sortMsg
);
673 $table
[0], multisort( $table
[0], config
.sortList
, cache
)
676 // Stop normal event by returning false
681 } ).mousedown( function() {
682 if ( config
.cancelSelection
) {
683 this.onselectstart = function() {
692 addParser: function( parser
) {
693 var l
= parsers
.length
,
695 for ( var i
= 0; i
< l
; i
++ ) {
696 if ( parsers
[i
].id
.toLowerCase() == parser
.id
.toLowerCase() ) {
701 parsers
.push( parser
);
705 formatDigit: function( s
) {
706 if ( ts
.transformTable
!== false ) {
709 for ( var p
= 0; p
< s
.length
; p
++ ) {
711 if ( c
in ts
.transformTable
) {
712 out
+= ts
.transformTable
[c
];
719 var i
= parseFloat( s
.replace( /[, ]/g, '' ).replace( "\u2212", '-' ) );
720 return ( isNaN(i
)) ? 0 : i
;
723 formatFloat: function( s
) {
724 var i
= parseFloat(s
);
725 return ( isNaN(i
)) ? 0 : i
;
728 formatInt: function( s
) {
729 var i
= parseInt( s
, 10 );
730 return ( isNaN(i
)) ? 0 : i
;
733 clearTableBody: function( table
) {
734 if ( $.browser
.msie
) {
735 var empty = function( el
) {
736 while ( el
.firstChild
) {
737 el
.removeChild( el
.firstChild
);
740 empty( table
.tBodies
[0] );
742 table
.tBodies
[0].innerHTML
= '';
750 // Register as jQuery prototype method
751 $.fn
.tablesorter = function( settings
) {
752 return ts
.construct( this, settings
);
755 // Add default parsers
761 format: function( s
) {
762 s
= $.trim( s
.toLowerCase() );
763 if ( ts
.collationRegex
) {
764 var tsc
= ts
.collationTable
;
765 s
= s
.replace( ts
.collationRegex
, function( match
) {
766 var r
= tsc
[match
] ? tsc
[match
] : tsc
[match
.toUpperCase()];
767 return r
.toLowerCase();
778 return ts
.rgx
.IPAddress
[0].test(s
);
780 format: function( s
) {
781 var a
= s
.split( '.' ),
784 for ( var i
= 0; i
< l
; i
++ ) {
786 if ( item
.length
== 1 ) {
788 } else if ( item
.length
== 2 ) {
794 return $.tablesorter
.formatFloat(r
);
802 return ts
.rgx
.currency
[0].test(s
);
804 format: function( s
) {
805 return $.tablesorter
.formatDigit( s
.replace( ts
.rgx
.currency
[1], '' ) );
813 return ts
.rgx
.url
[0].test(s
);
815 format: function( s
) {
816 return $.trim( s
.replace( ts
.rgx
.url
[1], '' ) );
824 return ts
.rgx
.isoDate
[0].test(s
);
826 format: function( s
) {
827 return $.tablesorter
.formatFloat((s
!== '') ? new Date(s
.replace(
828 new RegExp( /-/g), '/')).getTime() : '0' );
836 return ts.rgx.usLongDate[0].test(s);
838 format: function( s ) {
839 return $.tablesorter.formatFloat( new Date(s).getTime() );
847 return ( ts.dateRegex[0].test(s) || ts.dateRegex[1].test(s) || ts.dateRegex[2].test(s ));
849 format: function( s, table ) {
850 s = $.trim( s.toLowerCase() );
853 if ( ( match = s.match( ts.dateRegex[0] ) ) !== null ) {
854 if ( mw.config.get( 'wgDefaultDateFormat
' ) == 'mdy
' || mw.config.get( 'wgContentLanguage
' ) == 'en
' ) {
855 s = [ match[3], match[1], match[2] ];
856 } else if ( mw.config.get( 'wgDefaultDateFormat
' ) == 'dmy
' ) {
857 s = [ match[3], match[2], match[1] ];
859 } else if ( ( match = s.match( ts.dateRegex[1] ) ) !== null ) {
860 s = [ match[3], '' + ts.monthNames[match[2]], match[1] ];
861 } else if ( ( match = s.match( ts.dateRegex[2] ) ) !== null ) {
862 s = [ match[3], '' + ts.monthNames[match[1]], match[2] ];
864 // Should never get here
869 if ( s[1].length == 1 ) {
872 if ( s[2].length == 1 ) {
877 if ( ( y = parseInt( s[0], 10) ) < 100 ) {
878 // Guestimate years without centuries
885 while ( s[0].length < 4 ) {
888 return parseInt( s.join( '' ), 10 );
896 return ts.rgx.time[0].test(s);
898 format: function( s ) {
899 return $.tablesorter.formatFloat( new Date( '2000/01/01 ' + s ).getTime() );
906 is: function( s, table ) {
907 return $.tablesorter.numberRegex.test( $.trim( s ));
909 format: function( s ) {
910 return $.tablesorter.formatDigit(s);