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)
16 * @description Create a sortable table with multi-column sorting capabilitys
18 * @example $( 'table' ).tablesorter();
19 * @desc Create a simple tablesorter interface.
21 * @option String cssHeader ( optional ) A string of the class name to be appended
22 * to sortable tr elements in the thead of the table. Default value:
25 * @option String cssAsc ( optional ) A string of the class name to be appended to
26 * sortable tr elements in the thead on a ascending sort. Default value:
29 * @option String cssDesc ( optional ) A string of the class name to be appended
30 * to sortable tr elements in the thead on a descending sort. Default
31 * value: "headerSortDown"
33 * @option String sortInitialOrder ( optional ) A string of the inital sorting
34 * order can be asc or desc. Default value: "asc"
36 * @option String sortMultisortKey ( optional ) A string of the multi-column sort
37 * key. Default value: "shiftKey"
39 * @option Boolean sortLocaleCompare ( optional ) Boolean flag indicating whatever
40 * to use String.localeCampare method or not. Set to false.
42 * @option Boolean cancelSelection ( optional ) Boolean flag indicating if
43 * tablesorter should cancel selection of the table headers text.
46 * @option Boolean debug ( optional ) Boolean flag indicating if tablesorter
47 * should display debuging information usefull for development.
53 * @cat Plugins/Tablesorter
55 * @author Christian Bach/christian.bach@polyester.se
65 /* Parser utility functions */
67 function getParserById( name
) {
68 var len
= parsers
.length
;
69 for ( var i
= 0; i
< len
; i
++ ) {
70 if ( parsers
[i
].id
.toLowerCase() === name
.toLowerCase() ) {
77 function getElementText( node
) {
78 if ( node
.hasAttribute
&& node
.hasAttribute( 'data-sort-value' ) ) {
79 return node
.getAttribute( 'data-sort-value' );
81 return $( node
).text();
85 function getTextFromRowAndCellIndex( rows
, rowIndex
, cellIndex
) {
86 if ( rows
[rowIndex
] && rows
[rowIndex
].cells
[cellIndex
] ) {
87 return $.trim( getElementText( rows
[rowIndex
].cells
[cellIndex
] ) );
93 function detectParserForColumn( table
, rows
, cellIndex
) {
94 var l
= parsers
.length
,
96 // Start with 1 because 0 is the fallback parser
100 needed
= ( rows
.length
> 4 ) ? 5 : rows
.length
;
103 nodeValue
= getTextFromRowAndCellIndex( rows
, rowIndex
, cellIndex
);
104 if ( nodeValue
!== '') {
105 if ( parsers
[i
].is( nodeValue
, table
) ) {
108 if ( concurrent
>= needed
) {
109 // Confirmed the parser for multiple cells, let's return it
113 // Check next parser, reset rows
121 if ( rowIndex
> rows
.length
) {
128 // 0 is always the generic parser (text)
132 function buildParserCache( table
, $headers
) {
133 var rows
= table
.tBodies
[0].rows
,
139 var cells
= rows
[0].cells
,
143 for ( i
= 0; i
< len
; i
++ ) {
145 sortType
= $headers
.eq( i
).data( 'sort-type' );
146 if ( sortType
!== undefined ) {
147 parser
= getParserById( sortType
);
150 if ( parser
=== false ) {
151 parser
= detectParserForColumn( table
, rows
, i
);
154 parsers
.push( parser
);
160 /* Other utility functions */
162 function buildCache( table
) {
163 var totalRows
= ( table
.tBodies
[0] && table
.tBodies
[0].rows
.length
) || 0,
164 totalCells
= ( table
.tBodies
[0].rows
[0] && table
.tBodies
[0].rows
[0].cells
.length
) || 0,
165 parsers
= table
.config
.parsers
,
171 for ( var i
= 0; i
< totalRows
; ++i
) {
173 // Add the table data to main data array
174 var $row
= $( table
.tBodies
[0].rows
[i
] ),
177 // if this is a child row, add it to the last row's children and
178 // continue to the next row
179 if ( $row
.hasClass( table
.config
.cssChildRow
) ) {
180 cache
.row
[cache
.row
.length
- 1] = cache
.row
[cache
.row
.length
- 1].add( $row
);
181 // go to the next for loop
185 cache
.row
.push( $row
);
187 for ( var j
= 0; j
< totalCells
; ++j
) {
188 cols
.push( parsers
[j
].format( getElementText( $row
[0].cells
[j
] ), table
, $row
[0].cells
[j
] ) );
191 cols
.push( cache
.normalized
.length
); // add position for rowCache
192 cache
.normalized
.push( cols
);
199 function appendToTable( table
, cache
) {
201 normalized
= cache
.normalized
,
202 totalRows
= normalized
.length
,
203 checkCell
= ( normalized
[0].length
- 1 ),
204 fragment
= document
.createDocumentFragment();
206 for ( var i
= 0; i
< totalRows
; i
++ ) {
207 var pos
= normalized
[i
][checkCell
];
209 var l
= row
[pos
].length
;
211 for ( var j
= 0; j
< l
; j
++ ) {
212 fragment
.appendChild( row
[pos
][j
] );
216 table
.tBodies
[0].appendChild( fragment
);
219 function buildHeaders( table
, msg
) {
223 $tableHeaders
= $( 'thead:eq(0) tr', table
);
224 if ( $tableHeaders
.length
> 1 ) {
225 $tableHeaders
.each(function() {
226 if ( this.cells
.length
> maxSeen
) {
227 maxSeen
= this.cells
.length
;
231 $tableHeaders
= $( longest
);
233 $tableHeaders
= $tableHeaders
.find( 'th' ).each( function( index
) {
234 this.column
= realCellIndex
;
236 var colspan
= this.colspan
;
237 colspan
= colspan
? parseInt( colspan
, 10 ) : 1;
238 realCellIndex
+= colspan
;
243 if ( $( this ).is( '.unsortable' ) ) {
244 this.sortDisabled
= true;
247 if ( !this.sortDisabled
) {
248 var $th
= $( this ).addClass( table
.config
.cssHeader
).attr( 'title', msg
[1] );
251 // add cell to headerList
252 table
.config
.headerList
[index
] = this;
255 return $tableHeaders
;
259 function isValueInArray( v
, a
) {
261 for ( var i
= 0; i
< l
; i
++ ) {
262 if ( a
[i
][0] == v
) {
269 function setHeadersCss( table
, $headers
, list
, css
, msg
) {
270 // Remove all header information
271 $headers
.removeClass( css
[0] ).removeClass( css
[1] );
274 $headers
.each( function( offset
) {
275 if ( !this.sortDisabled
) {
276 h
[this.column
] = $( this );
281 for ( var i
= 0; i
< l
; i
++ ) {
282 h
[ list
[i
][0] ].addClass( css
[ list
[i
][1] ] ).attr( 'title', msg
[ list
[i
][1] ] );
286 function sortText( a
, b
) {
287 return ( (a
< b
) ? false : ((a
> b
) ? true : 0) );
290 function sortTextDesc( a
, b
) {
291 return ( (b
< a
) ? false : ((b
> a
) ? true : 0) );
294 function checkSorting( array1
, array2
, sortList
) {
296 for ( var i
= 0, len
= sortList
.length
; i
< len
; i
++ ) {
297 col
= sortList
[i
][0];
298 fn
= ( sortList
[i
][1] ) ? sortTextDesc
: sortText
;
299 ret
= fn
.call( this, array1
[col
], array2
[col
] );
307 // Merge sort algorithm
308 // Based on http://en.literateprograms.org/Merge_sort_(JavaScript)
309 function mergeSortHelper( array
, begin
, beginRight
, end
, sortList
) {
310 for ( ; begin
< beginRight
; ++begin
) {
311 if ( checkSorting( array
[begin
], array
[beginRight
], sortList
) ) {
312 var v
= array
[begin
];
313 array
[begin
] = array
[beginRight
];
314 var begin2
= beginRight
;
315 while ( begin2
+ 1 < end
&& checkSorting( v
, array
[begin2
+ 1], sortList
) ) {
316 var tmp
= array
[begin2
];
317 array
[begin2
] = array
[begin2
+ 1];
318 array
[begin2
+ 1] = tmp
;
326 function mergeSort(array
, begin
, end
, sortList
) {
327 var size
= end
- begin
;
332 var beginRight
= begin
+ Math
.floor(size
/ 2);
334 mergeSort( array
, begin
, beginRight
, sortList
);
335 mergeSort( array
, beginRight
, end
, sortList
);
336 mergeSortHelper( array
, begin
, beginRight
, end
, sortList
);
339 function multisort( table
, sortList
, cache
) {
340 var i
= sortList
.length
;
341 mergeSort( cache
.normalized
, 0, cache
.normalized
.length
, sortList
);
346 function buildTransformTable() {
347 var digits
= '0123456789,.'.split( '' );
348 var separatorTransformTable
= mw
.config
.get( 'wgSeparatorTransformTable' );
349 var digitTransformTable
= mw
.config
.get( 'wgDigitTransformTable' );
350 if ( separatorTransformTable
=== null || ( separatorTransformTable
[0] === '' && digitTransformTable
[2] === '' ) ) {
351 ts
.transformTable
= false;
353 ts
.transformTable
= {};
355 // Unpack the transform table
356 var ascii
= separatorTransformTable
[0].split( "\t" ).concat( digitTransformTable
[0].split( "\t" ) );
357 var localised
= separatorTransformTable
[1].split( "\t" ).concat( digitTransformTable
[1].split( "\t" ) );
359 // Construct regex for number identification
360 for ( var i
= 0; i
< ascii
.length
; i
++ ) {
361 ts
.transformTable
[localised
[i
]] = ascii
[i
];
362 digits
.push( $.escapeRE( localised
[i
] ) );
365 var digitClass
= '[' + digits
.join( '', digits
) + ']';
367 // We allow a trailing percent sign, which we just strip. This works fine
368 // if percents and regular numbers aren't being mixed.
369 ts
.numberRegex
= new RegExp("^(" + "[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?" + // Fortran-style scientific
370 "|" + "[-+\u2212]?" + digitClass
+ "+[\\s\\xa0]*%?" + // Generic localised
374 function buildDateTable() {
381 for ( var i
= 1; i
< 13; i
++ ) {
382 ts
.monthNames
[0][i
] = mw
.config
.get( 'wgMonthNames' )[i
].toLowerCase();
383 ts
.monthNames
[1][i
] = mw
.config
.get( 'wgMonthNamesShort' )[i
].toLowerCase().replace( '.', '' );
384 regex
.push( $.escapeRE( ts
.monthNames
[0][i
] ) );
385 regex
.push( $.escapeRE( ts
.monthNames
[1][i
] ) );
388 // Build piped string
389 regex
= regex
.join( '|' );
392 // Any date formated with . , ' - or /
393 ts
.dateRegex
[0] = new RegExp( /^\s*\d{1,2}[\,\.\-\/'\s]{1,2}\d{1,2}[\,\.\-\/'\s]{1,2}\d{2,4}\s*?/i);
395 // Written Month name, dmy
396 ts
.dateRegex
[1] = new RegExp( '^\\s*\\d{1,2}[\\,\\.\\-\\/\'\\s]*(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]*\\d{2,4}\\s*$', 'i' );
398 // Written Month name, mdy
399 ts
.dateRegex
[2] = new RegExp( '^\\s*(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]*\\d{1,2}[\\,\\.\\-\\/\'\\s]*\\d{2,4}\\s*$', 'i' );
403 function explodeRowspans( $table
) {
404 // Split multi row cells into multiple cells with the same content
405 $table
.find( '[rowspan]' ).each(function() {
406 var rowSpan
= this.rowSpan
;
408 var cell
= $( this );
409 var next
= cell
.parent().nextAll();
410 for ( var i
= 0; i
< rowSpan
- 1; i
++ ) {
411 var td
= next
.eq( i
).find( 'td' );
413 next
.eq( i
).append( cell
.clone() );
414 } else if ( this.cellIndex
=== 0 ) {
415 td
.eq( this.cellIndex
).before( cell
.clone() );
417 td
.eq( this.cellIndex
- 1 ).after( cell
.clone() );
423 function buildCollationTable() {
424 ts
.collationTable
= mw
.config
.get( 'tableSorterCollation' );
425 ts
.collationRegex
= null;
426 if ( ts
.collationTable
) {
429 // Build array of key names
430 for ( var key
in ts
.collationTable
) {
431 if ( ts
.collationTable
.hasOwnProperty(key
) ) { //to be safe
436 ts
.collationRegex
= new RegExp( '[' + keys
.join( '' ) + ']', 'ig' );
441 function cacheRegexs() {
447 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/)
450 new RegExp( /^[£$€?.]/),
451 new RegExp( /[£$€]/g)
454 new RegExp( /^(https?|ftp|file):\/\/$/),
455 new RegExp( /(https?|ftp|file):\/\//)
458 new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/)
461 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)))$/)
464 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/)
474 cssHeader
: 'headerSort',
475 cssAsc
: 'headerSortUp',
476 cssDesc
: 'headerSortDown',
477 cssChildRow
: 'expand-child',
478 sortInitialOrder
: 'asc',
479 sortMultiSortKey
: 'shiftKey',
480 sortLocaleCompare
: false,
484 cancelSelection
: true,
487 selectorHeaders
: 'thead tr:eq(0) th',
495 * @param $tables {jQuery}
496 * @param settings {Object} (optional)
498 construct: function( $tables
, settings
) {
499 return $tables
.each( function( i
, table
) {
501 // Quit if no thead or tbody.
502 if ( !table
.tHead
|| !table
.tBodies
) {
505 // Declare and cache.
506 var $document
, $headers
, cache
, config
, sortOrder
,
511 // New config object.
515 config
= $.extend( table
.config
, $.tablesorter
.defaultOptions
, settings
);
517 // Save the settings where they read
518 $.data( table
, 'tablesorter', config
);
520 // Get the CSS class names, could be done else where.
521 var sortCSS
= [ config
.cssDesc
, config
.cssAsc
];
522 var sortMsg
= [ mw
.msg( 'sort-descending' ), mw
.msg( 'sort-ascending' ) ];
525 $headers
= buildHeaders( table
, sortMsg
);
527 // Grab and process locale settings
528 buildTransformTable();
530 buildCollationTable();
532 // Precaching regexps can bring 10 fold
533 // performance improvements in some browsers.
536 // Apply event handling to headers
537 // this is to big, perhaps break it out?
538 $headers
.click( function( e
) {
543 // Legacy fix of .sortbottoms
544 // Wrap them inside inside a tfoot (because that's what they actually want to be) &
545 // Move them up one level in the DOM
546 var sortbottoms
= $table
.find('tr.sortbottom').wrap('<tfoot>');
547 sortbottoms
.parents('table').append(sortbottoms
.parent());
549 explodeRowspans( $table
);
550 // try to auto detect column type, and store in tables config
551 table
.config
.parsers
= buildParserCache( table
, $headers
);
552 // build the cache for the tbody cells
553 cache
= buildCache( table
);
555 var totalRows
= ( $table
[0].tBodies
[0] && $table
[0].tBodies
[0].rows
.length
) || 0;
556 if ( !table
.sortDisabled
&& totalRows
> 0 ) {
558 // Cache jQuery object
559 var $cell
= $( this );
561 // Get current column index
564 // Get current column sort order
565 this.order
= this.count
% 2;
568 // User only wants to sort on one column
569 if ( !e
[config
.sortMultiSortKey
] ) {
570 // Flush the sort list
571 config
.sortList
= [];
572 // Add column to sort list
573 config
.sortList
.push( [i
, this.order
] );
575 // Multi column sorting
577 // The user has clicked on an already sorted column.
578 if ( isValueInArray( i
, config
.sortList
) ) {
579 // Reverse the sorting direction for all tables.
580 for ( var j
= 0; j
< config
.sortList
.length
; j
++ ) {
581 var s
= config
.sortList
[j
],
582 o
= config
.headerList
[s
[0]];
590 // Add column to sort list array
591 config
.sortList
.push( [i
, this.order
] );
595 // Set CSS for headers
596 setHeadersCss( $table
[0], $headers
, config
.sortList
, sortCSS
, sortMsg
);
598 $table
[0], multisort( $table
[0], config
.sortList
, cache
)
601 // Stop normal event by returning false
606 } ).mousedown( function() {
607 if ( config
.cancelSelection
) {
608 this.onselectstart = function() {
618 addParser: function( parser
) {
619 var l
= parsers
.length
,
621 for ( var i
= 0; i
< l
; i
++ ) {
622 if ( parsers
[i
].id
.toLowerCase() == parser
.id
.toLowerCase() ) {
627 parsers
.push( parser
);
631 formatDigit: function( s
) {
632 if ( ts
.transformTable
!== false ) {
635 for ( var p
= 0; p
< s
.length
; p
++ ) {
637 if ( c
in ts
.transformTable
) {
638 out
+= ts
.transformTable
[c
];
645 var i
= parseFloat( s
.replace( /[, ]/g, '' ).replace( "\u2212", '-' ) );
646 return ( isNaN(i
)) ? 0 : i
;
649 formatFloat: function( s
) {
650 var i
= parseFloat(s
);
651 return ( isNaN(i
)) ? 0 : i
;
654 formatInt: function( s
) {
655 var i
= parseInt( s
, 10 );
656 return ( isNaN(i
)) ? 0 : i
;
659 clearTableBody: function( table
) {
660 if ( $.browser
.msie
) {
661 var empty = function( el
) {
662 while ( el
.firstChild
) {
663 el
.removeChild( el
.firstChild
);
666 empty( table
.tBodies
[0] );
668 table
.tBodies
[0].innerHTML
= '';
676 // Register as jQuery prototype method
677 $.fn
.tablesorter = function( settings
) {
678 return ts
.construct( this, settings
);
681 // Add default parsers
687 format: function( s
) {
688 s
= $.trim( s
.toLowerCase() );
689 if ( ts
.collationRegex
) {
690 var tsc
= ts
.collationTable
;
691 s
= s
.replace( ts
.collationRegex
, function( match
) {
692 var r
= tsc
[match
] ? tsc
[match
] : tsc
[match
.toUpperCase()];
693 return r
.toLowerCase();
704 return ts
.rgx
.IPAddress
[0].test(s
);
706 format: function( s
) {
707 var a
= s
.split( '.' ),
710 for ( var i
= 0; i
< l
; i
++ ) {
712 if ( item
.length
== 1 ) {
714 } else if ( item
.length
== 2 ) {
720 return $.tablesorter
.formatFloat(r
);
728 return ts
.rgx
.currency
[0].test(s
);
730 format: function( s
) {
731 return $.tablesorter
.formatDigit( s
.replace( ts
.rgx
.currency
[1], '' ) );
739 return ts
.rgx
.url
[0].test(s
);
741 format: function( s
) {
742 return $.trim( s
.replace( ts
.rgx
.url
[1], '' ) );
750 return ts
.rgx
.isoDate
[0].test(s
);
752 format: function( s
) {
753 return $.tablesorter
.formatFloat((s
!== '') ? new Date(s
.replace(
754 new RegExp( /-/g), '/')).getTime() : '0' );
762 return ts.rgx.usLongDate[0].test(s);
764 format: function( s ) {
765 return $.tablesorter.formatFloat( new Date(s).getTime() );
773 return ( ts.dateRegex[0].test(s) || ts.dateRegex[1].test(s) || ts.dateRegex[2].test(s ));
775 format: function( s, table ) {
776 s = $.trim( s.toLowerCase() );
778 for ( var i = 1, j = 0; i < 13 && j < 2; i++ ) {
779 s = s.replace( ts.monthNames[j][i], i );
786 s = s.replace( /[\-\.\,' ]/g
, '/' );
788 // Replace double slashes
789 s
= s
.replace( /\/\//g, '/' );
790 s
= s
.replace( /\/\//g, '/' );
794 if ( s
[0] && s
[0].length
== 1 ) {
797 if ( s
[1] && s
[1].length
== 1 ) {
803 // Fix yearless dates
805 } else if ( ( y
= parseInt( s
[2], 10) ) < 100 ) {
806 // Guestimate years without centuries
813 // Resort array depending on preferences
814 if ( mw
.config
.get( 'wgDefaultDateFormat' ) == 'mdy' || mw
.config
.get( 'wgContentLanguage' ) == 'en' ) {
817 } else if ( mw
.config
.get( 'wgDefaultDateFormat' ) == 'dmy' ) {
822 return parseInt( s
.join( '' ), 10 );
830 return ts
.rgx
.time
[0].test(s
);
832 format: function( s
) {
833 return $.tablesorter
.formatFloat( new Date( '2000/01/01 ' + s
).getTime() );
840 is: function( s
, table
) {
841 return $.tablesorter
.numberRegex
.test( $.trim( s
));
843 format: function( s
) {
844 return $.tablesorter
.formatDigit(s
);