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, wgDefaultDateFormat, wgContentLanguage)
12 * and mw.language.months.
14 * Uses 'tableSorterCollation' in mw.config (if available)
18 * @description Create a sortable table with multi-column sorting capabilities
20 * @example $( 'table' ).tablesorter();
21 * @desc Create a simple tablesorter interface.
23 * @example $( 'table' ).tablesorter( { sortList: [ { 0: 'desc' }, { 1: 'asc' } ] } );
24 * @desc Create a tablesorter interface initially sorting on the first and second column.
26 * @option String cssHeader ( optional ) A string of the class name to be appended
27 * to sortable tr elements in the thead of the table. Default value:
30 * @option String cssAsc ( optional ) A string of the class name to be appended to
31 * sortable tr elements in the thead on a ascending sort. Default value:
34 * @option String cssDesc ( optional ) A string of the class name to be appended
35 * to sortable tr elements in the thead on a descending sort. Default
36 * value: "headerSortDown"
38 * @option String sortMultisortKey ( optional ) A string of the multi-column sort
39 * key. Default value: "shiftKey"
41 * @option Boolean cancelSelection ( optional ) Boolean flag indicating if
42 * tablesorter should cancel selection of the table headers text.
45 * @option Array sortList ( optional ) An array containing objects specifying sorting.
46 * By passing more than one object, multi-sorting will be applied. Object structure:
47 * { <Integer column index>: <String 'asc' or 'desc'> }
50 * @event sortEnd.tablesorter: Triggered as soon as any sorting has been applied.
56 * @cat Plugins/Tablesorter
58 * @author Christian Bach/christian.bach@polyester.se
61 ( function ( $, mw
) {
67 /* Parser utility functions */
69 function getParserById( name
) {
72 for ( i
= 0; i
< len
; i
++ ) {
73 if ( parsers
[i
].id
.toLowerCase() === name
.toLowerCase() ) {
80 function getElementSortKey( node
) {
81 var $node
= $( node
),
82 // Use data-sort-value attribute.
83 // Use data() instead of attr() so that live value changes
84 // are processed as well (bug 38152).
85 data
= $node
.data( 'sortValue' );
87 if ( data
!== null && data
!== undefined ) {
88 // Cast any numbers or other stuff to a string, methods
89 // like charAt, toLowerCase and split are expected.
90 return String( data
);
94 } else if ( node
.tagName
.toLowerCase() === 'img' ) {
95 return $node
.attr( 'alt' ) || ''; // handle undefined alt
97 return $.map( $.makeArray( node
.childNodes
), function ( elem
) {
98 // 1 is for document.ELEMENT_NODE (the constant is undefined on old browsers)
99 if ( elem
.nodeType
=== 1 ) {
100 return getElementSortKey( elem
);
102 return $.text( elem
);
109 function detectParserForColumn( table
, rows
, cellIndex
) {
110 var l
= parsers
.length
,
112 // Start with 1 because 0 is the fallback parser
116 needed
= ( rows
.length
> 4 ) ? 5 : rows
.length
;
119 if ( rows
[rowIndex
] && rows
[rowIndex
].cells
[cellIndex
] ) {
120 nodeValue
= $.trim( getElementSortKey( rows
[rowIndex
].cells
[cellIndex
] ) );
125 if ( nodeValue
!== '' ) {
126 if ( parsers
[i
].is( nodeValue
, table
) ) {
129 if ( concurrent
>= needed
) {
130 // Confirmed the parser for multiple cells, let's return it
134 // Check next parser, reset rows
142 if ( rowIndex
> rows
.length
) {
149 // 0 is always the generic parser (text)
153 function buildParserCache( table
, $headers
) {
154 var sortType
, cells
, len
, i
, parser
,
155 rows
= table
.tBodies
[0].rows
,
160 cells
= rows
[0].cells
;
163 for ( i
= 0; i
< len
; i
++ ) {
165 sortType
= $headers
.eq( i
).data( 'sortType' );
166 if ( sortType
!== undefined ) {
167 parser
= getParserById( sortType
);
170 if ( parser
=== false ) {
171 parser
= detectParserForColumn( table
, rows
, i
);
174 parsers
.push( parser
);
180 /* Other utility functions */
182 function buildCache( table
) {
183 var i
, j
, $row
, cols
,
184 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 config
= $( table
).data( 'tablesorter' ).config
,
187 parsers
= config
.parsers
,
193 for ( i
= 0; i
< totalRows
; ++i
) {
195 // Add the table data to main data array
196 $row
= $( table
.tBodies
[0].rows
[i
] );
199 // if this is a child row, add it to the last row's children and
200 // continue to the next row
201 if ( $row
.hasClass( config
.cssChildRow
) ) {
202 cache
.row
[cache
.row
.length
- 1] = cache
.row
[cache
.row
.length
- 1].add( $row
);
203 // go to the next for loop
207 cache
.row
.push( $row
);
209 for ( j
= 0; j
< totalCells
; ++j
) {
210 cols
.push( parsers
[j
].format( getElementSortKey( $row
[0].cells
[j
] ), table
, $row
[0].cells
[j
] ) );
213 cols
.push( cache
.normalized
.length
); // add position for rowCache
214 cache
.normalized
.push( cols
);
221 function appendToTable( table
, cache
) {
224 normalized
= cache
.normalized
,
225 totalRows
= normalized
.length
,
226 checkCell
= ( normalized
[0].length
- 1 ),
227 fragment
= document
.createDocumentFragment();
229 for ( i
= 0; i
< totalRows
; i
++ ) {
230 pos
= normalized
[i
][checkCell
];
234 for ( j
= 0; j
< l
; j
++ ) {
235 fragment
.appendChild( row
[pos
][j
] );
239 table
.tBodies
[0].appendChild( fragment
);
241 $( table
).trigger( 'sortEnd.tablesorter' );
245 * Find all header rows in a thead-less table and put them in a <thead> tag.
246 * This only treats a row as a header row if it contains only <th>s (no <td>s)
247 * and if it is preceded entirely by header rows. The algorithm stops when
248 * it encounters the first non-header row.
250 * After this, it will look at all rows at the bottom for footer rows
251 * And place these in a tfoot using similar rules.
252 * @param $table jQuery object for a <table>
254 function emulateTHeadAndFoot( $table
) {
255 var $thead
, $tfoot
, i
, len
,
256 $rows
= $table
.find( '> tbody > tr' );
257 if ( !$table
.get( 0 ).tHead
) {
258 $thead
= $( '<thead>' );
259 $rows
.each( function () {
260 if ( $( this ).children( 'td' ).length
) {
261 // This row contains a <td>, so it's not a header row
265 $thead
.append( this );
267 $table
.find( ' > tbody:first' ).before( $thead
);
269 if ( !$table
.get( 0 ).tFoot
) {
270 $tfoot
= $( '<tfoot>' );
272 for ( i
= len
- 1; i
>= 0; i
-- ) {
273 if ( $( $rows
[i
] ).children( 'td' ).length
) {
276 $tfoot
.prepend( $( $rows
[i
] ) );
278 $table
.append( $tfoot
);
282 function buildHeaders( table
, msg
) {
283 var config
= $( table
).data( 'tablesorter' ).config
,
294 $tableHeaders
= $( [] ),
295 $tableRows
= $( 'thead:eq(0) > tr', table
);
296 if ( $tableRows
.length
<= 1 ) {
297 $tableHeaders
= $tableRows
.children( 'th' );
301 // Loop through all the dom cells of the thead
302 $tableRows
.each( function ( rowIndex
, row
) {
303 $.each( row
.cells
, function ( columnIndex
, cell
) {
307 rowspan
= Number( cell
.rowSpan
);
308 colspan
= Number( cell
.colSpan
);
310 // Skip the spots in the exploded matrix that are already filled
311 while ( exploded
[rowIndex
] && exploded
[rowIndex
][columnIndex
] !== undefined ) {
315 // Find the actual dimensions of the thead, by placing each cell
316 // in the exploded matrix rowspan times colspan times, with the proper offsets
317 for ( matrixColumnIndex
= columnIndex
; matrixColumnIndex
< columnIndex
+ colspan
; ++matrixColumnIndex
) {
318 for ( matrixRowIndex
= rowIndex
; matrixRowIndex
< rowIndex
+ rowspan
; ++matrixRowIndex
) {
319 if ( !exploded
[matrixRowIndex
] ) {
320 exploded
[matrixRowIndex
] = [];
322 exploded
[matrixRowIndex
][matrixColumnIndex
] = cell
;
327 // We want to find the row that has the most columns (ignoring colspan)
328 $.each( exploded
, function ( index
, cellArray
) {
329 headerCount
= $( uniqueElements( cellArray
) ).filter( 'th' ).length
;
330 if ( headerCount
>= maxSeen
) {
331 maxSeen
= headerCount
;
335 // We cannot use $.unique() here because it sorts into dom order, which is undesirable
336 $tableHeaders
= $( uniqueElements( exploded
[longestTR
] ) ).filter( 'th' );
339 // as each header can span over multiple columns (using colspan=N),
340 // we have to bidirectionally map headers to their columns and columns to their headers
341 $tableHeaders
.each( function ( headerIndex
) {
345 for ( i
= 0; i
< this.colSpan
; i
++ ) {
346 config
.columnToHeader
[ colspanOffset
+ i
] = headerIndex
;
347 columns
.push( colspanOffset
+ i
);
350 config
.headerToColumns
[ headerIndex
] = columns
;
351 colspanOffset
+= this.colSpan
;
354 headerIndex
: headerIndex
,
359 if ( $cell
.hasClass( config
.unsortableClass
) ) {
360 $cell
.data( 'sortDisabled', true );
363 if ( !$cell
.data( 'sortDisabled' ) ) {
365 .addClass( config
.cssHeader
)
366 .prop( 'tabIndex', 0 )
368 role
: 'columnheader button',
373 // add cell to headerList
374 config
.headerList
[headerIndex
] = this;
377 return $tableHeaders
;
382 * Sets the sort count of the columns that are not affected by the sorting to have them sorted
383 * in default (ascending) order when their header cell is clicked the next time.
385 * @param {jQuery} $headers
386 * @param {Number[][]} sortList
387 * @param {Number[][]} headerToColumns
389 function setHeadersOrder( $headers
, sortList
, headerToColumns
) {
390 // Loop through all headers to retrieve the indices of the columns the header spans across:
391 $.each( headerToColumns
, function ( headerIndex
, columns
) {
393 $.each( columns
, function ( i
, columnIndex
) {
394 var header
= $headers
[headerIndex
],
395 $header
= $( header
);
397 if ( !isValueInArray( columnIndex
, sortList
) ) {
398 // Column shall not be sorted: Reset header count and order.
404 // Column shall be sorted: Apply designated count and order.
405 $.each( sortList
, function ( j
, sortColumn
) {
406 if ( sortColumn
[0] === i
) {
408 order
: sortColumn
[1],
409 count
: sortColumn
[1] + 1
420 function isValueInArray( v
, a
) {
423 for ( i
= 0; i
< len
; i
++ ) {
424 if ( a
[i
][0] === v
) {
431 function uniqueElements( array
) {
433 $.each( array
, function ( index
, elem
) {
434 if ( elem
!== undefined && $.inArray( elem
, uniques
) === -1 ) {
435 uniques
.push( elem
);
441 function setHeadersCss( table
, $headers
, list
, css
, msg
, columnToHeader
) {
442 // Remove all header information and reset titles to default message
443 $headers
.removeClass( css
[0] ).removeClass( css
[1] ).attr( 'title', msg
[1] );
445 for ( var i
= 0; i
< list
.length
; i
++ ) {
446 $headers
.eq( columnToHeader
[ list
[i
][0] ] )
447 .addClass( css
[ list
[i
][1] ] )
448 .attr( 'title', msg
[ list
[i
][1] ] );
452 function sortText( a
, b
) {
453 return ( ( a
< b
) ? -1 : ( ( a
> b
) ? 1 : 0 ) );
456 function sortTextDesc( a
, b
) {
457 return ( ( b
< a
) ? -1 : ( ( b
> a
) ? 1 : 0 ) );
460 function multisort( table
, sortList
, cache
) {
463 len
= sortList
.length
;
464 for ( i
= 0; i
< len
; i
++ ) {
465 sortFn
[i
] = ( sortList
[i
][1] ) ? sortTextDesc
: sortText
;
467 cache
.normalized
.sort( function ( array1
, array2
) {
469 for ( i
= 0; i
< len
; i
++ ) {
470 col
= sortList
[i
][0];
471 ret
= sortFn
[i
].call( this, array1
[col
], array2
[col
] );
476 // Fall back to index number column to ensure stable sort
477 return sortText
.call( this, array1
[array1
.length
- 1], array2
[array2
.length
- 1] );
482 function buildTransformTable() {
483 var ascii
, localised
, i
, digitClass
,
484 digits
= '0123456789,.'.split( '' ),
485 separatorTransformTable
= mw
.config
.get( 'wgSeparatorTransformTable' ),
486 digitTransformTable
= mw
.config
.get( 'wgDigitTransformTable' );
488 if ( separatorTransformTable
=== null || ( separatorTransformTable
[0] === '' && digitTransformTable
[2] === '' ) ) {
489 ts
.transformTable
= false;
491 ts
.transformTable
= {};
493 // Unpack the transform table
494 ascii
= separatorTransformTable
[0].split( '\t' ).concat( digitTransformTable
[0].split( '\t' ) );
495 localised
= separatorTransformTable
[1].split( '\t' ).concat( digitTransformTable
[1].split( '\t' ) );
497 // Construct regex for number identification
498 for ( i
= 0; i
< ascii
.length
; i
++ ) {
499 ts
.transformTable
[localised
[i
]] = ascii
[i
];
500 digits
.push( $.escapeRE( localised
[i
] ) );
503 digitClass
= '[' + digits
.join( '', digits
) + ']';
505 // We allow a trailing percent sign, which we just strip. This works fine
506 // if percents and regular numbers aren't being mixed.
507 ts
.numberRegex
= new RegExp( '^(' + '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
508 '|' + '[-+\u2212]?' + digitClass
+ '+[\\s\\xa0]*%?' + // Generic localised
512 function buildDateTable() {
518 for ( i
= 0; i
< 12; i
++ ) {
519 name
= mw
.language
.months
.names
[i
].toLowerCase();
520 ts
.monthNames
[name
] = i
+ 1;
521 regex
.push( $.escapeRE( name
) );
522 name
= mw
.language
.months
.genitive
[i
].toLowerCase();
523 ts
.monthNames
[name
] = i
+ 1;
524 regex
.push( $.escapeRE( name
) );
525 name
= mw
.language
.months
.abbrev
[i
].toLowerCase().replace( '.', '' );
526 ts
.monthNames
[name
] = i
+ 1;
527 regex
.push( $.escapeRE( name
) );
530 // Build piped string
531 regex
= regex
.join( '|' );
534 // Any date formated with . , ' - or /
535 ts
.dateRegex
[0] = new RegExp( /^\s*(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{2,4})\s*?/i );
537 // Written Month name, dmy
538 ts
.dateRegex
[1] = new RegExp( '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
540 // Written Month name, mdy
541 ts
.dateRegex
[2] = new RegExp( '^\\s*(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
546 * Replace all rowspanned cells in the body with clones in each row, so sorting
547 * need not worry about them.
549 * @param $table jQuery object for a <table>
551 function explodeRowspans( $table
) {
552 var spanningRealCellIndex
, rowSpan
, colSpan
,
553 cell
, cellData
, i
, $tds
, $clone
, $nextRows
,
554 rowspanCells
= $table
.find( '> tbody > tr > [rowspan]' ).get();
557 if ( !rowspanCells
.length
) {
561 // First, we need to make a property like cellIndex but taking into
562 // account colspans. We also cache the rowIndex to avoid having to take
563 // cell.parentNode.rowIndex in the sorting function below.
564 $table
.find( '> tbody > tr' ).each( function () {
567 l
= this.cells
.length
;
568 for ( i
= 0; i
< l
; i
++ ) {
569 $( this.cells
[i
] ).data( 'tablesorter', {
571 realRowIndex
: this.rowIndex
573 col
+= this.cells
[i
].colSpan
;
577 // Split multi row cells into multiple cells with the same content.
578 // Sort by column then row index to avoid problems with odd table structures.
579 // Re-sort whenever a rowspanned cell's realCellIndex is changed, because it
580 // might change the sort order.
581 function resortCells() {
585 rowspanCells
= rowspanCells
.sort( function ( a
, b
) {
586 cellAData
= $.data( a
, 'tablesorter' );
587 cellBData
= $.data( b
, 'tablesorter' );
588 ret
= cellAData
.realCellIndex
- cellBData
.realCellIndex
;
590 ret
= cellAData
.realRowIndex
- cellBData
.realRowIndex
;
594 $.each( rowspanCells
, function () {
595 $.data( this, 'tablesorter' ).needResort
= false;
600 function filterfunc() {
601 return $.data( this, 'tablesorter' ).realCellIndex
>= spanningRealCellIndex
;
604 function fixTdCellIndex() {
605 $.data( this, 'tablesorter' ).realCellIndex
+= colSpan
;
606 if ( this.rowSpan
> 1 ) {
607 $.data( this, 'tablesorter' ).needResort
= true;
611 while ( rowspanCells
.length
) {
612 if ( $.data( rowspanCells
[0], 'tablesorter' ).needResort
) {
616 cell
= rowspanCells
.shift();
617 cellData
= $.data( cell
, 'tablesorter' );
618 rowSpan
= cell
.rowSpan
;
619 colSpan
= cell
.colSpan
;
620 spanningRealCellIndex
= cellData
.realCellIndex
;
622 $nextRows
= $( cell
).parent().nextAll();
623 for ( i
= 0; i
< rowSpan
- 1; i
++ ) {
624 $tds
= $( $nextRows
[i
].cells
).filter( filterfunc
);
625 $clone
= $( cell
).clone();
626 $clone
.data( 'tablesorter', {
627 realCellIndex
: spanningRealCellIndex
,
628 realRowIndex
: cellData
.realRowIndex
+ i
,
632 $tds
.each( fixTdCellIndex
);
633 $tds
.first().before( $clone
);
635 $nextRows
.eq( i
).append( $clone
);
641 function buildCollationTable() {
642 ts
.collationTable
= mw
.config
.get( 'tableSorterCollation' );
643 ts
.collationRegex
= null;
644 if ( ts
.collationTable
) {
648 // Build array of key names
649 for ( key
in ts
.collationTable
) {
650 // Check hasOwn to be safe
651 if ( ts
.collationTable
.hasOwnProperty( key
) ) {
656 ts
.collationRegex
= new RegExp( '[' + keys
.join( '' ) + ']', 'ig' );
661 function cacheRegexs() {
667 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/ )
670 new RegExp( /(^[£$€¥]|[£$€¥]$)/ ),
671 new RegExp( /[£$€¥]/g )
674 new RegExp( /^(https?|ftp|file):\/\/$/ ),
675 new RegExp( /(https?|ftp|file):\/\// )
678 new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/ )
681 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)))$/ )
684 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/ )
690 * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
691 * structure [ [ Integer , Integer ], ... ]
693 * @param sortObjects {Array} List of sort objects.
694 * @return {Array} List of internal sort definitions.
697 function convertSortList( sortObjects
) {
699 $.each( sortObjects
, function ( i
, sortObject
) {
700 $.each( sortObject
, function ( columnIndex
, order
) {
701 var orderIndex
= ( order
=== 'desc' ) ? 1 : 0;
702 sortList
.push( [parseInt( columnIndex
, 10 ), orderIndex
] );
713 cssHeader
: 'headerSort',
714 cssAsc
: 'headerSortUp',
715 cssDesc
: 'headerSortDown',
716 cssChildRow
: 'expand-child',
717 sortMultiSortKey
: 'shiftKey',
718 unsortableClass
: 'unsortable',
720 cancelSelection
: true,
731 * @param $tables {jQuery}
732 * @param settings {Object} (optional)
734 construct: function ( $tables
, settings
) {
735 return $tables
.each( function ( i
, table
) {
736 // Declare and cache.
737 var $headers
, cache
, config
, sortCSS
, sortMsg
,
742 if ( !table
.tBodies
) {
745 if ( !table
.tHead
) {
746 // No thead found. Look for rows with <th>s and
747 // move them into a <thead> tag or a <tfoot> tag
748 emulateTHeadAndFoot( $table
);
750 // Still no thead? Then quit
751 if ( !table
.tHead
) {
755 $table
.addClass( 'jquery-tablesorter' );
758 config
= $.extend( {}, $.tablesorter
.defaultOptions
, settings
);
760 // Save the settings where they read
761 $.data( table
, 'tablesorter', { config
: config
} );
763 // Get the CSS class names, could be done elsewhere
764 sortCSS
= [ config
.cssDesc
, config
.cssAsc
];
765 sortMsg
= [ mw
.msg( 'sort-descending' ), mw
.msg( 'sort-ascending' ) ];
768 $headers
= buildHeaders( table
, sortMsg
);
770 // Grab and process locale settings.
771 buildTransformTable();
774 // Precaching regexps can bring 10 fold
775 // performance improvements in some browsers.
778 function setupForFirstSort() {
781 // Defer buildCollationTable to first sort. As user and site scripts
782 // may customize tableSorterCollation but load after $.ready(), other
783 // scripts may call .tablesorter() before they have done the
784 // tableSorterCollation customizations.
785 buildCollationTable();
787 // Legacy fix of .sortbottoms
788 // Wrap them inside a tfoot (because that's what they actually want to be)
789 // and put the <tfoot> at the end of the <table>
791 $sortbottoms
= $table
.find( '> tbody > tr.sortbottom' );
792 if ( $sortbottoms
.length
) {
793 $tfoot
= $table
.children( 'tfoot' );
794 if ( $tfoot
.length
) {
795 $tfoot
.eq( 0 ).prepend( $sortbottoms
);
797 $table
.append( $( '<tfoot>' ).append( $sortbottoms
) );
801 explodeRowspans( $table
);
803 // Try to auto detect column type, and store in tables config
804 config
.parsers
= buildParserCache( table
, $headers
);
807 // Apply event handling to headers
808 // this is too big, perhaps break it out?
809 $headers
.not( '.' + config
.unsortableClass
).on( 'keypress click', function ( e
) {
810 var cell
, $cell
, columns
, newSortList
, i
,
814 if ( e
.type
=== 'click' && e
.target
.nodeName
.toLowerCase() === 'a' ) {
815 // The user clicked on a link inside a table header.
816 // Do nothing and let the default link click action continue.
820 if ( e
.type
=== 'keypress' && e
.which
!== 13 ) {
821 // Only handle keypresses on the "Enter" key.
829 // Build the cache for the tbody cells
830 // to share between calculations for this sort action.
831 // Re-calculated each time a sort action is performed due to possiblity
832 // that sort values change. Shouldn't be too expensive, but if it becomes
833 // too slow an event based system should be implemented somehow where
834 // cells get event .change() and bubbles up to the <table> here
835 cache
= buildCache( table
);
837 totalRows
= ( $table
[0].tBodies
[0] && $table
[0].tBodies
[0].rows
.length
) || 0;
838 if ( !table
.sortDisabled
&& totalRows
> 0 ) {
842 // Get current column sort order
844 order
: $cell
.data( 'count' ) % 2,
845 count
: $cell
.data( 'count' ) + 1
849 // Get current column index
850 columns
= config
.headerToColumns
[ $cell
.data( 'headerIndex' ) ];
851 newSortList
= $.map( columns
, function ( c
) {
852 // jQuery "helpfully" flattens the arrays...
853 return [[c
, $cell
.data( 'order' )]];
855 // Index of first column belonging to this header
858 if ( !e
[config
.sortMultiSortKey
] ) {
859 // User only wants to sort on one column set
860 // Flush the sort list and add new columns
861 config
.sortList
= newSortList
;
863 // Multi column sorting
864 // It is not possible for one column to belong to multiple headers,
865 // so this is okay - we don't need to check for every value in the columns array
866 if ( isValueInArray( i
, config
.sortList
) ) {
867 // The user has clicked on an already sorted column.
868 // Reverse the sorting direction for all tables.
869 for ( j
= 0; j
< config
.sortList
.length
; j
++ ) {
870 s
= config
.sortList
[j
];
871 o
= config
.headerList
[s
[0]];
872 if ( isValueInArray( s
[0], newSortList
) ) {
873 $( o
).data( 'count', s
[1] + 1 );
874 s
[1] = $( o
).data( 'count' ) % 2;
878 // Add columns to sort list array
879 config
.sortList
= config
.sortList
.concat( newSortList
);
883 // Reset order/counts of cells not affected by sorting
884 setHeadersOrder( $headers
, config
.sortList
, config
.headerToColumns
);
886 // Set CSS for headers
887 setHeadersCss( $table
[0], $headers
, config
.sortList
, sortCSS
, sortMsg
, config
.columnToHeader
);
889 $table
[0], multisort( $table
[0], config
.sortList
, cache
)
892 // Stop normal event by returning false
897 } ).mousedown( function () {
898 if ( config
.cancelSelection
) {
899 this.onselectstart = function () {
907 * Sorts the table. If no sorting is specified by passing a list of sort
908 * objects, the table is sorted according to the initial sorting order.
909 * Passing an empty array will reset sorting (basically just reset the headers
910 * making the table appear unsorted).
912 * @param sortList {Array} (optional) List of sort objects.
914 $table
.data( 'tablesorter' ).sort = function ( sortList
) {
920 if ( sortList
=== undefined ) {
921 sortList
= config
.sortList
;
922 } else if ( sortList
.length
> 0 ) {
923 sortList
= convertSortList( sortList
);
926 // Set each column's sort count to be able to determine the correct sort
927 // order when clicking on a header cell the next time
928 setHeadersOrder( $headers
, sortList
, config
.headerToColumns
);
930 // re-build the cache for the tbody cells
931 cache
= buildCache( table
);
933 // set css for headers
934 setHeadersCss( table
, $headers
, sortList
, sortCSS
, sortMsg
, config
.columnToHeader
);
936 // sort the table and append it to the dom
937 appendToTable( table
, multisort( table
, sortList
, cache
) );
941 if ( config
.sortList
.length
> 0 ) {
943 config
.sortList
= convertSortList( config
.sortList
);
944 $table
.data( 'tablesorter' ).sort();
950 addParser: function ( parser
) {
952 len
= parsers
.length
,
954 for ( i
= 0; i
< len
; i
++ ) {
955 if ( parsers
[i
].id
.toLowerCase() === parser
.id
.toLowerCase() ) {
960 parsers
.push( parser
);
964 formatDigit: function ( s
) {
966 if ( ts
.transformTable
!== false ) {
968 for ( p
= 0; p
< s
.length
; p
++ ) {
970 if ( c
in ts
.transformTable
) {
971 out
+= ts
.transformTable
[c
];
978 i
= parseFloat( s
.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
979 return isNaN( i
) ? 0 : i
;
982 formatFloat: function ( s
) {
983 var i
= parseFloat( s
);
984 return isNaN( i
) ? 0 : i
;
987 formatInt: function ( s
) {
988 var i
= parseInt( s
, 10 );
989 return isNaN( i
) ? 0 : i
;
992 clearTableBody: function ( table
) {
993 $( table
.tBodies
[0] ).empty();
1000 // Register as jQuery prototype method
1001 $.fn
.tablesorter = function ( settings
) {
1002 return ts
.construct( this, settings
);
1005 // Add default parsers
1011 format: function ( s
) {
1012 s
= $.trim( s
.toLowerCase() );
1013 if ( ts
.collationRegex
) {
1014 var tsc
= ts
.collationTable
;
1015 s
= s
.replace( ts
.collationRegex
, function ( match
) {
1016 var r
= tsc
[match
] ? tsc
[match
] : tsc
[match
.toUpperCase()];
1017 return r
.toLowerCase();
1027 is: function ( s
) {
1028 return ts
.rgx
.IPAddress
[0].test( s
);
1030 format: function ( s
) {
1035 for ( i
= 0; i
< len
; i
++ ) {
1037 if ( item
.length
=== 1 ) {
1039 } else if ( item
.length
=== 2 ) {
1045 return $.tablesorter
.formatFloat( r
);
1052 is: function ( s
) {
1053 return ts
.rgx
.currency
[0].test( s
);
1055 format: function ( s
) {
1056 return $.tablesorter
.formatDigit( s
.replace( ts
.rgx
.currency
[1], '' ) );
1063 is: function ( s
) {
1064 return ts
.rgx
.url
[0].test( s
);
1066 format: function ( s
) {
1067 return $.trim( s
.replace( ts
.rgx
.url
[1], '' ) );
1074 is: function ( s
) {
1075 return ts
.rgx
.isoDate
[0].test( s
);
1077 format: function ( s
) {
1078 return $.tablesorter
.formatFloat( ( s
!== '' ) ? new Date( s
.replace(
1079 new RegExp( /-/g ), '/' ) ).getTime() : '0' );
1086 is: function ( s ) {
1087 return ts.rgx.usLongDate[0].test( s );
1089 format: function ( s ) {
1090 return $.tablesorter.formatFloat( new Date( s ).getTime() );
1097 is: function ( s ) {
1098 return ( ts.dateRegex[0].test( s ) || ts.dateRegex[1].test( s ) || ts.dateRegex[2].test( s ) );
1100 format: function ( s ) {
1102 s = $.trim( s.toLowerCase() );
1104 if ( ( match = s.match( ts.dateRegex[0] ) ) !== null ) {
1105 if ( mw.config.get( 'wgDefaultDateFormat
' ) === 'mdy
' || mw.config.get( 'wgContentLanguage
' ) === 'en
' ) {
1106 s = [ match[3], match[1], match[2] ];
1107 } else if ( mw.config.get( 'wgDefaultDateFormat
' ) === 'dmy
' ) {
1108 s = [ match[3], match[2], match[1] ];
1110 // If we get here, we don't know which order the dd
-dd
-dddd
1111 // date is in. So return something not entirely invalid.
1114 } else if ( ( match
= s
.match( ts
.dateRegex
[1] ) ) !== null ) {
1115 s
= [ match
[3], String( ts
.monthNames
[match
[2]] ), match
[1] ];
1116 } else if ( ( match
= s
.match( ts
.dateRegex
[2] ) ) !== null ) {
1117 s
= [ match
[3], String( ts
.monthNames
[match
[1]] ), match
[2] ];
1119 // Should never get here
1123 // Pad Month and Day
1124 if ( s
[1].length
=== 1 ) {
1127 if ( s
[2].length
=== 1 ) {
1131 if ( ( y
= parseInt( s
[0], 10 ) ) < 100 ) {
1132 // Guestimate years without centuries
1139 while ( s
[0].length
< 4 ) {
1142 return parseInt( s
.join( '' ), 10 );
1149 is: function ( s
) {
1150 return ts
.rgx
.time
[0].test( s
);
1152 format: function ( s
) {
1153 return $.tablesorter
.formatFloat( new Date( '2000/01/01 ' + s
).getTime() );
1160 is: function ( s
) {
1161 return $.tablesorter
.numberRegex
.test( $.trim( s
) );
1163 format: function ( s
) {
1164 return $.tablesorter
.formatDigit( s
);
1169 }( jQuery
, mediaWiki
) );