3 * TableSorter for MediaWiki
5 * Written 2011 Leo Koppelkamm
6 * Based on tablesorter.com plugin, written (c) 2007 Christian Bach.
8 * Dual licensed under the MIT and GPL licenses:
9 * http://www.opensource.org/licenses/mit-license.php
10 * http://www.gnu.org/licenses/gpl.html
15 * @description Create a sortable table with multi-column sorting capabilitys
17 * @example $( 'table' ).tablesorter();
18 * @desc Create a simple tablesorter interface.
20 * @option String cssHeader ( optional ) A string of the class name to be appended
21 * to sortable tr elements in the thead of the table. Default value:
24 * @option String cssAsc ( optional ) A string of the class name to be appended to
25 * sortable tr elements in the thead on a ascending sort. Default value:
28 * @option String cssDesc ( optional ) A string of the class name to be appended
29 * to sortable tr elements in the thead on a descending sort. Default
30 * value: "headerSortDown"
32 * @option String sortInitialOrder ( optional ) A string of the inital sorting
33 * order can be asc or desc. Default value: "asc"
35 * @option String sortMultisortKey ( optional ) A string of the multi-column sort
36 * key. Default value: "shiftKey"
38 * @option Boolean sortLocaleCompare ( optional ) Boolean flag indicating whatever
39 * to use String.localeCampare method or not. Set to false.
41 * @option Boolean cancelSelection ( optional ) Boolean flag indicating if
42 * tablesorter should cancel selection of the table headers text.
45 * @option Boolean debug ( optional ) Boolean flag indicating if tablesorter
46 * should display debuging information usefull for development.
52 * @cat Plugins/Tablesorter
54 * @author Christian Bach/christian.bach@polyester.se
66 cssHeader
: "headerSort",
67 cssAsc
: "headerSortUp",
68 cssDesc
: "headerSortDown",
69 cssChildRow
: "expand-child",
70 sortInitialOrder
: "asc",
71 sortMultiSortKey
: "shiftKey",
72 sortLocaleCompare
: false,
76 cancelSelection
: true,
79 selectorHeaders
: 'thead tr:eq(0) th',
85 // function benchmark( s, d ) {
86 // console.log( s + " " + ( new Date().getTime() - d.getTime() ) + "ms" );
89 // this.benchmark = benchmark;
93 function buildParserCache( table
, $headers
) {
94 var rows
= table
.tBodies
[0].rows
,
100 cells
= rows
[0].cells
,
103 for ( var i
= 0; i
< l
; i
++ ) {
105 sortType
= $headers
.eq(i
).data('sort-type');
106 if ( typeof sortType
!= 'undefined' ) {
107 p
= getParserById( sortType
);
111 p
= detectParserForColumn( table
, rows
, i
);
113 // if ( table.config.debug ) {
114 // console.log( "column:" + i + " parser:" + p.id + "\n" );
122 function detectParserForColumn( table
, rows
, cellIndex
) {
123 var l
= parsers
.length
,
125 // Start with 1 because 0 is the fallback parser
129 needed
= (rows
.length
> 4 ) ? 5 : rows
.length
;
131 nodeValue
= getTextFromRowAndCellIndex( rows
, rowIndex
, cellIndex
);
132 if ( nodeValue
!= '') {
133 if ( parsers
[i
].is( nodeValue
, table
) ) {
136 if (concurrent
>= needed
) {
137 // Confirmed the parser for multiple cells, let's return it
141 // Check next parser, reset rows
149 if ( rowIndex
> rows
.length
) {
156 // 0 is always the generic parser ( text )
160 function getTextFromRowAndCellIndex( rows
, rowIndex
, cellIndex
) {
161 if ( rows
[rowIndex
] && rows
[rowIndex
].cells
[cellIndex
] ) {
162 return $.trim( getElementText( rows
[rowIndex
].cells
[cellIndex
] ) );
168 function getParserById( name
) {
169 var l
= parsers
.length
;
170 for ( var i
= 0; i
< l
; i
++ ) {
171 if ( parsers
[i
].id
.toLowerCase() == name
.toLowerCase() ) {
180 function buildCache( table
) {
181 // if ( table.config.debug ) {
182 // var cacheTime = new Date();
184 var totalRows
= ( table
.tBodies
[0] && table
.tBodies
[0].rows
.length
) || 0,
185 totalCells
= ( table
.tBodies
[0].rows
[0] && table
.tBodies
[0].rows
[0].cells
.length
) || 0,
186 parsers
= table
.config
.parsers
,
192 for ( var i
= 0; i
< totalRows
; ++i
) {
194 // Add the table data to main data array
195 var c
= $( table
.tBodies
[0].rows
[i
] ),
198 // if this is a child row, add it to the last row's children and
199 // continue to the next row
200 if ( c
.hasClass( table
.config
.cssChildRow
) ) {
201 cache
.row
[cache
.row
.length
- 1] = cache
.row
[cache
.row
.length
- 1].add(c
);
202 // go to the next for loop
208 for ( var j
= 0; j
< totalCells
; ++j
) {
209 cols
.push( parsers
[j
].format( getElementText( c
[0].cells
[j
] ), table
, c
[0].cells
[j
] ) );
212 cols
.push( cache
.normalized
.length
); // add position for rowCache
213 cache
.normalized
.push( cols
);
217 // if ( table.config.debug ) {
218 // benchmark( "Building cache for " + totalRows + " rows:", cacheTime );
223 function getElementText( node
) {
224 if ( node
.hasAttribute
&& node
.hasAttribute( "data-sort-value" ) ) {
225 return node
.getAttribute( "data-sort-value" );
227 return $( node
).text();
231 function appendToTable( table
, cache
) {
232 // if ( table.config.debug ) {
233 // var appendTime = new Date()
238 totalRows
= n
.length
,
239 checkCell
= (n
[0].length
- 1),
240 tableBody
= $( table
.tBodies
[0] ),
241 fragment
= document
.createDocumentFragment();
243 for ( var i
= 0; i
< totalRows
; i
++ ) {
244 var pos
= n
[i
][checkCell
];
246 var l
= r
[pos
].length
;
248 for ( var j
= 0; j
< l
; j
++ ) {
249 fragment
.appendChild( r
[pos
][j
] );
253 tableBody
[0].appendChild( fragment
);
254 // if ( table.config.debug ) {
255 // benchmark( "Rebuilt table:", appendTime );
259 function buildHeaders( table
, msg
) {
262 // if ( table.config.debug ) {
263 // var time = new Date();
265 //var header_index = computeTableHeaderCellIndexes( table );
266 var realCellIndex
= 0;
267 var $tableHeaders
= $( "thead:eq(0) tr", table
);
268 if ( $tableHeaders
.length
> 1 ) {
269 $tableHeaders
.each(function() {
270 if (this.cells
.length
> maxSeen
) {
271 maxSeen
= this.cells
.length
;
275 $tableHeaders
= $( longest
);
277 $tableHeaders
= $tableHeaders
.find('th').each( function ( index
) {
278 //var normalIndex = allCells.index( this );
279 //var realCellIndex = 0;
280 this.column
= realCellIndex
;
282 var colspan
= this.colspan
;
283 colspan
= colspan
? parseInt( colspan
, 10 ) : 1;
284 realCellIndex
+= colspan
;
286 //this.column = header_index[this.parentNode.rowIndex + "-" + this.cellIndex];
290 if ( $( this ).is( '.unsortable' ) ) this.sortDisabled
= true;
292 if ( !this.sortDisabled
) {
293 var $th
= $( this ).addClass( table
.config
.cssHeader
).attr( 'title', msg
[1] );
295 //if ( table.config.onRenderHeader ) table.config.onRenderHeader.apply($th);
298 // add cell to headerList
299 table
.config
.headerList
[index
] = this;
302 // if ( table.config.debug ) {
303 // benchmark( "Built headers:", time );
304 // console.log( $tableHeaders );
307 return $tableHeaders
;
311 function isValueInArray( v
, a
) {
313 for ( var i
= 0; i
< l
; i
++ ) {
314 if ( a
[i
][0] == v
) {
321 function setHeadersCss( table
, $headers
, list
, css
, msg
) {
322 // remove all header information
323 $headers
.removeClass( css
[0] ).removeClass( css
[1] );
326 $headers
.each( function ( offset
) {
327 if ( !this.sortDisabled
) {
328 h
[this.column
] = $( this );
333 for ( var i
= 0; i
< l
; i
++ ) {
334 h
[ list
[i
][0] ].addClass( css
[ list
[i
][1] ] ).attr( 'title', msg
[ list
[i
][1] ] );
338 function checkSorting (array1
, array2
, sortList
) {
340 for ( var i
= 0, len
= sortList
.length
; i
< len
; i
++ ) {
341 col
= sortList
[i
][0];
342 fn
= ( sortList
[i
][1] ) ? sortTextDesc
: sortText
;
343 ret
= fn
.call( this, array1
[col
], array2
[col
] );
351 // Merge sort algorithm
352 // Based on http://en.literateprograms.org/Merge_sort_(JavaScript)
353 function mergeSortHelper(array
, begin
, beginRight
, end
, sortList
) {
354 for (; begin
< beginRight
; ++begin
) {
355 if (checkSorting( array
[begin
], array
[beginRight
], sortList
)) {
356 var v
= array
[begin
];
357 array
[begin
] = array
[beginRight
];
358 var begin2
= beginRight
;
359 while ( begin2
+ 1 < end
&& checkSorting( v
, array
[begin2
+ 1], sortList
) ) {
360 var tmp
= array
[begin2
];
361 array
[begin2
] = array
[begin2
+ 1];
362 array
[begin2
+ 1] = tmp
;
370 function mergeSort(array
, begin
, end
, sortList
) {
371 var size
= end
- begin
;
372 if (size
< 2) return;
374 var beginRight
= begin
+ Math
.floor(size
/ 2);
376 mergeSort(array
, begin
, beginRight
, sortList
);
377 mergeSort(array
, beginRight
, end
, sortList
);
378 mergeSortHelper(array
, begin
, beginRight
, end
, sortList
);
381 function multisort( table
, sortList
, cache
) {
382 //var sortTime = new Date();
384 var i
= sortList
.length
;
385 mergeSort(cache
.normalized
, 0, cache
.normalized
.length
, sortList
);
387 //benchmark( "Sorting in dir " + order + " time:", sortTime );
392 function sortText( a
, b
) {
393 return ((a
< b
) ? false : ((a
> b
) ? true : 0));
396 function sortTextDesc( a
, b
) {
397 return ((b
< a
) ? false : ((b
> a
) ? true : 0));
400 function buildTransformTable() {
401 var digits
= '0123456789,.'.split('');
402 var separatorTransformTable
= mw
.config
.get( 'wgSeparatorTransformTable' );
403 var digitTransformTable
= mw
.config
.get( 'wgDigitTransformTable' );
404 if ( separatorTransformTable
== null || ( separatorTransformTable
[0] == '' && digitTransformTable
[2] == '' ) ) {
405 ts
.transformTable
= false;
407 ts
.transformTable
= {};
409 // Unpack the transform table
410 var ascii
= separatorTransformTable
[0].split( "\t" ).concat( digitTransformTable
[0].split( "\t" ) );
411 var localised
= separatorTransformTable
[1].split( "\t" ).concat( digitTransformTable
[1].split( "\t" ) );
413 // Construct regex for number identification
414 for ( var i
= 0; i
< ascii
.length
; i
++ ) {
415 ts
.transformTable
[localised
[i
]] = ascii
[i
];
416 digits
.push( $.escapeRE( localised
[i
] ) );
419 var digitClass
= '[' + digits
.join( '', digits
) + ']';
421 // We allow a trailing percent sign, which we just strip. This works fine
422 // if percents and regular numbers aren't being mixed.
423 ts
.numberRegex
= new RegExp("^(" + "[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?" + // Fortran-style scientific
424 "|" + "[-+\u2212]?" + digitClass
+ "+[\\s\\xa0]*%?" + // Generic localised
428 function buildDateTable() {
436 for ( var i
= 1; i
< 13; i
++ ) {
437 ts
.monthNames
[0][i
] = mw
.config
.get( 'wgMonthNames' )[i
].toLowerCase();
438 ts
.monthNames
[1][i
] = mw
.config
.get( 'wgMonthNamesShort' )[i
].toLowerCase().replace( '.', '' );
439 r
+= $.escapeRE( ts
.monthNames
[0][i
] ) + '|';
440 r
+= $.escapeRE( ts
.monthNames
[1][i
] ) + '|';
443 //Remove trailing pipe
444 r
= r
.slice( 0, -1 );
447 //Any date formated with . , ' - or /
448 ts
.dateRegex
[0] = new RegExp(/^\s*\d{1,2}[\,\.\-\/'\s]{1,2}\d{1,2}[\,\.\-\/'\s]{1,2}\d{2,4}\s*?/i);
450 //Written Month name, dmy
451 ts
.dateRegex
[1] = new RegExp('^\\s*\\d{1,2}[\\,\\.\\-\\/\'\\s]*(' + r
+ ')' + '[\\,\\.\\-\\/\'\\s]*\\d{2,4}\\s*$', 'i');
453 //Written Month name, mdy
454 ts
.dateRegex
[2] = new RegExp('^\\s*(' + r
+ ')' + '[\\,\\.\\-\\/\'\\s]*\\d{1,2}[\\,\\.\\-\\/\'\\s]*\\d{2,4}\\s*$', 'i');
458 function explodeRowspans( $table
) {
459 // Split multi row cells into multiple cells with the same content
460 $table
.find( '[rowspan]' ).each(function() {
461 var rowSpan
= this.rowSpan
;
463 var cell
= $( this );
464 var next
= cell
.parent().nextAll();
465 for ( var i
= 0; i
< rowSpan
- 1; i
++ ) {
466 var td
= next
.eq( i
).find( 'td' );
468 next
.eq( i
).append( cell
.clone() );
469 } else if ( this.cellIndex
== 0 ) {
470 td
.eq( this.cellIndex
).before( cell
.clone() );
472 td
.eq( this.cellIndex
- 1 ).after( cell
.clone() );
478 function buildCollationTable() {
479 ts
.collationTable
= mw
.config
.get('tableSorterCollation');
480 ts
.collationRegex
= null;
481 if ( ts
.collationTable
) {
484 //Build array of key names
485 for ( var key
in ts
.collationTable
) {
486 if ( ts
.collationTable
.hasOwnProperty(key
) ) { //to be safe
491 ts
.collationRegex
= new RegExp( '[' + keys
.join('') + ']', 'ig' );
496 function cacheRegexs() {
498 IPAddress
: [new RegExp(/^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/)],
499 currency
: [new RegExp(/^[£$€?.]/), new RegExp(/[£$€]/g)],
500 url
: [new RegExp(/^(https?|ftp|file):\/\/$/), new RegExp(/(https?|ftp|file):\/\//)],
501 isoDate
: [new RegExp(/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/)],
502 usLongDate
: [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 time
: [new RegExp(/^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/)]
505 } /* public methods */
506 this.construct = function ( settings
) {
507 return this.each( function () {
508 // if no thead or tbody quit.
509 if ( !this.tHead
|| !this.tBodies
) return;
511 var $this, $document
, $headers
, cache
, config
, shiftDown
= 0,
512 sortOrder
, firstTime
= true, that
= this;
513 // new blank config object
516 config
= $.extend( this.config
, $.tablesorter
.defaults
, settings
);
518 // store common expression for speed
520 // save the settings where they read
521 $.data( this, "tablesorter", config
);
523 // get the css class names, could be done else where.
524 var sortCSS
= [ config
.cssDesc
, config
.cssAsc
];
525 var sortMsg
= [ mw
.msg( 'sort-descending' ), mw
.msg( 'sort-ascending' ) ];
528 $headers
= buildHeaders( this, sortMsg
);
529 // Grab and process locale settings
530 buildTransformTable();
532 buildCollationTable();
534 //Precaching regexps can bring 10 fold
535 //performance improvements in some browsers
538 // apply event handling to headers
539 // this is to big, perhaps break it out?
543 //var clickTime= new Date();
546 explodeRowspans( $this );
547 // try to auto detect column type, and store in tables config
548 that
.config
.parsers
= buildParserCache( that
, $headers
);
549 // build the cache for the tbody cells
550 cache
= buildCache( that
);
552 var totalRows
= ( $this[0].tBodies
[0] && $this[0].tBodies
[0].rows
.length
) || 0;
553 if ( !this.sortDisabled
&& totalRows
> 0 ) {
554 // Only call sortStart if sorting is
556 //$this.trigger( "sortStart" );
558 // store exp, for speed
559 var $cell
= $( this );
560 // get current column index
562 // get current column sort order
563 this.order
= this.count
% 2;
565 // user only whants to sort on one
567 if ( !e
[config
.sortMultiSortKey
] ) {
568 // flush the sort list
569 config
.sortList
= [];
570 // add column to sort list
571 config
.sortList
.push( [i
, this.order
] );
572 // multi column sorting
574 // the user has clicked on an already sorted column.
575 if ( isValueInArray( i
, config
.sortList
) ) {
576 // revers the sorting direction
578 for ( var j
= 0; j
< config
.sortList
.length
; j
++ ) {
579 var s
= config
.sortList
[j
],
580 o
= config
.headerList
[s
[0]];
588 // add column to sort list array
589 config
.sortList
.push( [i
, this.order
] );
593 // set css for headers
594 setHeadersCss( $this[0], $headers
, config
.sortList
, sortCSS
, sortMsg
);
597 $this[0], config
.sortList
, cache
) );
598 //benchmark( "Sorting " + totalRows + " rows:", clickTime );
600 // stop normal event by returning false
604 } ).mousedown( function () {
605 if ( config
.cancelSelection
) {
606 this.onselectstart = function () {
612 // apply easy methods that trigger binded events
613 //Can't think of any use for these in a mw context
614 // $this.bind( "update", function () {
616 // setTimeout( function () {
617 // // rebuild parsers.
618 // me.config.parsers = buildParserCache(
620 // // rebuild the cache map
621 // cache = buildCache(me);
623 // } ).bind( "updateCell", function ( e, cell ) {
624 // var config = this.config;
625 // // get position from the dom.
626 // var pos = [( cell.parentNode.rowIndex - 1 ), cell.cellIndex];
628 // cache.normalized[pos[0]][pos[1]] = config.parsers[pos[1]].format(
629 // getElementText( cell ), cell );
630 // } ).bind( "sorton", function ( e, list ) {
631 // $( this ).trigger( "sortStart" );
632 // config.sortList = list;
633 // // update and store the sortlist
634 // var sortList = config.sortList;
635 // // update header count index
636 // updateHeaderSortCount( this, sortList );
637 // // set css for headers
638 // setHeadersCss( this, $headers, sortList, sortCSS );
639 // // sort the table and append it to the dom
640 // appendToTable( this, multisort( this, sortList, cache ) );
641 // } ).bind( "appendCache", function () {
642 // appendToTable( this, cache );
646 this.addParser = function ( parser
) {
647 var l
= parsers
.length
,
649 for ( var i
= 0; i
< l
; i
++ ) {
650 if ( parsers
[i
].id
.toLowerCase() == parser
.id
.toLowerCase() ) {
655 parsers
.push( parser
);
658 this.formatDigit = function (s
) {
659 if ( ts
.transformTable
!= false ) {
662 for ( var p
= 0; p
< s
.length
; p
++ ) {
664 if ( c
in ts
.transformTable
) {
665 out
+= ts
.transformTable
[c
];
672 var i
= parseFloat( s
.replace(/[, ]/g, '').replace( "\u2212", '-' ) );
673 return ( isNaN(i
)) ? 0 : i
;
675 this.formatFloat = function (s
) {
676 var i
= parseFloat(s
);
677 return ( isNaN(i
)) ? 0 : i
;
679 this.formatInt = function (s
) {
680 var i
= parseInt( s
, 10 );
681 return ( isNaN(i
)) ? 0 : i
;
683 this.clearTableBody = function ( table
) {
684 if ( $.browser
.msie
) {
686 while ( this.firstChild
)
687 this.removeChild( this.firstChild
);
689 empty
.apply( table
.tBodies
[0] );
691 table
.tBodies
[0].innerHTML
= "";
697 // extend plugin scope
699 tablesorter
: $.tablesorter
.construct
703 var ts
= $.tablesorter
;
705 // add default parsers
711 format: function (s
) {
712 s
= $.trim( s
.toLowerCase() );
713 if ( ts
.collationRegex
) {
714 var tsc
= ts
.collationTable
;
715 s
= s
.replace( ts
.collationRegex
, function ( match
) {
716 var r
= tsc
[match
] ? tsc
[match
] : tsc
[match
.toUpperCase()];
717 return r
.toLowerCase();
728 return ts
.rgx
.IPAddress
[0].test(s
);
730 format: function (s
) {
731 var a
= s
.split("."),
734 for ( var i
= 0; i
< l
; i
++ ) {
736 if ( item
.length
== 1 ) {
738 } else if ( item
.length
== 2 ) {
744 return $.tablesorter
.formatFloat(r
);
752 return ts
.rgx
.currency
[0].test(s
);
754 format: function (s
) {
755 return $.tablesorter
.formatDigit( s
.replace( ts
.rgx
.currency
[1], "" ) );
763 return ts
.rgx
.url
[0].test(s
);
765 format: function (s
) {
766 return $.trim( s
.replace( ts
.rgx
.url
[1], '' ) );
774 return ts
.rgx
.isoDate
[0].test(s
);
776 format: function (s
) {
777 return $.tablesorter
.formatFloat((s
!= "") ? new Date(s
.replace(
778 new RegExp(/-/g), "/")).getTime() : "0");
786 return ts.rgx.usLongDate[0].test(s);
788 format: function (s) {
789 return $.tablesorter.formatFloat( new Date(s).getTime() );
797 return ( ts.dateRegex[0].test(s) || ts.dateRegex[1].test(s) || ts.dateRegex[2].test(s ));
799 format: function ( s, table ) {
800 s = $.trim( s.toLowerCase() );
802 for ( var i = 1, j = 0; i < 13 && j < 2; i++ ) {
803 s = s.replace( ts.monthNames[j][i], i );
810 s = s.replace(/[\-\.\,' ]/g, "/");
812 //Replace double slashes
813 s = s.replace(/\/\//g, "/");
814 s = s.replace(/\/\//g, "/");
818 if ( s[0] && s[0].length == 1 ) s[0] = "0" + s[0];
819 if ( s[1] && s[1].length == 1 ) s[1] = "0" + s[1];
825 } else if ( ( y = parseInt( s[2], 10) ) < 100 ) {
826 //Guestimate years without centuries
833 //Resort array depending on preferences
834 if ( mw.config.get( 'wgDefaultDateFormat' ) == "mdy
" || mw.config.get('wgContentLanguage') == 'en' ) {
837 } else if ( mw.config.get( 'wgDefaultDateFormat' ) == "dmy
" ) {
842 return parseInt( s.join(''), 10 );
849 return ts.rgx.time[0].test(s);
851 format: function (s) {
852 return $.tablesorter.formatFloat( new Date( "2000/01/01 " + s ).getTime() );
858 is: function ( s, table ) {
859 return $.tablesorter.numberRegex.test( $.trim(s ));
861 format: function (s) {
862 return $.tablesorter.formatDigit(s);