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
, -1, i
);
113 // if ( table.config.debug ) {
114 // console.log( "column:" + i + " parser:" + p.id + "\n" );
122 function detectParserForColumn( table
, rows
, rowIndex
, cellIndex
) {
123 var l
= parsers
.length
,
127 while ( nodeValue
== '' && keepLooking
) {
129 if ( rows
[rowIndex
] ) {
130 node
= getNodeFromRowAndCellIndex( rows
, rowIndex
, cellIndex
);
131 nodeValue
= trimAndGetNodeText( node
);
132 // if ( table.config.debug ) {
133 // console.log( 'Checking if value was empty on row:' + rowIndex );
139 for ( var i
= 1; i
< l
; i
++ ) {
140 if ( parsers
[i
].is( nodeValue
, table
, node
) ) {
144 // 0 is always the generic parser ( text )
148 function getNodeFromRowAndCellIndex( rows
, rowIndex
, cellIndex
) {
149 return rows
[rowIndex
].cells
[cellIndex
];
152 function trimAndGetNodeText( node
) {
153 return $.trim( getElementText( node
) );
156 function getParserById( name
) {
157 var l
= parsers
.length
;
158 for ( var i
= 0; i
< l
; i
++ ) {
159 if ( parsers
[i
].id
.toLowerCase() == name
.toLowerCase() ) {
168 function buildCache( table
) {
169 // if ( table.config.debug ) {
170 // var cacheTime = new Date();
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 c
= $( 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 ( c
.hasClass( table
.config
.cssChildRow
) ) {
189 cache
.row
[cache
.row
.length
- 1] = cache
.row
[cache
.row
.length
- 1].add(c
);
190 // go to the next for loop
196 for ( var j
= 0; j
< totalCells
; ++j
) {
197 cols
.push( parsers
[j
].format( getElementText( c
[0].cells
[j
] ), table
, c
[0].cells
[j
] ) );
200 cols
.push( cache
.normalized
.length
); // add position for rowCache
201 cache
.normalized
.push( cols
);
205 // if ( table.config.debug ) {
206 // benchmark( "Building cache for " + totalRows + " rows:", cacheTime );
211 function getElementText( node
) {
213 var sortValue
= n
.data('sort-value');
214 if ( typeof sortValue
!= 'undefined' ) {
221 function appendToTable( table
, cache
) {
222 // if ( table.config.debug ) {
223 // var appendTime = new Date()
228 totalRows
= n
.length
,
229 checkCell
= (n
[0].length
- 1),
230 tableBody
= $( table
.tBodies
[0] ),
231 fragment
= document
.createDocumentFragment();
233 for ( var i
= 0; i
< totalRows
; i
++ ) {
234 var pos
= n
[i
][checkCell
];
236 var l
= r
[pos
].length
;
238 for ( var j
= 0; j
< l
; j
++ ) {
239 fragment
.appendChild( r
[pos
][j
] );
243 tableBody
[0].appendChild( fragment
);
244 // if ( table.config.debug ) {
245 // benchmark( "Rebuilt table:", appendTime );
249 function buildHeaders( table
) {
252 // if ( table.config.debug ) {
253 // var time = new Date();
255 //var header_index = computeTableHeaderCellIndexes( table );
256 var realCellIndex
= 0;
257 $tableHeaders
= $( "thead:eq(0) tr", table
);
258 if ( $tableHeaders
.length
> 1 ) {
259 $tableHeaders
.each(function() {
260 if (this.cells
.length
> maxSeen
) {
261 maxSeen
= this.cells
.length
;
265 $tableHeaders
= $( longest
);
267 $tableHeaders
= $tableHeaders
.find('th').each( function ( index
) {
268 //var normalIndex = allCells.index( this );
269 //var realCellIndex = 0;
270 this.column
= realCellIndex
;
272 var colspan
= this.colspan
;
273 colspan
= colspan
? parseInt( colspan
, 10 ) : 1;
274 realCellIndex
+= colspan
;
276 //this.column = header_index[this.parentNode.rowIndex + "-" + this.cellIndex];
280 if ( $( this ).is( '.unsortable' ) ) this.sortDisabled
= true;
282 if ( !this.sortDisabled
) {
283 var $th
= $( this ).addClass( table
.config
.cssHeader
);
284 //if ( table.config.onRenderHeader ) table.config.onRenderHeader.apply($th);
287 // add cell to headerList
288 table
.config
.headerList
[index
] = this;
291 // if ( table.config.debug ) {
292 // benchmark( "Built headers:", time );
293 // console.log( $tableHeaders );
296 return $tableHeaders
;
300 function isValueInArray( v
, a
) {
302 for ( var i
= 0; i
< l
; i
++ ) {
303 if ( a
[i
][0] == v
) {
310 function setHeadersCss( table
, $headers
, list
, css
) {
311 // remove all header information
312 $headers
.removeClass( css
[0] ).removeClass( css
[1] );
315 $headers
.each( function ( offset
) {
316 if ( !this.sortDisabled
) {
317 h
[this.column
] = $( this );
322 for ( var i
= 0; i
< l
; i
++ ) {
323 h
[list
[i
][0]].addClass( css
[list
[i
][1]] );
327 function checkSorting (array1
, array2
, sortList
) {
329 for ( var i
= 0, len
= sortList
.length
; i
< len
; i
++ ) {
330 col
= sortList
[i
][0];
331 fn
= ( sortList
[i
][1] ) ? sortTextDesc
: sortText
;
332 ret
= fn
.call( this, array1
[col
], array2
[col
] );
340 // Merge sort algorithm
341 // Based on http://en.literateprograms.org/Merge_sort_(JavaScript)
342 function mergeSortHelper(array
, begin
, beginRight
, end
, sortList
) {
343 for (; begin
< beginRight
; ++begin
) {
344 if (checkSorting( array
[begin
], array
[beginRight
], sortList
)) {
345 var v
= array
[begin
];
346 array
[begin
] = array
[beginRight
];
347 var begin2
= beginRight
;
348 while ( begin2
+ 1 < end
&& checkSorting( v
, array
[begin2
+ 1], sortList
) ) {
349 var tmp
= array
[begin2
];
350 array
[begin2
] = array
[begin2
+ 1];
351 array
[begin2
+ 1] = tmp
;
359 function mergeSort(array
, begin
, end
, sortList
) {
360 var size
= end
- begin
;
361 if (size
< 2) return;
363 var beginRight
= begin
+ Math
.floor(size
/ 2);
365 mergeSort(array
, begin
, beginRight
, sortList
);
366 mergeSort(array
, beginRight
, end
, sortList
);
367 mergeSortHelper(array
, begin
, beginRight
, end
, sortList
);
372 function multisort( table
, sortList
, cache
) {
373 //var sortTime = new Date();
375 var i
= sortList
.length
;
376 if ( i
== 1 && sortList
[0][0] === lastSort
) {
377 // Special case a simple reverse
378 cache
.normalized
.reverse();
380 mergeSort(cache
.normalized
, 0, cache
.normalized
.length
, sortList
);
382 lastSort
= ( sortList
.length
== 1 ) ? sortList
[0][0] : '';
384 //benchmark( "Sorting in dir " + order + " time:", sortTime );
389 function sortText( a
, b
) {
390 return ((a
< b
) ? false : ((a
> b
) ? true : 0));
393 function sortTextDesc( a
, b
) {
394 return ((b
< a
) ? false : ((b
> a
) ? true : 0));
397 function buildTransformTable() {
398 var digits
= '0123456789,.'.split('');
400 if ( typeof wgSeparatorTransformTable
== 'undefined' || ( wgSeparatorTransformTable
[0] == '' && wgDigitTransformTable
[2] == '' ) ) {
401 ts
.transformTable
= false;
403 ts
.transformTable
= {};
405 // Unpack the transform table
406 var ascii
= wgSeparatorTransformTable
[0].split( "\t" ).concat( wgDigitTransformTable
[0].split( "\t" ) );
407 var localised
= wgSeparatorTransformTable
[1].split( "\t" ).concat( wgDigitTransformTable
[1].split( "\t" ) );
409 // Construct regex for number identification
410 for ( var i
= 0; i
< ascii
.length
; i
++ ) {
411 ts
.transformTable
[localised
[i
]] = ascii
[i
];
412 digits
.push( $.escapeRE( localised
[i
] ) );
415 var digitClass
= '[' + digits
.join( '', digits
) + ']';
417 // We allow a trailing percent sign, which we just strip. This works fine
418 // if percents and regular numbers aren't being mixed.
419 ts
.numberRegex
= new RegExp("^(" + "[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?" + // Fortran-style scientific
420 "|" + "[-+\u2212]?" + digitClass
+ "+%?" + // Generic localised
424 function buildDateTable() {
432 for ( i
= 1; i
< 13; i
++ ) {
433 ts
.monthNames
[0][i
] = wgMonthNames
[i
].toLowerCase();
434 ts
.monthNames
[1][i
] = wgMonthNamesShort
[i
].toLowerCase().replace( '.', '' );
435 r
+= $.escapeRE( ts
.monthNames
[0][i
] ) + '|';
436 r
+= $.escapeRE( ts
.monthNames
[1][i
] ) + '|';
439 //Remove trailing pipe
440 r
= r
.slice( 0, -1 );
443 //Any date formated with . , ' - or /
444 ts
.dateRegex
[0] = new RegExp(/^\s*\d{1,2}[\,\.\-\/'\s]*\d{1,2}[\,\.\-\/'\s]*\d{2,4}\s*?/i);
446 //Written Month name, dmy
447 ts
.dateRegex
[1] = new RegExp('^\\s*\\d{1,2}[\\,\\.\\-\\/\'\\s]*(' + r
+ ')' + '[\\,\\.\\-\\/\'\\s]*\\d{2,4}\\s*$', 'i');
449 //Written Month name, mdy
450 ts
.dateRegex
[2] = new RegExp('^\\s*(' + r
+ ')' + '[\\,\\.\\-\\/\'\\s]*\\d{1,2}[\\,\\.\\-\\/\'\\s]*\\d{2,4}\\s*$', 'i');
454 function explodeRowspans( $table
) {
455 // Split multi row cells into multiple cells with the same content
456 $table
.find( '[rowspan]' ).each(function() {
457 var rowSpan
= this.rowSpan
;
459 var cell
= $( this );
460 var next
= cell
.parent().nextAll();
461 for ( var i
= 0; i
< rowSpan
- 1; i
++ ) {
462 next
.eq(0).find( 'td' ).eq( this.cellIndex
).before( cell
.clone() );
467 function buildCollationTable() {
468 ts
.collationTable
= mw
.config
.get('tableSorterCollation');
469 if ( typeof ts
.collationTable
=== "object" ) {
470 ts
.collationRegex
= [];
472 //Build array of key names
473 for ( var key
in ts
.collationTable
) {
474 if ( ts
.collationTable
.hasOwnProperty(key
) ) { //to be safe
475 ts
.collationRegex
.push(key
);
478 ts
.collationRegex
= new RegExp( '[' + ts
.collationRegex
.join('') + ']', 'ig' );
482 function cacheRegexs() {
484 IPAddress
: [new RegExp(/^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/)],
485 currency
: [new RegExp(/^[£$€?.]/), new RegExp(/[£$€]/g)],
486 url
: [new RegExp(/^(https?|ftp|file):\/\/$/), new RegExp(/(https?|ftp|file):\/\//)],
487 isoDate
: [new RegExp(/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/)],
488 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)))$/)],
489 time
: [new RegExp(/^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/)]
491 } /* public methods */
492 this.construct = function ( settings
) {
493 return this.each( function () {
494 // if no thead or tbody quit.
495 if ( !this.tHead
|| !this.tBodies
) return;
497 var $this, $document
, $headers
, cache
, config
, shiftDown
= 0,
498 sortOrder
, firstTime
= true, that
= this;
499 // new blank config object
502 config
= $.extend( this.config
, $.tablesorter
.defaults
, settings
);
504 // store common expression for speed
506 // save the settings where they read
507 $.data( this, "tablesorter", config
);
509 $headers
= buildHeaders( this );
510 // Grab and process locale settings
511 buildTransformTable();
513 buildCollationTable();
515 //Precaching regexps can bring 10 fold
516 //performance improvements in some browsers
519 // get the css class names, could be done else where.
520 var sortCSS
= [config
.cssDesc
, config
.cssAsc
];
521 // apply event handling to headers
522 // this is to big, perhaps break it out?
526 //var clickTime= new Date();
529 explodeRowspans( $this );
530 // try to auto detect column type, and store in tables config
531 that
.config
.parsers
= buildParserCache( that
, $headers
);
532 // build the cache for the tbody cells
533 cache
= buildCache( that
);
535 var totalRows
= ( $this[0].tBodies
[0] && $this[0].tBodies
[0].rows
.length
) || 0;
536 if ( !this.sortDisabled
&& totalRows
> 0 ) {
537 // Only call sortStart if sorting is
539 //$this.trigger( "sortStart" );
541 // store exp, for speed
542 var $cell
= $( this );
543 // get current column index
545 // get current column sort order
546 this.order
= this.count
% 2;
548 // user only whants to sort on one
550 if ( !e
[config
.sortMultiSortKey
] ) {
551 // flush the sort list
552 config
.sortList
= [];
553 // add column to sort list
554 config
.sortList
.push( [i
, this.order
] );
555 // multi column sorting
557 // the user has clicked on an already sorted column.
558 if ( isValueInArray( i
, config
.sortList
) ) {
559 // revers the sorting direction
561 for ( var j
= 0; j
< config
.sortList
.length
; j
++ ) {
562 var s
= config
.sortList
[j
],
563 o
= config
.headerList
[s
[0]];
571 // add column to sort list array
572 config
.sortList
.push( [i
, this.order
] );
575 setTimeout( function () {
576 // set css for headers
577 setHeadersCss( $this[0], $headers
, config
.sortList
, sortCSS
);
580 $this[0], config
.sortList
, cache
) );
581 //benchmark( "Sorting " + totalRows + " rows:", clickTime );
583 // stop normal event by returning false
587 } ).mousedown( function () {
588 if ( config
.cancelSelection
) {
589 this.onselectstart = function () {
595 // apply easy methods that trigger binded events
596 //Can't think of any use for these in a mw context
597 // $this.bind( "update", function () {
599 // setTimeout( function () {
600 // // rebuild parsers.
601 // me.config.parsers = buildParserCache(
603 // // rebuild the cache map
604 // cache = buildCache(me);
606 // } ).bind( "updateCell", function ( e, cell ) {
607 // var config = this.config;
608 // // get position from the dom.
609 // var pos = [( cell.parentNode.rowIndex - 1 ), cell.cellIndex];
611 // cache.normalized[pos[0]][pos[1]] = config.parsers[pos[1]].format(
612 // getElementText( cell ), cell );
613 // } ).bind( "sorton", function ( e, list ) {
614 // $( this ).trigger( "sortStart" );
615 // config.sortList = list;
616 // // update and store the sortlist
617 // var sortList = config.sortList;
618 // // update header count index
619 // updateHeaderSortCount( this, sortList );
620 // // set css for headers
621 // setHeadersCss( this, $headers, sortList, sortCSS );
622 // // sort the table and append it to the dom
623 // appendToTable( this, multisort( this, sortList, cache ) );
624 // } ).bind( "appendCache", function () {
625 // appendToTable( this, cache );
629 this.addParser = function ( parser
) {
630 var l
= parsers
.length
,
632 for ( var i
= 0; i
< l
; i
++ ) {
633 if ( parsers
[i
].id
.toLowerCase() == parser
.id
.toLowerCase() ) {
638 parsers
.push( parser
);
641 this.formatDigit = function (s
) {
642 if ( ts
.transformTable
!= false ) {
645 for ( var p
= 0; p
< s
.length
; p
++ ) {
647 if ( c
in ts
.transformTable
) {
648 out
+= ts
.transformTable
[c
];
655 var i
= parseFloat( s
.replace(/[, ]/g, '').replace( "\u2212", '-' ) );
656 return ( isNaN(i
)) ? 0 : i
;
658 this.formatFloat = function (s
) {
659 var i
= parseFloat(s
);
660 return ( isNaN(i
)) ? 0 : i
;
662 this.formatInt = function (s
) {
663 var i
= parseInt( s
, 10 );
664 return ( isNaN(i
)) ? 0 : i
;
666 this.clearTableBody = function ( table
) {
667 if ( $.browser
.msie
) {
669 while ( this.firstChild
)
670 this.removeChild( this.firstChild
);
672 empty
.apply( table
.tBodies
[0] );
674 table
.tBodies
[0].innerHTML
= "";
680 // extend plugin scope
682 tablesorter
: $.tablesorter
.construct
686 var ts
= $.tablesorter
;
688 // add default parsers
694 format: function (s
) {
695 s
= $.trim( s
.toLowerCase() );
696 if ( ts
.collationRegex
) {
697 var tsc
= ts
.collationTable
;
698 s
= s
.replace( ts
.collationRegex
, function ( match
) {
699 var r
= tsc
[match
] ? tsc
[match
] : tsc
[match
.toUpperCase()];
700 return r
.toLowerCase();
711 return ts
.rgx
.IPAddress
[0].test(s
);
713 format: function (s
) {
714 var a
= s
.split("."),
717 for ( var i
= 0; i
< l
; i
++ ) {
719 if ( item
.length
== 2 ) {
725 return $.tablesorter
.formatFloat(r
);
732 is: function ( s
, table
) {
733 return $.tablesorter
.numberRegex
.test( $.trim(s
));
735 format: function (s
) {
736 return $.tablesorter
.formatDigit(s
);
744 return ts
.rgx
.currency
[0].test(s
);
746 format: function (s
) {
747 return $.tablesorter
.formatDigit( s
.replace( ts
.rgx
.currency
[1], "" ) );
755 return ts
.rgx
.url
[0].test(s
);
757 format: function (s
) {
758 return $.trim( s
.replace( ts
.rgx
.url
[1], '' ) );
766 return ts
.rgx
.isoDate
[0].test(s
);
768 format: function (s
) {
769 return $.tablesorter
.formatFloat((s
!= "") ? new Date(s
.replace(
770 new RegExp(/-/g), "/")).getTime() : "0");
778 return ts.rgx.usLongDate[0].test(s);
780 format: function (s) {
781 return $.tablesorter.formatFloat( new Date(s).getTime() );
789 return ( ts.dateRegex[0].test(s) || ts.dateRegex[1].test(s) || ts.dateRegex[2].test(s ));
791 format: function ( s, table ) {
792 s = $.trim( s.toLowerCase() );
794 for ( i = 1, j = 0; i < 13 && j < 2; i++ ) {
795 s = s.replace( ts.monthNames[j][i], i );
802 s = s.replace(/[\-\.\,' ]/g, "/");
804 //Replace double slashes
805 s = s.replace(/\/\//g, "/");
806 s = s.replace(/\/\//g, "/");
810 if ( s[0] && s[0].length == 1 ) s[0] = "0" + s[0];
811 if ( s[1] && s[1].length == 1 ) s[1] = "0" + s[1];
816 } else if ( ( y = parseInt( s[2], 10) ) < 100 ) {
817 //Guestimate years without centuries
824 //Resort array depending on preferences
825 if ( wgDefaultDateFormat == "mdy
" ) {
828 } else if ( wgDefaultDateFormat == "dmy
" ) {
833 return parseInt( s.join(''), 10 );
840 return ts.rgx.time[0].test(s);
842 format: function (s) {
843 return $.tablesorter.formatFloat( new Date( "2000/01/01 " + s ).getTime() );