21e1f968e8e942aea464189582dc0ca231dd22b8
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() {
418 for ( var i
= 1; i
< 13; i
++ ) {
419 var name
= mw
.config
.get( 'wgMonthNames' )[i
].toLowerCase();
420 ts
.monthNames
[name
] = i
;
421 regex
.push( $.escapeRE( name
) );
422 name
= mw
.config
.get( 'wgMonthNamesShort' )[i
].toLowerCase().replace( '.', '' );
423 ts
.monthNames
[name
] = i
;
424 regex
.push( $.escapeRE( name
) );
427 // Build piped string
428 regex
= regex
.join( '|' );
431 // Any date formated with . , ' - or /
432 ts
.dateRegex
[0] = new RegExp( /^\s*(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{2,4})\s*?/i);
434 // Written Month name, dmy
435 ts
.dateRegex
[1] = new RegExp( '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]*(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]*(\\d{2,4})\\s*$', 'i' );
437 // Written Month name, mdy
438 ts
.dateRegex
[2] = new RegExp( '^\\s*(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]*(\\d{1,2})[\\,\\.\\-\\/\'\\s]*(\\d{2,4})\\s*$', 'i' );
442 function explodeRowspans( $table
) {
443 // Split multi row cells into multiple cells with the same content
444 $table
.find( '> tbody > tr > [rowspan]' ).each(function() {
445 var rowSpan
= this.rowSpan
;
447 var cell
= $( this );
448 var next
= cell
.parent().nextAll();
449 for ( var i
= 0; i
< rowSpan
- 1; i
++ ) {
450 var td
= next
.eq( i
).children( 'td' );
452 next
.eq( i
).append( cell
.clone() );
453 } else if ( this.cellIndex
=== 0 ) {
454 td
.eq( this.cellIndex
).before( cell
.clone() );
456 td
.eq( this.cellIndex
- 1 ).after( cell
.clone() );
462 function buildCollationTable() {
463 ts
.collationTable
= mw
.config
.get( 'tableSorterCollation' );
464 ts
.collationRegex
= null;
465 if ( ts
.collationTable
) {
468 // Build array of key names
469 for ( var key
in ts
.collationTable
) {
470 if ( ts
.collationTable
.hasOwnProperty(key
) ) { //to be safe
475 ts
.collationRegex
= new RegExp( '[' + keys
.join( '' ) + ']', 'ig' );
480 function cacheRegexs() {
486 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/)
489 new RegExp( /^[£$€?.]/),
490 new RegExp( /[£$€]/g)
493 new RegExp( /^(https?|ftp|file):\/\/$/),
494 new RegExp( /(https?|ftp|file):\/\//)
497 new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/)
500 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)))$/)
503 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/)
513 cssHeader
: 'headerSort',
514 cssAsc
: 'headerSortUp',
515 cssDesc
: 'headerSortDown',
516 cssChildRow
: 'expand-child',
517 sortInitialOrder
: 'asc',
518 sortMultiSortKey
: 'shiftKey',
519 sortLocaleCompare
: false,
523 cancelSelection
: true,
526 selectorHeaders
: 'thead tr:eq(0) th',
534 * @param $tables {jQuery}
535 * @param settings {Object} (optional)
537 construct: function( $tables
, settings
) {
538 return $tables
.each( function( i
, table
) {
539 // Declare and cache.
540 var $document
, $headers
, cache
, config
, sortOrder
,
546 if ( !table
.tBodies
) {
549 if ( !table
.tHead
) {
550 // No thead found. Look for rows with <th>s and
551 // move them into a <thead> tag or a <tfoot> tag
552 emulateTHeadAndFoot( $table
);
554 // Still no thead? Then quit
555 if ( !table
.tHead
) {
559 $table
.addClass( "jquery-tablesorter" );
561 // New config object.
565 config
= $.extend( table
.config
, $.tablesorter
.defaultOptions
, settings
);
567 // Save the settings where they read
568 $.data( table
, 'tablesorter', config
);
570 // Get the CSS class names, could be done else where.
571 var sortCSS
= [ config
.cssDesc
, config
.cssAsc
];
572 var sortMsg
= [ mw
.msg( 'sort-descending' ), mw
.msg( 'sort-ascending' ) ];
575 $headers
= buildHeaders( table
, sortMsg
);
577 // Grab and process locale settings
578 buildTransformTable();
580 buildCollationTable();
582 // Precaching regexps can bring 10 fold
583 // performance improvements in some browsers.
586 // Apply event handling to headers
587 // this is too big, perhaps break it out?
588 $headers
.click( function( e
) {
589 if ( e
.target
.nodeName
.toLowerCase() == 'a' ) {
590 // The user clicked on a link inside a table header
591 // Do nothing and let the default link click action continue
598 // Legacy fix of .sortbottoms
599 // Wrap them inside inside a tfoot (because that's what they actually want to be) &
600 // and put the <tfoot> at the end of the <table>
601 var $sortbottoms
= $table
.find( '> tbody > tr.sortbottom' );
602 if ( $sortbottoms
.length
) {
603 var $tfoot
= $table
.children( 'tfoot' );
604 if ( $tfoot
.length
) {
605 $tfoot
.eq(0).prepend( $sortbottoms
);
607 $table
.append( $( '<tfoot>' ).append( $sortbottoms
) );
611 explodeRowspans( $table
);
612 // try to auto detect column type, and store in tables config
613 table
.config
.parsers
= buildParserCache( table
, $headers
);
614 // build the cache for the tbody cells
615 cache
= buildCache( table
);
617 var totalRows
= ( $table
[0].tBodies
[0] && $table
[0].tBodies
[0].rows
.length
) || 0;
618 if ( !table
.sortDisabled
&& totalRows
> 0 ) {
620 // Cache jQuery object
621 var $cell
= $( this );
623 // Get current column index
626 // Get current column sort order
627 this.order
= this.count
% 2;
630 // User only wants to sort on one column
631 if ( !e
[config
.sortMultiSortKey
] ) {
632 // Flush the sort list
633 config
.sortList
= [];
634 // Add column to sort list
635 config
.sortList
.push( [i
, this.order
] );
637 // Multi column sorting
639 // The user has clicked on an already sorted column.
640 if ( isValueInArray( i
, config
.sortList
) ) {
641 // Reverse the sorting direction for all tables.
642 for ( var j
= 0; j
< config
.sortList
.length
; j
++ ) {
643 var s
= config
.sortList
[j
],
644 o
= config
.headerList
[s
[0]];
652 // Add column to sort list array
653 config
.sortList
.push( [i
, this.order
] );
657 // Set CSS for headers
658 setHeadersCss( $table
[0], $headers
, config
.sortList
, sortCSS
, sortMsg
);
660 $table
[0], multisort( $table
[0], config
.sortList
, cache
)
663 // Stop normal event by returning false
668 } ).mousedown( function() {
669 if ( config
.cancelSelection
) {
670 this.onselectstart = function() {
679 addParser: function( parser
) {
680 var l
= parsers
.length
,
682 for ( var i
= 0; i
< l
; i
++ ) {
683 if ( parsers
[i
].id
.toLowerCase() == parser
.id
.toLowerCase() ) {
688 parsers
.push( parser
);
692 formatDigit: function( s
) {
693 if ( ts
.transformTable
!== false ) {
696 for ( var p
= 0; p
< s
.length
; p
++ ) {
698 if ( c
in ts
.transformTable
) {
699 out
+= ts
.transformTable
[c
];
706 var i
= parseFloat( s
.replace( /[, ]/g, '' ).replace( "\u2212", '-' ) );
707 return ( isNaN(i
)) ? 0 : i
;
710 formatFloat: function( s
) {
711 var i
= parseFloat(s
);
712 return ( isNaN(i
)) ? 0 : i
;
715 formatInt: function( s
) {
716 var i
= parseInt( s
, 10 );
717 return ( isNaN(i
)) ? 0 : i
;
720 clearTableBody: function( table
) {
721 if ( $.browser
.msie
) {
722 var empty = function( el
) {
723 while ( el
.firstChild
) {
724 el
.removeChild( el
.firstChild
);
727 empty( table
.tBodies
[0] );
729 table
.tBodies
[0].innerHTML
= '';
737 // Register as jQuery prototype method
738 $.fn
.tablesorter = function( settings
) {
739 return ts
.construct( this, settings
);
742 // Add default parsers
748 format: function( s
) {
749 s
= $.trim( s
.toLowerCase() );
750 if ( ts
.collationRegex
) {
751 var tsc
= ts
.collationTable
;
752 s
= s
.replace( ts
.collationRegex
, function( match
) {
753 var r
= tsc
[match
] ? tsc
[match
] : tsc
[match
.toUpperCase()];
754 return r
.toLowerCase();
765 return ts
.rgx
.IPAddress
[0].test(s
);
767 format: function( s
) {
768 var a
= s
.split( '.' ),
771 for ( var i
= 0; i
< l
; i
++ ) {
773 if ( item
.length
== 1 ) {
775 } else if ( item
.length
== 2 ) {
781 return $.tablesorter
.formatFloat(r
);
789 return ts
.rgx
.currency
[0].test(s
);
791 format: function( s
) {
792 return $.tablesorter
.formatDigit( s
.replace( ts
.rgx
.currency
[1], '' ) );
800 return ts
.rgx
.url
[0].test(s
);
802 format: function( s
) {
803 return $.trim( s
.replace( ts
.rgx
.url
[1], '' ) );
811 return ts
.rgx
.isoDate
[0].test(s
);
813 format: function( s
) {
814 return $.tablesorter
.formatFloat((s
!== '') ? new Date(s
.replace(
815 new RegExp( /-/g), '/')).getTime() : '0' );
823 return ts.rgx.usLongDate[0].test(s);
825 format: function( s ) {
826 return $.tablesorter.formatFloat( new Date(s).getTime() );
834 return ( ts.dateRegex[0].test(s) || ts.dateRegex[1].test(s) || ts.dateRegex[2].test(s ));
836 format: function( s, table ) {
837 s = $.trim( s.toLowerCase() );
840 if ( ( match = s.match( ts.dateRegex[0] ) ) !== null ) {
841 if ( mw.config.get( 'wgDefaultDateFormat
' ) == 'mdy
' || mw.config.get( 'wgContentLanguage
' ) == 'en
' ) {
842 s = [ match[3], match[1], match[2] ];
843 } else if ( mw.config.get( 'wgDefaultDateFormat
' ) == 'dmy
' ) {
844 s = [ match[3], match[2], match[1] ];
846 } else if ( ( match = s.match( ts.dateRegex[1] ) ) !== null ) {
847 s = [ match[3], '' + ts.monthNames[match[2]], match[1] ];
848 } else if ( ( match = s.match( ts.dateRegex[2] ) ) !== null ) {
849 s = [ match[3], '' + ts.monthNames[match[1]], match[2] ];
851 // Should never get here
856 if ( s[1].length == 1 ) {
859 if ( s[2].length == 1 ) {
864 if ( ( y = parseInt( s[0], 10) ) < 100 ) {
865 // Guestimate years without centuries
872 while ( s[0].length < 4 ) {
875 return parseInt( s.join( '' ), 10 );
883 return ts.rgx.time[0].test(s);
885 format: function( s ) {
886 return $.tablesorter.formatFloat( new Date( '2000/01/01 ' + s ).getTime() );
893 is: function( s, table ) {
894 return $.tablesorter.numberRegex.test( $.trim( s ));
896 format: function( s ) {
897 return $.tablesorter.formatDigit(s);