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
59 ( function ( $, mw
) {
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( 'sortType' );
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
) ? -1 : ((a
> b
) ? 1 : 0) );
336 function sortTextDesc( a
, b
) {
337 return ( (b
< a
) ? -1 : ((b
> a
) ? 1 : 0) );
340 function multisort( table
, sortList
, cache
) {
342 var len
= sortList
.length
;
343 for ( var i
= 0; i
< len
; i
++ ) {
344 sortFn
[i
] = ( sortList
[i
][1] ) ? sortTextDesc
: sortText
;
346 cache
.normalized
.sort( function ( array1
, array2
) {
348 for ( var i
= 0; i
< len
; i
++ ) {
349 col
= sortList
[i
][0];
350 ret
= sortFn
[i
].call( this, array1
[col
], array2
[col
] );
355 // Fall back to index number column to ensure stable sort
356 return sortText
.call( this, array1
[array1
.length
- 1], array2
[array2
.length
- 1] );
361 function buildTransformTable() {
362 var digits
= '0123456789,.'.split( '' );
363 var separatorTransformTable
= mw
.config
.get( 'wgSeparatorTransformTable' );
364 var digitTransformTable
= mw
.config
.get( 'wgDigitTransformTable' );
365 if ( separatorTransformTable
=== null || ( separatorTransformTable
[0] === '' && digitTransformTable
[2] === '' ) ) {
366 ts
.transformTable
= false;
368 ts
.transformTable
= {};
370 // Unpack the transform table
371 var ascii
= separatorTransformTable
[0].split( "\t" ).concat( digitTransformTable
[0].split( "\t" ) );
372 var localised
= separatorTransformTable
[1].split( "\t" ).concat( digitTransformTable
[1].split( "\t" ) );
374 // Construct regex for number identification
375 for ( var i
= 0; i
< ascii
.length
; i
++ ) {
376 ts
.transformTable
[localised
[i
]] = ascii
[i
];
377 digits
.push( $.escapeRE( localised
[i
] ) );
380 var digitClass
= '[' + digits
.join( '', digits
) + ']';
382 // We allow a trailing percent sign, which we just strip. This works fine
383 // if percents and regular numbers aren't being mixed.
384 ts
.numberRegex
= new RegExp("^(" + "[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?" + // Fortran-style scientific
385 "|" + "[-+\u2212]?" + digitClass
+ "+[\\s\\xa0]*%?" + // Generic localised
389 function buildDateTable() {
393 for ( var i
= 1; i
< 13; i
++ ) {
394 var name
= mw
.config
.get( 'wgMonthNames' )[i
].toLowerCase();
395 ts
.monthNames
[name
] = i
;
396 regex
.push( $.escapeRE( name
) );
397 name
= mw
.config
.get( 'wgMonthNamesShort' )[i
].toLowerCase().replace( '.', '' );
398 ts
.monthNames
[name
] = i
;
399 regex
.push( $.escapeRE( name
) );
402 // Build piped string
403 regex
= regex
.join( '|' );
406 // Any date formated with . , ' - or /
407 ts
.dateRegex
[0] = new RegExp( /^\s*(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{2,4})\s*?/i);
409 // Written Month name, dmy
410 ts
.dateRegex
[1] = new RegExp( '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]*(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]*(\\d{2,4})\\s*$', 'i' );
412 // Written Month name, mdy
413 ts
.dateRegex
[2] = new RegExp( '^\\s*(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]*(\\d{1,2})[\\,\\.\\-\\/\'\\s]*(\\d{2,4})\\s*$', 'i' );
417 function explodeRowspans( $table
) {
418 // Split multi row cells into multiple cells with the same content
419 $table
.find( '> tbody > tr > [rowspan]' ).each(function () {
420 var rowSpan
= this.rowSpan
;
422 var cell
= $( this );
423 var next
= cell
.parent().nextAll();
424 for ( var i
= 0; i
< rowSpan
- 1; i
++ ) {
425 var td
= next
.eq( i
).children( 'td' );
427 next
.eq( i
).append( cell
.clone() );
428 } else if ( this.cellIndex
=== 0 ) {
429 td
.eq( this.cellIndex
).before( cell
.clone() );
431 td
.eq( this.cellIndex
- 1 ).after( cell
.clone() );
437 function buildCollationTable() {
438 ts
.collationTable
= mw
.config
.get( 'tableSorterCollation' );
439 ts
.collationRegex
= null;
440 if ( ts
.collationTable
) {
443 // Build array of key names
444 for ( var key
in ts
.collationTable
) {
445 if ( ts
.collationTable
.hasOwnProperty(key
) ) { //to be safe
450 ts
.collationRegex
= new RegExp( '[' + keys
.join( '' ) + ']', 'ig' );
455 function cacheRegexs() {
461 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/)
464 new RegExp( /(^[£$€¥]|[£$€¥]$)/),
465 new RegExp( /[£$€¥]/g)
468 new RegExp( /^(https?|ftp|file):\/\/$/),
469 new RegExp( /(https?|ftp|file):\/\//)
472 new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/)
475 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)))$/)
478 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/)
488 cssHeader
: 'headerSort',
489 cssAsc
: 'headerSortUp',
490 cssDesc
: 'headerSortDown',
491 cssChildRow
: 'expand-child',
492 sortInitialOrder
: 'asc',
493 sortMultiSortKey
: 'shiftKey',
494 sortLocaleCompare
: false,
498 cancelSelection
: true,
501 selectorHeaders
: 'thead tr:eq(0) th',
509 * @param $tables {jQuery}
510 * @param settings {Object} (optional)
512 construct: function ( $tables
, settings
) {
513 return $tables
.each( function ( i
, table
) {
514 // Declare and cache.
515 var $document
, $headers
, cache
, config
, sortOrder
,
521 if ( !table
.tBodies
) {
524 if ( !table
.tHead
) {
525 // No thead found. Look for rows with <th>s and
526 // move them into a <thead> tag or a <tfoot> tag
527 emulateTHeadAndFoot( $table
);
529 // Still no thead? Then quit
530 if ( !table
.tHead
) {
534 $table
.addClass( "jquery-tablesorter" );
536 // New config object.
540 config
= $.extend( table
.config
, $.tablesorter
.defaultOptions
, settings
);
542 // Save the settings where they read
543 $.data( table
, 'tablesorter', config
);
545 // Get the CSS class names, could be done else where.
546 var sortCSS
= [ config
.cssDesc
, config
.cssAsc
];
547 var sortMsg
= [ mw
.msg( 'sort-descending' ), mw
.msg( 'sort-ascending' ) ];
550 $headers
= buildHeaders( table
, sortMsg
);
552 // Grab and process locale settings
553 buildTransformTable();
555 buildCollationTable();
557 // Precaching regexps can bring 10 fold
558 // performance improvements in some browsers.
561 // Apply event handling to headers
562 // this is too big, perhaps break it out?
563 $headers
.click( function ( e
) {
564 if ( e
.target
.nodeName
.toLowerCase() === 'a' ) {
565 // The user clicked on a link inside a table header
566 // Do nothing and let the default link click action continue
573 // Legacy fix of .sortbottoms
574 // Wrap them inside inside a tfoot (because that's what they actually want to be) &
575 // and put the <tfoot> at the end of the <table>
576 var $sortbottoms
= $table
.find( '> tbody > tr.sortbottom' );
577 if ( $sortbottoms
.length
) {
578 var $tfoot
= $table
.children( 'tfoot' );
579 if ( $tfoot
.length
) {
580 $tfoot
.eq(0).prepend( $sortbottoms
);
582 $table
.append( $( '<tfoot>' ).append( $sortbottoms
) );
586 explodeRowspans( $table
);
587 // try to auto detect column type, and store in tables config
588 table
.config
.parsers
= buildParserCache( table
, $headers
);
591 // Build the cache for the tbody cells
592 // to share between calculations for this sort action.
593 // Re-calculated each time a sort action is performed due to possiblity
594 // that sort values change. Shouldn't be too expensive, but if it becomes
595 // too slow an event based system should be implemented somehow where
596 // cells get event .change() and bubbles up to the <table> here
597 cache
= buildCache( table
);
599 var totalRows
= ( $table
[0].tBodies
[0] && $table
[0].tBodies
[0].rows
.length
) || 0;
600 if ( !table
.sortDisabled
&& totalRows
> 0 ) {
602 // Cache jQuery object
603 var $cell
= $( this );
605 // Get current column index
608 // Get current column sort order
609 this.order
= this.count
% 2;
612 // User only wants to sort on one column
613 if ( !e
[config
.sortMultiSortKey
] ) {
614 // Flush the sort list
615 config
.sortList
= [];
616 // Add column to sort list
617 config
.sortList
.push( [i
, this.order
] );
619 // Multi column sorting
621 // The user has clicked on an already sorted column.
622 if ( isValueInArray( i
, config
.sortList
) ) {
623 // Reverse the sorting direction for all tables.
624 for ( var j
= 0; j
< config
.sortList
.length
; j
++ ) {
625 var s
= config
.sortList
[j
],
626 o
= config
.headerList
[s
[0]];
634 // Add column to sort list array
635 config
.sortList
.push( [i
, this.order
] );
639 // Set CSS for headers
640 setHeadersCss( $table
[0], $headers
, config
.sortList
, sortCSS
, sortMsg
);
642 $table
[0], multisort( $table
[0], config
.sortList
, cache
)
645 // Stop normal event by returning false
650 } ).mousedown( function () {
651 if ( config
.cancelSelection
) {
652 this.onselectstart = function () {
661 addParser: function ( parser
) {
662 var l
= parsers
.length
,
664 for ( var i
= 0; i
< l
; i
++ ) {
665 if ( parsers
[i
].id
.toLowerCase() === parser
.id
.toLowerCase() ) {
670 parsers
.push( parser
);
674 formatDigit: function ( s
) {
675 if ( ts
.transformTable
!== false ) {
678 for ( var p
= 0; p
< s
.length
; p
++ ) {
680 if ( c
in ts
.transformTable
) {
681 out
+= ts
.transformTable
[c
];
688 var i
= parseFloat( s
.replace( /[, ]/g, '' ).replace( "\u2212", '-' ) );
689 return ( isNaN(i
)) ? 0 : i
;
692 formatFloat: function ( s
) {
693 var i
= parseFloat(s
);
694 return ( isNaN(i
)) ? 0 : i
;
697 formatInt: function ( s
) {
698 var i
= parseInt( s
, 10 );
699 return ( isNaN(i
)) ? 0 : i
;
702 clearTableBody: function ( table
) {
703 if ( $.browser
.msie
) {
704 var empty = function ( el
) {
705 while ( el
.firstChild
) {
706 el
.removeChild( el
.firstChild
);
709 empty( table
.tBodies
[0] );
711 table
.tBodies
[0].innerHTML
= '';
719 // Register as jQuery prototype method
720 $.fn
.tablesorter = function ( settings
) {
721 return ts
.construct( this, settings
);
724 // Add default parsers
730 format: function ( s
) {
731 s
= $.trim( s
.toLowerCase() );
732 if ( ts
.collationRegex
) {
733 var tsc
= ts
.collationTable
;
734 s
= s
.replace( ts
.collationRegex
, function ( match
) {
735 var r
= tsc
[match
] ? tsc
[match
] : tsc
[match
.toUpperCase()];
736 return r
.toLowerCase();
747 return ts
.rgx
.IPAddress
[0].test(s
);
749 format: function ( s
) {
750 var a
= s
.split( '.' ),
753 for ( var i
= 0; i
< l
; i
++ ) {
755 if ( item
.length
=== 1 ) {
757 } else if ( item
.length
=== 2 ) {
763 return $.tablesorter
.formatFloat(r
);
771 return ts
.rgx
.currency
[0].test(s
);
773 format: function ( s
) {
774 return $.tablesorter
.formatDigit( s
.replace( ts
.rgx
.currency
[1], '' ) );
782 return ts
.rgx
.url
[0].test(s
);
784 format: function ( s
) {
785 return $.trim( s
.replace( ts
.rgx
.url
[1], '' ) );
793 return ts
.rgx
.isoDate
[0].test(s
);
795 format: function ( s
) {
796 return $.tablesorter
.formatFloat((s
!== '') ? new Date(s
.replace(
797 new RegExp( /-/g), '/')).getTime() : '0' );
805 return ts.rgx.usLongDate[0].test(s);
807 format: function ( s ) {
808 return $.tablesorter.formatFloat( new Date(s).getTime() );
816 return ( ts.dateRegex[0].test(s) || ts.dateRegex[1].test(s) || ts.dateRegex[2].test(s ));
818 format: function ( s, table ) {
820 s = $.trim( s.toLowerCase() );
822 if ( ( match = s.match( ts.dateRegex[0] ) ) !== null ) {
823 if ( mw.config.get( 'wgDefaultDateFormat
' ) === 'mdy
' || mw.config.get( 'wgContentLanguage
' ) === 'en
' ) {
824 s = [ match[3], match[1], match[2] ];
825 } else if ( mw.config.get( 'wgDefaultDateFormat
' ) === 'dmy
' ) {
826 s = [ match[3], match[2], match[1] ];
828 } else if ( ( match = s.match( ts.dateRegex[1] ) ) !== null ) {
829 s = [ match[3], '' + ts.monthNames[match[2]], match[1] ];
830 } else if ( ( match = s.match( ts.dateRegex[2] ) ) !== null ) {
831 s = [ match[3], '' + ts.monthNames[match[1]], match[2] ];
833 // Should never get here
838 if ( s[1].length === 1 ) {
841 if ( s[2].length === 1 ) {
846 if ( ( y = parseInt( s[0], 10) ) < 100 ) {
847 // Guestimate years without centuries
854 while ( s[0].length < 4 ) {
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);
884 }( jQuery, mediaWiki ) );