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
) {
212 if ( node
.hasAttribute
&& node
.hasAttribute( "data-sort-value" ) ) {
213 return node
.getAttribute( "data-sort-value" );
215 return $( node
).text();
219 function appendToTable( table
, cache
) {
220 // if ( table.config.debug ) {
221 // var appendTime = new Date()
226 totalRows
= n
.length
,
227 checkCell
= (n
[0].length
- 1),
228 tableBody
= $( table
.tBodies
[0] ),
229 fragment
= document
.createDocumentFragment();
231 for ( var i
= 0; i
< totalRows
; i
++ ) {
232 var pos
= n
[i
][checkCell
];
234 var l
= r
[pos
].length
;
236 for ( var j
= 0; j
< l
; j
++ ) {
237 fragment
.appendChild( r
[pos
][j
] );
241 tableBody
[0].appendChild( fragment
);
242 // if ( table.config.debug ) {
243 // benchmark( "Rebuilt table:", appendTime );
247 function buildHeaders( table
) {
250 // if ( table.config.debug ) {
251 // var time = new Date();
253 //var header_index = computeTableHeaderCellIndexes( table );
254 var realCellIndex
= 0;
255 $tableHeaders
= $( "thead:eq(0) tr", table
);
256 if ( $tableHeaders
.length
> 1 ) {
257 $tableHeaders
.each(function() {
258 if (this.cells
.length
> maxSeen
) {
259 maxSeen
= this.cells
.length
;
263 $tableHeaders
= $( longest
);
265 $tableHeaders
= $tableHeaders
.find('th').each( function ( index
) {
266 //var normalIndex = allCells.index( this );
267 //var realCellIndex = 0;
268 this.column
= realCellIndex
;
270 var colspan
= this.colspan
;
271 colspan
= colspan
? parseInt( colspan
, 10 ) : 1;
272 realCellIndex
+= colspan
;
274 //this.column = header_index[this.parentNode.rowIndex + "-" + this.cellIndex];
278 if ( $( this ).is( '.unsortable' ) ) this.sortDisabled
= true;
280 if ( !this.sortDisabled
) {
281 var $th
= $( this ).addClass( table
.config
.cssHeader
);
282 //if ( table.config.onRenderHeader ) table.config.onRenderHeader.apply($th);
285 // add cell to headerList
286 table
.config
.headerList
[index
] = this;
289 // if ( table.config.debug ) {
290 // benchmark( "Built headers:", time );
291 // console.log( $tableHeaders );
294 return $tableHeaders
;
298 function isValueInArray( v
, a
) {
300 for ( var i
= 0; i
< l
; i
++ ) {
301 if ( a
[i
][0] == v
) {
308 function setHeadersCss( table
, $headers
, list
, css
) {
309 // remove all header information
310 $headers
.removeClass( css
[0] ).removeClass( css
[1] );
313 $headers
.each( function ( offset
) {
314 if ( !this.sortDisabled
) {
315 h
[this.column
] = $( this );
320 for ( var i
= 0; i
< l
; i
++ ) {
321 h
[list
[i
][0]].addClass( css
[list
[i
][1]] );
325 function checkSorting (array1
, array2
, sortList
) {
327 for ( var i
= 0, len
= sortList
.length
; i
< len
; i
++ ) {
328 col
= sortList
[i
][0];
329 fn
= ( sortList
[i
][1] ) ? sortTextDesc
: sortText
;
330 ret
= fn
.call( this, array1
[col
], array2
[col
] );
338 // Merge sort algorithm
339 // Based on http://en.literateprograms.org/Merge_sort_(JavaScript)
340 function mergeSortHelper(array
, begin
, beginRight
, end
, sortList
) {
341 for (; begin
< beginRight
; ++begin
) {
342 if (checkSorting( array
[begin
], array
[beginRight
], sortList
)) {
343 var v
= array
[begin
];
344 array
[begin
] = array
[beginRight
];
345 var begin2
= beginRight
;
346 while ( begin2
+ 1 < end
&& checkSorting( v
, array
[begin2
+ 1], sortList
) ) {
347 var tmp
= array
[begin2
];
348 array
[begin2
] = array
[begin2
+ 1];
349 array
[begin2
+ 1] = tmp
;
357 function mergeSort(array
, begin
, end
, sortList
) {
358 var size
= end
- begin
;
359 if (size
< 2) return;
361 var beginRight
= begin
+ Math
.floor(size
/ 2);
363 mergeSort(array
, begin
, beginRight
, sortList
);
364 mergeSort(array
, beginRight
, end
, sortList
);
365 mergeSortHelper(array
, begin
, beginRight
, end
, sortList
);
370 function multisort( table
, sortList
, cache
) {
371 //var sortTime = new Date();
373 var i
= sortList
.length
;
374 if ( i
== 1 && sortList
[0][0] === lastSort
) {
375 // Special case a simple reverse
376 cache
.normalized
.reverse();
378 mergeSort(cache
.normalized
, 0, cache
.normalized
.length
, sortList
);
380 lastSort
= ( sortList
.length
== 1 ) ? sortList
[0][0] : '';
382 //benchmark( "Sorting in dir " + order + " time:", sortTime );
387 function sortText( a
, b
) {
388 return ((a
< b
) ? false : ((a
> b
) ? true : 0));
391 function sortTextDesc( a
, b
) {
392 return ((b
< a
) ? false : ((b
> a
) ? true : 0));
395 function buildTransformTable() {
396 var digits
= '0123456789,.'.split('');
398 if ( typeof wgSeparatorTransformTable
== 'undefined' || ( wgSeparatorTransformTable
[0] == '' && wgDigitTransformTable
[2] == '' ) ) {
399 ts
.transformTable
= false;
401 ts
.transformTable
= {};
403 // Unpack the transform table
404 var ascii
= wgSeparatorTransformTable
[0].split( "\t" ).concat( wgDigitTransformTable
[0].split( "\t" ) );
405 var localised
= wgSeparatorTransformTable
[1].split( "\t" ).concat( wgDigitTransformTable
[1].split( "\t" ) );
407 // Construct regex for number identification
408 for ( var i
= 0; i
< ascii
.length
; i
++ ) {
409 ts
.transformTable
[localised
[i
]] = ascii
[i
];
410 digits
.push( $.escapeRE( localised
[i
] ) );
413 var digitClass
= '[' + digits
.join( '', digits
) + ']';
415 // We allow a trailing percent sign, which we just strip. This works fine
416 // if percents and regular numbers aren't being mixed.
417 ts
.numberRegex
= new RegExp("^(" + "[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?" + // Fortran-style scientific
418 "|" + "[-+\u2212]?" + digitClass
+ "+[\\s\\xa0]*%?" + // Generic localised
422 function buildDateTable() {
430 for ( i
= 1; i
< 13; i
++ ) {
431 ts
.monthNames
[0][i
] = wgMonthNames
[i
].toLowerCase();
432 ts
.monthNames
[1][i
] = wgMonthNamesShort
[i
].toLowerCase().replace( '.', '' );
433 r
+= $.escapeRE( ts
.monthNames
[0][i
] ) + '|';
434 r
+= $.escapeRE( ts
.monthNames
[1][i
] ) + '|';
437 //Remove trailing pipe
438 r
= r
.slice( 0, -1 );
441 //Any date formated with . , ' - or /
442 ts
.dateRegex
[0] = new RegExp(/^\s*\d{1,2}[\,\.\-\/'\s]*\d{1,2}[\,\.\-\/'\s]*\d{2,4}\s*?/i);
444 //Written Month name, dmy
445 ts
.dateRegex
[1] = new RegExp('^\\s*\\d{1,2}[\\,\\.\\-\\/\'\\s]*(' + r
+ ')' + '[\\,\\.\\-\\/\'\\s]*\\d{2,4}\\s*$', 'i');
447 //Written Month name, mdy
448 ts
.dateRegex
[2] = new RegExp('^\\s*(' + r
+ ')' + '[\\,\\.\\-\\/\'\\s]*\\d{1,2}[\\,\\.\\-\\/\'\\s]*\\d{2,4}\\s*$', 'i');
452 function explodeRowspans( $table
) {
453 // Split multi row cells into multiple cells with the same content
454 $table
.find( '[rowspan]' ).each(function() {
455 var rowSpan
= this.rowSpan
;
457 var cell
= $( this );
458 var next
= cell
.parent().nextAll();
459 for ( var i
= 0; i
< rowSpan
- 1; i
++ ) {
460 next
.eq(0).find( 'td' ).eq( this.cellIndex
).before( cell
.clone() );
465 function buildCollationTable() {
466 ts
.collationTable
= mw
.config
.get('tableSorterCollation');
467 if ( typeof ts
.collationTable
=== "object" ) {
468 ts
.collationRegex
= [];
470 //Build array of key names
471 for ( var key
in ts
.collationTable
) {
472 if ( ts
.collationTable
.hasOwnProperty(key
) ) { //to be safe
473 ts
.collationRegex
.push(key
);
476 ts
.collationRegex
= new RegExp( '[' + ts
.collationRegex
.join('') + ']', 'ig' );
480 function cacheRegexs() {
482 IPAddress
: [new RegExp(/^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/)],
483 currency
: [new RegExp(/^[£$€?.]/), new RegExp(/[£$€]/g)],
484 url
: [new RegExp(/^(https?|ftp|file):\/\/$/), new RegExp(/(https?|ftp|file):\/\//)],
485 isoDate
: [new RegExp(/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/)],
486 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)))$/)],
487 time
: [new RegExp(/^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/)]
489 } /* public methods */
490 this.construct = function ( settings
) {
491 return this.each( function () {
492 // if no thead or tbody quit.
493 if ( !this.tHead
|| !this.tBodies
) return;
495 var $this, $document
, $headers
, cache
, config
, shiftDown
= 0,
496 sortOrder
, firstTime
= true, that
= this;
497 // new blank config object
500 config
= $.extend( this.config
, $.tablesorter
.defaults
, settings
);
502 // store common expression for speed
504 // save the settings where they read
505 $.data( this, "tablesorter", config
);
507 $headers
= buildHeaders( this );
508 // Grab and process locale settings
509 buildTransformTable();
511 buildCollationTable();
513 //Precaching regexps can bring 10 fold
514 //performance improvements in some browsers
517 // get the css class names, could be done else where.
518 var sortCSS
= [config
.cssDesc
, config
.cssAsc
];
519 // apply event handling to headers
520 // this is to big, perhaps break it out?
524 //var clickTime= new Date();
527 explodeRowspans( $this );
528 // try to auto detect column type, and store in tables config
529 that
.config
.parsers
= buildParserCache( that
, $headers
);
530 // build the cache for the tbody cells
531 cache
= buildCache( that
);
533 var totalRows
= ( $this[0].tBodies
[0] && $this[0].tBodies
[0].rows
.length
) || 0;
534 if ( !this.sortDisabled
&& totalRows
> 0 ) {
535 // Only call sortStart if sorting is
537 //$this.trigger( "sortStart" );
539 // store exp, for speed
540 var $cell
= $( this );
541 // get current column index
543 // get current column sort order
544 this.order
= this.count
% 2;
546 // user only whants to sort on one
548 if ( !e
[config
.sortMultiSortKey
] ) {
549 // flush the sort list
550 config
.sortList
= [];
551 // add column to sort list
552 config
.sortList
.push( [i
, this.order
] );
553 // multi column sorting
555 // the user has clicked on an already sorted column.
556 if ( isValueInArray( i
, config
.sortList
) ) {
557 // revers the sorting direction
559 for ( var j
= 0; j
< config
.sortList
.length
; j
++ ) {
560 var s
= config
.sortList
[j
],
561 o
= config
.headerList
[s
[0]];
569 // add column to sort list array
570 config
.sortList
.push( [i
, this.order
] );
573 setTimeout( function () {
574 // set css for headers
575 setHeadersCss( $this[0], $headers
, config
.sortList
, sortCSS
);
578 $this[0], config
.sortList
, cache
) );
579 //benchmark( "Sorting " + totalRows + " rows:", clickTime );
581 // stop normal event by returning false
585 } ).mousedown( function () {
586 if ( config
.cancelSelection
) {
587 this.onselectstart = function () {
593 // apply easy methods that trigger binded events
594 //Can't think of any use for these in a mw context
595 // $this.bind( "update", function () {
597 // setTimeout( function () {
598 // // rebuild parsers.
599 // me.config.parsers = buildParserCache(
601 // // rebuild the cache map
602 // cache = buildCache(me);
604 // } ).bind( "updateCell", function ( e, cell ) {
605 // var config = this.config;
606 // // get position from the dom.
607 // var pos = [( cell.parentNode.rowIndex - 1 ), cell.cellIndex];
609 // cache.normalized[pos[0]][pos[1]] = config.parsers[pos[1]].format(
610 // getElementText( cell ), cell );
611 // } ).bind( "sorton", function ( e, list ) {
612 // $( this ).trigger( "sortStart" );
613 // config.sortList = list;
614 // // update and store the sortlist
615 // var sortList = config.sortList;
616 // // update header count index
617 // updateHeaderSortCount( this, sortList );
618 // // set css for headers
619 // setHeadersCss( this, $headers, sortList, sortCSS );
620 // // sort the table and append it to the dom
621 // appendToTable( this, multisort( this, sortList, cache ) );
622 // } ).bind( "appendCache", function () {
623 // appendToTable( this, cache );
627 this.addParser = function ( parser
) {
628 var l
= parsers
.length
,
630 for ( var i
= 0; i
< l
; i
++ ) {
631 if ( parsers
[i
].id
.toLowerCase() == parser
.id
.toLowerCase() ) {
636 parsers
.push( parser
);
639 this.formatDigit = function (s
) {
640 if ( ts
.transformTable
!= false ) {
643 for ( var p
= 0; p
< s
.length
; p
++ ) {
645 if ( c
in ts
.transformTable
) {
646 out
+= ts
.transformTable
[c
];
653 var i
= parseFloat( s
.replace(/[, ]/g, '').replace( "\u2212", '-' ) );
654 return ( isNaN(i
)) ? 0 : i
;
656 this.formatFloat = function (s
) {
657 var i
= parseFloat(s
);
658 return ( isNaN(i
)) ? 0 : i
;
660 this.formatInt = function (s
) {
661 var i
= parseInt( s
, 10 );
662 return ( isNaN(i
)) ? 0 : i
;
664 this.clearTableBody = function ( table
) {
665 if ( $.browser
.msie
) {
667 while ( this.firstChild
)
668 this.removeChild( this.firstChild
);
670 empty
.apply( table
.tBodies
[0] );
672 table
.tBodies
[0].innerHTML
= "";
678 // extend plugin scope
680 tablesorter
: $.tablesorter
.construct
684 var ts
= $.tablesorter
;
686 // add default parsers
692 format: function (s
) {
693 s
= $.trim( s
.toLowerCase() );
694 if ( ts
.collationRegex
) {
695 var tsc
= ts
.collationTable
;
696 s
= s
.replace( ts
.collationRegex
, function ( match
) {
697 var r
= tsc
[match
] ? tsc
[match
] : tsc
[match
.toUpperCase()];
698 return r
.toLowerCase();
709 return ts
.rgx
.IPAddress
[0].test(s
);
711 format: function (s
) {
712 var a
= s
.split("."),
715 for ( var i
= 0; i
< l
; i
++ ) {
717 if ( item
.length
== 2 ) {
723 return $.tablesorter
.formatFloat(r
);
730 is: function ( s
, table
) {
731 return $.tablesorter
.numberRegex
.test( $.trim(s
));
733 format: function (s
) {
734 return $.tablesorter
.formatDigit(s
);
742 return ts
.rgx
.currency
[0].test(s
);
744 format: function (s
) {
745 return $.tablesorter
.formatDigit( s
.replace( ts
.rgx
.currency
[1], "" ) );
753 return ts
.rgx
.url
[0].test(s
);
755 format: function (s
) {
756 return $.trim( s
.replace( ts
.rgx
.url
[1], '' ) );
764 return ts
.rgx
.isoDate
[0].test(s
);
766 format: function (s
) {
767 return $.tablesorter
.formatFloat((s
!= "") ? new Date(s
.replace(
768 new RegExp(/-/g), "/")).getTime() : "0");
776 return ts.rgx.usLongDate[0].test(s);
778 format: function (s) {
779 return $.tablesorter.formatFloat( new Date(s).getTime() );
787 return ( ts.dateRegex[0].test(s) || ts.dateRegex[1].test(s) || ts.dateRegex[2].test(s ));
789 format: function ( s, table ) {
790 s = $.trim( s.toLowerCase() );
792 for ( i = 1, j = 0; i < 13 && j < 2; i++ ) {
793 s = s.replace( ts.monthNames[j][i], i );
800 s = s.replace(/[\-\.\,' ]/g, "/");
802 //Replace double slashes
803 s = s.replace(/\/\//g, "/");
804 s = s.replace(/\/\//g, "/");
808 if ( s[0] && s[0].length == 1 ) s[0] = "0" + s[0];
809 if ( s[1] && s[1].length == 1 ) s[1] = "0" + s[1];
814 } else if ( ( y = parseInt( s[2], 10) ) < 100 ) {
815 //Guestimate years without centuries
822 //Resort array depending on preferences
823 if ( wgDefaultDateFormat == "mdy
" ) {
826 } else if ( wgDefaultDateFormat == "dmy
" ) {
831 return parseInt( s.join(''), 10 );
838 return ts.rgx.time[0].test(s);
840 format: function (s) {
841 return $.tablesorter.formatFloat( new Date( "2000/01/01 " + s ).getTime() );