0030b4cb3083d60348ebb92b76b5f3bcf811c99c
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.
227 * @param $table jQuery object for a <table>
229 function emulateTHead( $table
) {
230 var $thead
= $( '<thead>' );
231 $table
.find( 'tr' ).each( function() {
232 if ( $(this).children( 'td' ).length
> 0 ) {
233 // This row contains a <td>, so it's not a header row
237 $thead
.append( this );
239 $table
.prepend( $thead
);
242 function buildHeaders( table
, msg
) {
246 $tableHeaders
= $( 'thead:eq(0) tr', table
);
247 if ( $tableHeaders
.length
> 1 ) {
248 $tableHeaders
.each( function() {
249 if ( this.cells
.length
> maxSeen
) {
250 maxSeen
= this.cells
.length
;
254 $tableHeaders
= $( longest
);
256 $tableHeaders
= $tableHeaders
.find( 'th' ).each( function( index
) {
257 this.column
= realCellIndex
;
259 var colspan
= this.colspan
;
260 colspan
= colspan
? parseInt( colspan
, 10 ) : 1;
261 realCellIndex
+= colspan
;
266 if ( $( this ).is( '.unsortable' ) ) {
267 this.sortDisabled
= true;
270 if ( !this.sortDisabled
) {
271 var $th
= $( this ).addClass( table
.config
.cssHeader
).attr( 'title', msg
[1] );
274 // add cell to headerList
275 table
.config
.headerList
[index
] = this;
278 return $tableHeaders
;
282 function isValueInArray( v
, a
) {
284 for ( var i
= 0; i
< l
; i
++ ) {
285 if ( a
[i
][0] == v
) {
292 function setHeadersCss( table
, $headers
, list
, css
, msg
) {
293 // Remove all header information
294 $headers
.removeClass( css
[0] ).removeClass( css
[1] );
297 $headers
.each( function( offset
) {
298 if ( !this.sortDisabled
) {
299 h
[this.column
] = $( this );
304 for ( var i
= 0; i
< l
; i
++ ) {
305 h
[ list
[i
][0] ].addClass( css
[ list
[i
][1] ] ).attr( 'title', msg
[ list
[i
][1] ] );
309 function sortText( a
, b
) {
310 return ( (a
< b
) ? false : ((a
> b
) ? true : 0) );
313 function sortTextDesc( a
, b
) {
314 return ( (b
< a
) ? false : ((b
> a
) ? true : 0) );
317 function checkSorting( array1
, array2
, sortList
) {
319 for ( var i
= 0, len
= sortList
.length
; i
< len
; i
++ ) {
320 col
= sortList
[i
][0];
321 fn
= ( sortList
[i
][1] ) ? sortTextDesc
: sortText
;
322 ret
= fn
.call( this, array1
[col
], array2
[col
] );
330 // Merge sort algorithm
331 // Based on http://en.literateprograms.org/Merge_sort_(JavaScript)
332 function mergeSortHelper( array
, begin
, beginRight
, end
, sortList
) {
333 for ( ; begin
< beginRight
; ++begin
) {
334 if ( checkSorting( array
[begin
], array
[beginRight
], sortList
) ) {
335 var v
= array
[begin
];
336 array
[begin
] = array
[beginRight
];
337 var begin2
= beginRight
;
338 while ( begin2
+ 1 < end
&& checkSorting( v
, array
[begin2
+ 1], sortList
) ) {
339 var tmp
= array
[begin2
];
340 array
[begin2
] = array
[begin2
+ 1];
341 array
[begin2
+ 1] = tmp
;
349 function mergeSort(array
, begin
, end
, sortList
) {
350 var size
= end
- begin
;
355 var beginRight
= begin
+ Math
.floor(size
/ 2);
357 mergeSort( array
, begin
, beginRight
, sortList
);
358 mergeSort( array
, beginRight
, end
, sortList
);
359 mergeSortHelper( array
, begin
, beginRight
, end
, sortList
);
362 function multisort( table
, sortList
, cache
) {
363 var i
= sortList
.length
;
364 mergeSort( cache
.normalized
, 0, cache
.normalized
.length
, sortList
);
369 function buildTransformTable() {
370 var digits
= '0123456789,.'.split( '' );
371 var separatorTransformTable
= mw
.config
.get( 'wgSeparatorTransformTable' );
372 var digitTransformTable
= mw
.config
.get( 'wgDigitTransformTable' );
373 if ( separatorTransformTable
=== null || ( separatorTransformTable
[0] === '' && digitTransformTable
[2] === '' ) ) {
374 ts
.transformTable
= false;
376 ts
.transformTable
= {};
378 // Unpack the transform table
379 var ascii
= separatorTransformTable
[0].split( "\t" ).concat( digitTransformTable
[0].split( "\t" ) );
380 var localised
= separatorTransformTable
[1].split( "\t" ).concat( digitTransformTable
[1].split( "\t" ) );
382 // Construct regex for number identification
383 for ( var i
= 0; i
< ascii
.length
; i
++ ) {
384 ts
.transformTable
[localised
[i
]] = ascii
[i
];
385 digits
.push( $.escapeRE( localised
[i
] ) );
388 var digitClass
= '[' + digits
.join( '', digits
) + ']';
390 // We allow a trailing percent sign, which we just strip. This works fine
391 // if percents and regular numbers aren't being mixed.
392 ts
.numberRegex
= new RegExp("^(" + "[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?" + // Fortran-style scientific
393 "|" + "[-+\u2212]?" + digitClass
+ "+[\\s\\xa0]*%?" + // Generic localised
397 function buildDateTable() {
404 for ( var i
= 1; i
< 13; i
++ ) {
405 ts
.monthNames
[0][i
] = mw
.config
.get( 'wgMonthNames' )[i
].toLowerCase();
406 ts
.monthNames
[1][i
] = mw
.config
.get( 'wgMonthNamesShort' )[i
].toLowerCase().replace( '.', '' );
407 regex
.push( $.escapeRE( ts
.monthNames
[0][i
] ) );
408 regex
.push( $.escapeRE( ts
.monthNames
[1][i
] ) );
411 // Build piped string
412 regex
= regex
.join( '|' );
415 // Any date formated with . , ' - or /
416 ts
.dateRegex
[0] = new RegExp( /^\s*\d{1,2}[\,\.\-\/'\s]{1,2}\d{1,2}[\,\.\-\/'\s]{1,2}\d{2,4}\s*?/i);
418 // Written Month name, dmy
419 ts
.dateRegex
[1] = new RegExp( '^\\s*\\d{1,2}[\\,\\.\\-\\/\'\\s]*(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]*\\d{2,4}\\s*$', 'i' );
421 // Written Month name, mdy
422 ts
.dateRegex
[2] = new RegExp( '^\\s*(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]*\\d{1,2}[\\,\\.\\-\\/\'\\s]*\\d{2,4}\\s*$', 'i' );
426 function explodeRowspans( $table
) {
427 // Split multi row cells into multiple cells with the same content
428 $table
.find( '[rowspan]' ).each(function() {
429 var rowSpan
= this.rowSpan
;
431 var cell
= $( this );
432 var next
= cell
.parent().nextAll();
433 for ( var i
= 0; i
< rowSpan
- 1; i
++ ) {
434 var td
= next
.eq( i
).find( 'td' );
436 next
.eq( i
).append( cell
.clone() );
437 } else if ( this.cellIndex
=== 0 ) {
438 td
.eq( this.cellIndex
).before( cell
.clone() );
440 td
.eq( this.cellIndex
- 1 ).after( cell
.clone() );
446 function buildCollationTable() {
447 ts
.collationTable
= mw
.config
.get( 'tableSorterCollation' );
448 ts
.collationRegex
= null;
449 if ( ts
.collationTable
) {
452 // Build array of key names
453 for ( var key
in ts
.collationTable
) {
454 if ( ts
.collationTable
.hasOwnProperty(key
) ) { //to be safe
459 ts
.collationRegex
= new RegExp( '[' + keys
.join( '' ) + ']', 'ig' );
464 function cacheRegexs() {
470 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/)
473 new RegExp( /^[£$€?.]/),
474 new RegExp( /[£$€]/g)
477 new RegExp( /^(https?|ftp|file):\/\/$/),
478 new RegExp( /(https?|ftp|file):\/\//)
481 new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/)
484 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)))$/)
487 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/)
497 cssHeader
: 'headerSort',
498 cssAsc
: 'headerSortUp',
499 cssDesc
: 'headerSortDown',
500 cssChildRow
: 'expand-child',
501 sortInitialOrder
: 'asc',
502 sortMultiSortKey
: 'shiftKey',
503 sortLocaleCompare
: false,
507 cancelSelection
: true,
510 selectorHeaders
: 'thead tr:eq(0) th',
518 * @param $tables {jQuery}
519 * @param settings {Object} (optional)
521 construct: function( $tables
, settings
) {
522 return $tables
.each( function( i
, table
) {
523 // Declare and cache.
524 var $document
, $headers
, cache
, config
, sortOrder
,
530 if ( !table
.tBodies
) {
533 if ( !table
.tHead
) {
534 // No thead found. Look for rows with <th>s and
535 // move them into a <thead> tag
536 emulateTHead( $table
);
538 // Still no thead? Then quit
539 if ( !table
.tHead
) {
543 $table
.addClass( "jquery-tablesorter" );
545 // New config object.
549 config
= $.extend( table
.config
, $.tablesorter
.defaultOptions
, settings
);
551 // Save the settings where they read
552 $.data( table
, 'tablesorter', config
);
554 // Get the CSS class names, could be done else where.
555 var sortCSS
= [ config
.cssDesc
, config
.cssAsc
];
556 var sortMsg
= [ mw
.msg( 'sort-descending' ), mw
.msg( 'sort-ascending' ) ];
559 $headers
= buildHeaders( table
, sortMsg
);
561 // Grab and process locale settings
562 buildTransformTable();
564 buildCollationTable();
566 // Precaching regexps can bring 10 fold
567 // performance improvements in some browsers.
570 // Apply event handling to headers
571 // this is to big, perhaps break it out?
572 $headers
.click( function( e
) {
577 // Legacy fix of .sortbottoms
578 // Wrap them inside inside a tfoot (because that's what they actually want to be) &
579 // and put the <tfoot> at the end of the <table>
580 var $sortbottoms
= $table
.find( 'tr.sortbottom' );
581 if ( $sortbottoms
.length
) {
582 $table
.append( $( '<tfoot>' ).append( $sortbottoms
) )
585 explodeRowspans( $table
);
586 // try to auto detect column type, and store in tables config
587 table
.config
.parsers
= buildParserCache( table
, $headers
);
588 // build the cache for the tbody cells
589 cache
= buildCache( table
);
591 var totalRows
= ( $table
[0].tBodies
[0] && $table
[0].tBodies
[0].rows
.length
) || 0;
592 if ( !table
.sortDisabled
&& totalRows
> 0 ) {
594 // Cache jQuery object
595 var $cell
= $( this );
597 // Get current column index
600 // Get current column sort order
601 this.order
= this.count
% 2;
604 // User only wants to sort on one column
605 if ( !e
[config
.sortMultiSortKey
] ) {
606 // Flush the sort list
607 config
.sortList
= [];
608 // Add column to sort list
609 config
.sortList
.push( [i
, this.order
] );
611 // Multi column sorting
613 // The user has clicked on an already sorted column.
614 if ( isValueInArray( i
, config
.sortList
) ) {
615 // Reverse the sorting direction for all tables.
616 for ( var j
= 0; j
< config
.sortList
.length
; j
++ ) {
617 var s
= config
.sortList
[j
],
618 o
= config
.headerList
[s
[0]];
626 // Add column to sort list array
627 config
.sortList
.push( [i
, this.order
] );
631 // Set CSS for headers
632 setHeadersCss( $table
[0], $headers
, config
.sortList
, sortCSS
, sortMsg
);
634 $table
[0], multisort( $table
[0], config
.sortList
, cache
)
637 // Stop normal event by returning false
642 } ).mousedown( function() {
643 if ( config
.cancelSelection
) {
644 this.onselectstart = function() {
654 addParser: function( parser
) {
655 var l
= parsers
.length
,
657 for ( var i
= 0; i
< l
; i
++ ) {
658 if ( parsers
[i
].id
.toLowerCase() == parser
.id
.toLowerCase() ) {
663 parsers
.push( parser
);
667 formatDigit: function( s
) {
668 if ( ts
.transformTable
!== false ) {
671 for ( var p
= 0; p
< s
.length
; p
++ ) {
673 if ( c
in ts
.transformTable
) {
674 out
+= ts
.transformTable
[c
];
681 var i
= parseFloat( s
.replace( /[, ]/g, '' ).replace( "\u2212", '-' ) );
682 return ( isNaN(i
)) ? 0 : i
;
685 formatFloat: function( s
) {
686 var i
= parseFloat(s
);
687 return ( isNaN(i
)) ? 0 : i
;
690 formatInt: function( s
) {
691 var i
= parseInt( s
, 10 );
692 return ( isNaN(i
)) ? 0 : i
;
695 clearTableBody: function( table
) {
696 if ( $.browser
.msie
) {
697 var empty = function( el
) {
698 while ( el
.firstChild
) {
699 el
.removeChild( el
.firstChild
);
702 empty( table
.tBodies
[0] );
704 table
.tBodies
[0].innerHTML
= '';
712 // Register as jQuery prototype method
713 $.fn
.tablesorter = function( settings
) {
714 return ts
.construct( this, settings
);
717 // Add default parsers
723 format: function( s
) {
724 s
= $.trim( s
.toLowerCase() );
725 if ( ts
.collationRegex
) {
726 var tsc
= ts
.collationTable
;
727 s
= s
.replace( ts
.collationRegex
, function( match
) {
728 var r
= tsc
[match
] ? tsc
[match
] : tsc
[match
.toUpperCase()];
729 return r
.toLowerCase();
740 return ts
.rgx
.IPAddress
[0].test(s
);
742 format: function( s
) {
743 var a
= s
.split( '.' ),
746 for ( var i
= 0; i
< l
; i
++ ) {
748 if ( item
.length
== 1 ) {
750 } else if ( item
.length
== 2 ) {
756 return $.tablesorter
.formatFloat(r
);
764 return ts
.rgx
.currency
[0].test(s
);
766 format: function( s
) {
767 return $.tablesorter
.formatDigit( s
.replace( ts
.rgx
.currency
[1], '' ) );
775 return ts
.rgx
.url
[0].test(s
);
777 format: function( s
) {
778 return $.trim( s
.replace( ts
.rgx
.url
[1], '' ) );
786 return ts
.rgx
.isoDate
[0].test(s
);
788 format: function( s
) {
789 return $.tablesorter
.formatFloat((s
!== '') ? new Date(s
.replace(
790 new RegExp( /-/g), '/')).getTime() : '0' );
798 return ts.rgx.usLongDate[0].test(s);
800 format: function( s ) {
801 return $.tablesorter.formatFloat( new Date(s).getTime() );
809 return ( ts.dateRegex[0].test(s) || ts.dateRegex[1].test(s) || ts.dateRegex[2].test(s ));
811 format: function( s, table ) {
812 s = $.trim( s.toLowerCase() );
814 for ( var i = 1, j = 0; i < 13 && j < 2; i++ ) {
815 s = s.replace( ts.monthNames[j][i], i );
822 s = s.replace( /[\-\.\,' ]/g
, '/' );
824 // Replace double slashes
825 s
= s
.replace( /\/\//g, '/' );
826 s
= s
.replace( /\/\//g, '/' );
830 if ( s
[0] && s
[0].length
== 1 ) {
833 if ( s
[1] && s
[1].length
== 1 ) {
839 // Fix yearless dates
841 } else if ( ( y
= parseInt( s
[2], 10) ) < 100 ) {
842 // Guestimate years without centuries
849 // Resort array depending on preferences
850 if ( mw
.config
.get( 'wgDefaultDateFormat' ) == 'mdy' || mw
.config
.get( 'wgContentLanguage' ) == 'en' ) {
853 } else if ( mw
.config
.get( 'wgDefaultDateFormat' ) == 'dmy' ) {
858 return parseInt( s
.join( '' ), 10 );
866 return ts
.rgx
.time
[0].test(s
);
868 format: function( s
) {
869 return $.tablesorter
.formatFloat( new Date( '2000/01/01 ' + s
).getTime() );
876 is: function( s
, table
) {
877 return $.tablesorter
.numberRegex
.test( $.trim( s
));
879 format: function( s
) {
880 return $.tablesorter
.formatDigit(s
);