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.
228 * After this, it will look at all rows at the bottom for footer rows
229 * And place these in a tfoot using similar rules.
230 * @param $table jQuery object for a <table>
232 function emulateTHeadAndFoot( $table
) {
233 var $rows
= $table
.find( '> tbody > tr' );
234 if( !$table
.get(0).tHead
) {
235 var $thead
= $( '<thead>' );
236 $rows
.each( function() {
237 if ( $(this).children( 'td' ).length
> 0 ) {
238 // This row contains a <td>, so it's not a header row
242 $thead
.append( this );
244 $table
.find(' > tbody:first').before( $thead
);
246 if( !$table
.get(0).tFoot
) {
247 var $tfoot
= $( '<tfoot>' );
248 var len
= $rows
.length
;
249 for ( var i
= len
-1; i
>= 0; i
-- ) {
250 if( $( $rows
[i
] ).children( 'td' ).length
> 0 ){
253 $tfoot
.prepend( $( $rows
[i
] ));
255 $table
.append( $tfoot
);
259 function buildHeaders( table
, msg
) {
263 $tableHeaders
= $( 'thead:eq(0) > tr', table
);
264 if ( $tableHeaders
.length
> 1 ) {
265 $tableHeaders
.each( function() {
266 if ( this.cells
.length
> maxSeen
) {
267 maxSeen
= this.cells
.length
;
271 $tableHeaders
= $( longest
);
273 $tableHeaders
= $tableHeaders
.children( 'th' ).each( function( index
) {
274 this.column
= realCellIndex
;
276 var colspan
= this.colspan
;
277 colspan
= colspan
? parseInt( colspan
, 10 ) : 1;
278 realCellIndex
+= colspan
;
283 if ( $( this ).is( '.unsortable' ) ) {
284 this.sortDisabled
= true;
287 if ( !this.sortDisabled
) {
288 var $th
= $( this ).addClass( table
.config
.cssHeader
).attr( 'title', msg
[1] );
291 // add cell to headerList
292 table
.config
.headerList
[index
] = this;
295 return $tableHeaders
;
299 function isValueInArray( v
, a
) {
301 for ( var i
= 0; i
< l
; i
++ ) {
302 if ( a
[i
][0] == v
) {
309 function setHeadersCss( table
, $headers
, list
, css
, msg
) {
310 // Remove all header information
311 $headers
.removeClass( css
[0] ).removeClass( css
[1] );
314 $headers
.each( function( offset
) {
315 if ( !this.sortDisabled
) {
316 h
[this.column
] = $( this );
321 for ( var i
= 0; i
< l
; i
++ ) {
322 h
[ list
[i
][0] ].addClass( css
[ list
[i
][1] ] ).attr( 'title', msg
[ list
[i
][1] ] );
326 function sortText( a
, b
) {
327 return ( (a
< b
) ? false : ((a
> b
) ? true : 0) );
330 function sortTextDesc( a
, b
) {
331 return ( (b
< a
) ? false : ((b
> a
) ? true : 0) );
334 function checkSorting( array1
, array2
, sortList
) {
336 for ( var i
= 0, len
= sortList
.length
; i
< len
; i
++ ) {
337 col
= sortList
[i
][0];
338 fn
= ( sortList
[i
][1] ) ? sortTextDesc
: sortText
;
339 ret
= fn
.call( this, array1
[col
], array2
[col
] );
347 // Merge sort algorithm
348 // Based on http://en.literateprograms.org/Merge_sort_(JavaScript)
349 function mergeSortHelper( array
, begin
, beginRight
, end
, sortList
) {
350 for ( ; begin
< beginRight
; ++begin
) {
351 if ( checkSorting( array
[begin
], array
[beginRight
], sortList
) ) {
352 var v
= array
[begin
];
353 array
[begin
] = array
[beginRight
];
354 var begin2
= beginRight
;
355 while ( begin2
+ 1 < end
&& checkSorting( v
, array
[begin2
+ 1], sortList
) ) {
356 var tmp
= array
[begin2
];
357 array
[begin2
] = array
[begin2
+ 1];
358 array
[begin2
+ 1] = tmp
;
366 function mergeSort(array
, begin
, end
, sortList
) {
367 var size
= end
- begin
;
372 var beginRight
= begin
+ Math
.floor(size
/ 2);
374 mergeSort( array
, begin
, beginRight
, sortList
);
375 mergeSort( array
, beginRight
, end
, sortList
);
376 mergeSortHelper( array
, begin
, beginRight
, end
, sortList
);
379 function multisort( table
, sortList
, cache
) {
380 var i
= sortList
.length
;
381 mergeSort( cache
.normalized
, 0, cache
.normalized
.length
, sortList
);
386 function buildTransformTable() {
387 var digits
= '0123456789,.'.split( '' );
388 var separatorTransformTable
= mw
.config
.get( 'wgSeparatorTransformTable' );
389 var digitTransformTable
= mw
.config
.get( 'wgDigitTransformTable' );
390 if ( separatorTransformTable
=== null || ( separatorTransformTable
[0] === '' && digitTransformTable
[2] === '' ) ) {
391 ts
.transformTable
= false;
393 ts
.transformTable
= {};
395 // Unpack the transform table
396 var ascii
= separatorTransformTable
[0].split( "\t" ).concat( digitTransformTable
[0].split( "\t" ) );
397 var localised
= separatorTransformTable
[1].split( "\t" ).concat( digitTransformTable
[1].split( "\t" ) );
399 // Construct regex for number identification
400 for ( var i
= 0; i
< ascii
.length
; i
++ ) {
401 ts
.transformTable
[localised
[i
]] = ascii
[i
];
402 digits
.push( $.escapeRE( localised
[i
] ) );
405 var digitClass
= '[' + digits
.join( '', digits
) + ']';
407 // We allow a trailing percent sign, which we just strip. This works fine
408 // if percents and regular numbers aren't being mixed.
409 ts
.numberRegex
= new RegExp("^(" + "[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?" + // Fortran-style scientific
410 "|" + "[-+\u2212]?" + digitClass
+ "+[\\s\\xa0]*%?" + // Generic localised
414 function buildDateTable() {
421 for ( var i
= 1; i
< 13; i
++ ) {
422 ts
.monthNames
[0][i
] = mw
.config
.get( 'wgMonthNames' )[i
].toLowerCase();
423 ts
.monthNames
[1][i
] = mw
.config
.get( 'wgMonthNamesShort' )[i
].toLowerCase().replace( '.', '' );
424 regex
.push( $.escapeRE( ts
.monthNames
[0][i
] ) );
425 regex
.push( $.escapeRE( ts
.monthNames
[1][i
] ) );
428 // Build piped string
429 regex
= regex
.join( '|' );
432 // Any date formated with . , ' - or /
433 ts
.dateRegex
[0] = new RegExp( /^\s*\d{1,2}[\,\.\-\/'\s]{1,2}\d{1,2}[\,\.\-\/'\s]{1,2}\d{2,4}\s*?/i);
435 // Written Month name, dmy
436 ts
.dateRegex
[1] = new RegExp( '^\\s*\\d{1,2}[\\,\\.\\-\\/\'\\s]*(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]*\\d{2,4}\\s*$', 'i' );
438 // Written Month name, mdy
439 ts
.dateRegex
[2] = new RegExp( '^\\s*(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]*\\d{1,2}[\\,\\.\\-\\/\'\\s]*\\d{2,4}\\s*$', 'i' );
443 function explodeRowspans( $table
) {
444 // Split multi row cells into multiple cells with the same content
445 $table
.find( '> tbody > tr > [rowspan]' ).each(function() {
446 var rowSpan
= this.rowSpan
;
448 var cell
= $( this );
449 var next
= cell
.parent().nextAll();
450 for ( var i
= 0; i
< rowSpan
- 1; i
++ ) {
451 var td
= next
.eq( i
).children( 'td' );
453 next
.eq( i
).append( cell
.clone() );
454 } else if ( this.cellIndex
=== 0 ) {
455 td
.eq( this.cellIndex
).before( cell
.clone() );
457 td
.eq( this.cellIndex
- 1 ).after( cell
.clone() );
463 function buildCollationTable() {
464 ts
.collationTable
= mw
.config
.get( 'tableSorterCollation' );
465 ts
.collationRegex
= null;
466 if ( ts
.collationTable
) {
469 // Build array of key names
470 for ( var key
in ts
.collationTable
) {
471 if ( ts
.collationTable
.hasOwnProperty(key
) ) { //to be safe
476 ts
.collationRegex
= new RegExp( '[' + keys
.join( '' ) + ']', 'ig' );
481 function cacheRegexs() {
487 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/)
490 new RegExp( /^[£$€?.]/),
491 new RegExp( /[£$€]/g)
494 new RegExp( /^(https?|ftp|file):\/\/$/),
495 new RegExp( /(https?|ftp|file):\/\//)
498 new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/)
501 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)))$/)
504 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/)
514 cssHeader
: 'headerSort',
515 cssAsc
: 'headerSortUp',
516 cssDesc
: 'headerSortDown',
517 cssChildRow
: 'expand-child',
518 sortInitialOrder
: 'asc',
519 sortMultiSortKey
: 'shiftKey',
520 sortLocaleCompare
: false,
524 cancelSelection
: true,
527 selectorHeaders
: 'thead tr:eq(0) th',
535 * @param $tables {jQuery}
536 * @param settings {Object} (optional)
538 construct: function( $tables
, settings
) {
539 return $tables
.each( function( i
, table
) {
540 // Declare and cache.
541 var $document
, $headers
, cache
, config
, sortOrder
,
547 if ( !table
.tBodies
) {
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
);
555 // Still no thead? Then quit
556 if ( !table
.tHead
) {
560 $table
.addClass( "jquery-tablesorter" );
562 // New config object.
566 config
= $.extend( table
.config
, $.tablesorter
.defaultOptions
, settings
);
568 // Save the settings where they read
569 $.data( table
, 'tablesorter', config
);
571 // Get the CSS class names, could be done else where.
572 var sortCSS
= [ config
.cssDesc
, config
.cssAsc
];
573 var sortMsg
= [ mw
.msg( 'sort-descending' ), mw
.msg( 'sort-ascending' ) ];
576 $headers
= buildHeaders( table
, sortMsg
);
578 // Grab and process locale settings
579 buildTransformTable();
581 buildCollationTable();
583 // Precaching regexps can bring 10 fold
584 // performance improvements in some browsers.
587 // Apply event handling to headers
588 // this is too big, perhaps break it out?
589 $headers
.click( function( e
) {
590 if ( e
.target
.nodeName
.toLowerCase() == 'a' ) {
591 // The user clicked on a link inside a table header
592 // Do nothing and let the default link click action continue
599 // Legacy fix of .sortbottoms
600 // Wrap them inside inside a tfoot (because that's what they actually want to be) &
601 // and put the <tfoot> at the end of the <table>
602 var $sortbottoms
= $table
.find( '> tbody > tr.sortbottom' );
603 if ( $sortbottoms
.length
) {
604 var $tfoot
= $table
.children( 'tfoot' );
605 if ( $tfoot
.length
) {
606 $tfoot
.eq(0).prepend( $sortbottoms
);
608 $table
.append( $( '<tfoot>' ).append( $sortbottoms
) );
612 explodeRowspans( $table
);
613 // try to auto detect column type, and store in tables config
614 table
.config
.parsers
= buildParserCache( table
, $headers
);
615 // build the cache for the tbody cells
616 cache
= buildCache( table
);
618 var totalRows
= ( $table
[0].tBodies
[0] && $table
[0].tBodies
[0].rows
.length
) || 0;
619 if ( !table
.sortDisabled
&& totalRows
> 0 ) {
621 // Cache jQuery object
622 var $cell
= $( this );
624 // Get current column index
627 // Get current column sort order
628 this.order
= this.count
% 2;
631 // User only wants to sort on one column
632 if ( !e
[config
.sortMultiSortKey
] ) {
633 // Flush the sort list
634 config
.sortList
= [];
635 // Add column to sort list
636 config
.sortList
.push( [i
, this.order
] );
638 // Multi column sorting
640 // The user has clicked on an already sorted column.
641 if ( isValueInArray( i
, config
.sortList
) ) {
642 // Reverse the sorting direction for all tables.
643 for ( var j
= 0; j
< config
.sortList
.length
; j
++ ) {
644 var s
= config
.sortList
[j
],
645 o
= config
.headerList
[s
[0]];
653 // Add column to sort list array
654 config
.sortList
.push( [i
, this.order
] );
658 // Set CSS for headers
659 setHeadersCss( $table
[0], $headers
, config
.sortList
, sortCSS
, sortMsg
);
661 $table
[0], multisort( $table
[0], config
.sortList
, cache
)
664 // Stop normal event by returning false
669 } ).mousedown( function() {
670 if ( config
.cancelSelection
) {
671 this.onselectstart = function() {
680 addParser: function( parser
) {
681 var l
= parsers
.length
,
683 for ( var i
= 0; i
< l
; i
++ ) {
684 if ( parsers
[i
].id
.toLowerCase() == parser
.id
.toLowerCase() ) {
689 parsers
.push( parser
);
693 formatDigit: function( s
) {
694 if ( ts
.transformTable
!== false ) {
697 for ( var p
= 0; p
< s
.length
; p
++ ) {
699 if ( c
in ts
.transformTable
) {
700 out
+= ts
.transformTable
[c
];
707 var i
= parseFloat( s
.replace( /[, ]/g, '' ).replace( "\u2212", '-' ) );
708 return ( isNaN(i
)) ? 0 : i
;
711 formatFloat: function( s
) {
712 var i
= parseFloat(s
);
713 return ( isNaN(i
)) ? 0 : i
;
716 formatInt: function( s
) {
717 var i
= parseInt( s
, 10 );
718 return ( isNaN(i
)) ? 0 : i
;
721 clearTableBody: function( table
) {
722 if ( $.browser
.msie
) {
723 var empty = function( el
) {
724 while ( el
.firstChild
) {
725 el
.removeChild( el
.firstChild
);
728 empty( table
.tBodies
[0] );
730 table
.tBodies
[0].innerHTML
= '';
738 // Register as jQuery prototype method
739 $.fn
.tablesorter = function( settings
) {
740 return ts
.construct( this, settings
);
743 // Add default parsers
749 format: function( s
) {
750 s
= $.trim( s
.toLowerCase() );
751 if ( ts
.collationRegex
) {
752 var tsc
= ts
.collationTable
;
753 s
= s
.replace( ts
.collationRegex
, function( match
) {
754 var r
= tsc
[match
] ? tsc
[match
] : tsc
[match
.toUpperCase()];
755 return r
.toLowerCase();
766 return ts
.rgx
.IPAddress
[0].test(s
);
768 format: function( s
) {
769 var a
= s
.split( '.' ),
772 for ( var i
= 0; i
< l
; i
++ ) {
774 if ( item
.length
== 1 ) {
776 } else if ( item
.length
== 2 ) {
782 return $.tablesorter
.formatFloat(r
);
790 return ts
.rgx
.currency
[0].test(s
);
792 format: function( s
) {
793 return $.tablesorter
.formatDigit( s
.replace( ts
.rgx
.currency
[1], '' ) );
801 return ts
.rgx
.url
[0].test(s
);
803 format: function( s
) {
804 return $.trim( s
.replace( ts
.rgx
.url
[1], '' ) );
812 return ts
.rgx
.isoDate
[0].test(s
);
814 format: function( s
) {
815 return $.tablesorter
.formatFloat((s
!== '') ? new Date(s
.replace(
816 new RegExp( /-/g), '/')).getTime() : '0' );
824 return ts.rgx.usLongDate[0].test(s);
826 format: function( s ) {
827 return $.tablesorter.formatFloat( new Date(s).getTime() );
835 return ( ts.dateRegex[0].test(s) || ts.dateRegex[1].test(s) || ts.dateRegex[2].test(s ));
837 format: function( s, table ) {
838 s = $.trim( s.toLowerCase() );
840 for ( var i = 1, j = 0; i < 13 && j < 2; i++ ) {
841 s = s.replace( ts.monthNames[j][i], i );
848 s = s.replace( /[\-\.\,' ]/g
, '/' );
850 // Replace double slashes
851 s
= s
.replace( /\/\//g, '/' );
852 s
= s
.replace( /\/\//g, '/' );
856 if ( s
[0] && s
[0].length
== 1 ) {
859 if ( s
[1] && s
[1].length
== 1 ) {
865 // Fix yearless dates
867 } else if ( ( y
= parseInt( s
[2], 10) ) < 100 ) {
868 // Guestimate years without centuries
875 // Resort array depending on preferences
876 if ( mw
.config
.get( 'wgDefaultDateFormat' ) == 'mdy' || mw
.config
.get( 'wgContentLanguage' ) == 'en' ) {
879 } else if ( mw
.config
.get( 'wgDefaultDateFormat' ) == 'dmy' ) {
884 return parseInt( s
.join( '' ), 10 );
892 return ts
.rgx
.time
[0].test(s
);
894 format: function( s
) {
895 return $.tablesorter
.formatFloat( new Date( '2000/01/01 ' + s
).getTime() );
902 is: function( s
, table
) {
903 return $.tablesorter
.numberRegex
.test( $.trim( s
));
905 format: function( s
) {
906 return $.tablesorter
.formatDigit(s
);