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, wgPageContentLanguage)
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 if ( elem
.nodeType
=== Node
.ELEMENT_NODE
) {
99 return getElementSortKey( elem
);
101 return $.text( elem
);
108 function detectParserForColumn( table
, rows
, cellIndex
) {
109 var l
= parsers
.length
,
111 // Start with 1 because 0 is the fallback parser
115 needed
= ( rows
.length
> 4 ) ? 5 : rows
.length
;
118 if ( rows
[rowIndex
] && rows
[rowIndex
].cells
[cellIndex
] ) {
119 nodeValue
= $.trim( getElementSortKey( rows
[rowIndex
].cells
[cellIndex
] ) );
124 if ( nodeValue
!== '' ) {
125 if ( parsers
[i
].is( nodeValue
, table
) ) {
128 if ( concurrent
>= needed
) {
129 // Confirmed the parser for multiple cells, let's return it
133 // Check next parser, reset rows
141 if ( rowIndex
> rows
.length
) {
148 // 0 is always the generic parser (text)
152 function buildParserCache( table
, $headers
) {
153 var sortType
, cells
, len
, i
, parser
,
154 rows
= table
.tBodies
[0].rows
,
159 cells
= rows
[0].cells
;
162 for ( i
= 0; i
< len
; i
++ ) {
164 sortType
= $headers
.eq( i
).data( 'sortType' );
165 if ( sortType
!== undefined ) {
166 parser
= getParserById( sortType
);
169 if ( parser
=== false ) {
170 parser
= detectParserForColumn( table
, rows
, i
);
173 parsers
.push( parser
);
179 /* Other utility functions */
181 function buildCache( table
) {
182 var i
, j
, $row
, cols
,
183 totalRows
= ( table
.tBodies
[0] && table
.tBodies
[0].rows
.length
) || 0,
184 totalCells
= ( table
.tBodies
[0].rows
[0] && table
.tBodies
[0].rows
[0].cells
.length
) || 0,
185 config
= $( table
).data( 'tablesorter' ).config
,
186 parsers
= config
.parsers
,
192 for ( i
= 0; i
< totalRows
; ++i
) {
194 // Add the table data to main data array
195 $row
= $( 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 ( $row
.hasClass( config
.cssChildRow
) ) {
201 cache
.row
[cache
.row
.length
- 1] = cache
.row
[cache
.row
.length
- 1].add( $row
);
202 // go to the next for loop
206 cache
.row
.push( $row
);
208 for ( j
= 0; j
< totalCells
; ++j
) {
209 cols
.push( parsers
[j
].format( getElementSortKey( $row
[0].cells
[j
] ), table
, $row
[0].cells
[j
] ) );
212 cols
.push( cache
.normalized
.length
); // add position for rowCache
213 cache
.normalized
.push( cols
);
220 function appendToTable( table
, cache
) {
223 normalized
= cache
.normalized
,
224 totalRows
= normalized
.length
,
225 checkCell
= ( normalized
[0].length
- 1 ),
226 fragment
= document
.createDocumentFragment();
228 for ( i
= 0; i
< totalRows
; i
++ ) {
229 pos
= normalized
[i
][checkCell
];
233 for ( j
= 0; j
< l
; j
++ ) {
234 fragment
.appendChild( row
[pos
][j
] );
238 table
.tBodies
[0].appendChild( fragment
);
240 $( table
).trigger( 'sortEnd.tablesorter' );
244 * Find all header rows in a thead-less table and put them in a <thead> tag.
245 * This only treats a row as a header row if it contains only <th>s (no <td>s)
246 * and if it is preceded entirely by header rows. The algorithm stops when
247 * it encounters the first non-header row.
249 * After this, it will look at all rows at the bottom for footer rows
250 * And place these in a tfoot using similar rules.
251 * @param $table jQuery object for a <table>
253 function emulateTHeadAndFoot( $table
) {
254 var $thead
, $tfoot
, i
, len
,
255 $rows
= $table
.find( '> tbody > tr' );
256 if ( !$table
.get( 0 ).tHead
) {
257 $thead
= $( '<thead>' );
258 $rows
.each( function () {
259 if ( $( this ).children( 'td' ).length
) {
260 // This row contains a <td>, so it's not a header row
264 $thead
.append( this );
266 $table
.find( ' > tbody:first' ).before( $thead
);
268 if ( !$table
.get( 0 ).tFoot
) {
269 $tfoot
= $( '<tfoot>' );
271 for ( i
= len
- 1; i
>= 0; i
-- ) {
272 if ( $( $rows
[i
] ).children( 'td' ).length
) {
275 $tfoot
.prepend( $( $rows
[i
] ) );
277 $table
.append( $tfoot
);
281 function buildHeaders( table
, msg
) {
282 var config
= $( table
).data( 'tablesorter' ).config
,
293 $tableHeaders
= $( [] ),
294 $tableRows
= $( 'thead:eq(0) > tr', table
);
295 if ( $tableRows
.length
<= 1 ) {
296 $tableHeaders
= $tableRows
.children( 'th' );
300 // Loop through all the dom cells of the thead
301 $tableRows
.each( function ( rowIndex
, row
) {
302 $.each( row
.cells
, function ( columnIndex
, cell
) {
306 rowspan
= Number( cell
.rowSpan
);
307 colspan
= Number( cell
.colSpan
);
309 // Skip the spots in the exploded matrix that are already filled
310 while ( exploded
[rowIndex
] && exploded
[rowIndex
][columnIndex
] !== undefined ) {
314 // Find the actual dimensions of the thead, by placing each cell
315 // in the exploded matrix rowspan times colspan times, with the proper offsets
316 for ( matrixColumnIndex
= columnIndex
; matrixColumnIndex
< columnIndex
+ colspan
; ++matrixColumnIndex
) {
317 for ( matrixRowIndex
= rowIndex
; matrixRowIndex
< rowIndex
+ rowspan
; ++matrixRowIndex
) {
318 if ( !exploded
[matrixRowIndex
] ) {
319 exploded
[matrixRowIndex
] = [];
321 exploded
[matrixRowIndex
][matrixColumnIndex
] = cell
;
326 // We want to find the row that has the most columns (ignoring colspan)
327 $.each( exploded
, function ( index
, cellArray
) {
328 headerCount
= $( uniqueElements( cellArray
) ).filter( 'th' ).length
;
329 if ( headerCount
>= maxSeen
) {
330 maxSeen
= headerCount
;
334 // We cannot use $.unique() here because it sorts into dom order, which is undesirable
335 $tableHeaders
= $( uniqueElements( exploded
[longestTR
] ) ).filter( 'th' );
338 // as each header can span over multiple columns (using colspan=N),
339 // we have to bidirectionally map headers to their columns and columns to their headers
340 $tableHeaders
.each( function ( headerIndex
) {
344 for ( i
= 0; i
< this.colSpan
; i
++ ) {
345 config
.columnToHeader
[ colspanOffset
+ i
] = headerIndex
;
346 columns
.push( colspanOffset
+ i
);
349 config
.headerToColumns
[ headerIndex
] = columns
;
350 colspanOffset
+= this.colSpan
;
353 headerIndex
: headerIndex
,
358 if ( $cell
.hasClass( config
.unsortableClass
) ) {
359 $cell
.data( 'sortDisabled', true );
362 if ( !$cell
.data( 'sortDisabled' ) ) {
364 .addClass( config
.cssHeader
)
365 .prop( 'tabIndex', 0 )
367 role
: 'columnheader button',
372 // add cell to headerList
373 config
.headerList
[headerIndex
] = this;
376 return $tableHeaders
;
381 * Sets the sort count of the columns that are not affected by the sorting to have them sorted
382 * in default (ascending) order when their header cell is clicked the next time.
384 * @param {jQuery} $headers
385 * @param {Number[][]} sortList
386 * @param {Number[][]} headerToColumns
388 function setHeadersOrder( $headers
, sortList
, headerToColumns
) {
389 // Loop through all headers to retrieve the indices of the columns the header spans across:
390 $.each( headerToColumns
, function ( headerIndex
, columns
) {
392 $.each( columns
, function ( i
, columnIndex
) {
393 var header
= $headers
[headerIndex
],
394 $header
= $( header
);
396 if ( !isValueInArray( columnIndex
, sortList
) ) {
397 // Column shall not be sorted: Reset header count and order.
403 // Column shall be sorted: Apply designated count and order.
404 $.each( sortList
, function ( j
, sortColumn
) {
405 if ( sortColumn
[0] === i
) {
407 order
: sortColumn
[1],
408 count
: sortColumn
[1] + 1
419 function isValueInArray( v
, a
) {
422 for ( i
= 0; i
< len
; i
++ ) {
423 if ( a
[i
][0] === v
) {
430 function uniqueElements( array
) {
432 $.each( array
, function ( index
, elem
) {
433 if ( elem
!== undefined && $.inArray( elem
, uniques
) === -1 ) {
434 uniques
.push( elem
);
440 function setHeadersCss( table
, $headers
, list
, css
, msg
, columnToHeader
) {
441 // Remove all header information and reset titles to default message
442 $headers
.removeClass( css
[0] ).removeClass( css
[1] ).attr( 'title', msg
[1] );
444 for ( var i
= 0; i
< list
.length
; i
++ ) {
445 $headers
.eq( columnToHeader
[ list
[i
][0] ] )
446 .addClass( css
[ list
[i
][1] ] )
447 .attr( 'title', msg
[ list
[i
][1] ] );
451 function sortText( a
, b
) {
452 return ( ( a
< b
) ? -1 : ( ( a
> b
) ? 1 : 0 ) );
455 function sortTextDesc( a
, b
) {
456 return ( ( b
< a
) ? -1 : ( ( b
> a
) ? 1 : 0 ) );
459 function multisort( table
, sortList
, cache
) {
462 len
= sortList
.length
;
463 for ( i
= 0; i
< len
; i
++ ) {
464 sortFn
[i
] = ( sortList
[i
][1] ) ? sortTextDesc
: sortText
;
466 cache
.normalized
.sort( function ( array1
, array2
) {
468 for ( i
= 0; i
< len
; i
++ ) {
469 col
= sortList
[i
][0];
470 ret
= sortFn
[i
].call( this, array1
[col
], array2
[col
] );
475 // Fall back to index number column to ensure stable sort
476 return sortText
.call( this, array1
[array1
.length
- 1], array2
[array2
.length
- 1] );
481 function buildTransformTable() {
482 var ascii
, localised
, i
, digitClass
,
483 digits
= '0123456789,.'.split( '' ),
484 separatorTransformTable
= mw
.config
.get( 'wgSeparatorTransformTable' ),
485 digitTransformTable
= mw
.config
.get( 'wgDigitTransformTable' );
487 if ( separatorTransformTable
=== null || ( separatorTransformTable
[0] === '' && digitTransformTable
[2] === '' ) ) {
488 ts
.transformTable
= false;
490 ts
.transformTable
= {};
492 // Unpack the transform table
493 ascii
= separatorTransformTable
[0].split( '\t' ).concat( digitTransformTable
[0].split( '\t' ) );
494 localised
= separatorTransformTable
[1].split( '\t' ).concat( digitTransformTable
[1].split( '\t' ) );
496 // Construct regex for number identification
497 for ( i
= 0; i
< ascii
.length
; i
++ ) {
498 ts
.transformTable
[localised
[i
]] = ascii
[i
];
499 digits
.push( mw
.RegExp
.escape( localised
[i
] ) );
502 digitClass
= '[' + digits
.join( '', digits
) + ']';
504 // We allow a trailing percent sign, which we just strip. This works fine
505 // if percents and regular numbers aren't being mixed.
506 ts
.numberRegex
= new RegExp( '^(' + '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
507 '|' + '[-+\u2212]?' + digitClass
+ '+[\\s\\xa0]*%?' + // Generic localised
511 function buildDateTable() {
517 for ( i
= 0; i
< 12; i
++ ) {
518 name
= mw
.language
.months
.names
[i
].toLowerCase();
519 ts
.monthNames
[name
] = i
+ 1;
520 regex
.push( mw
.RegExp
.escape( name
) );
521 name
= mw
.language
.months
.genitive
[i
].toLowerCase();
522 ts
.monthNames
[name
] = i
+ 1;
523 regex
.push( mw
.RegExp
.escape( name
) );
524 name
= mw
.language
.months
.abbrev
[i
].toLowerCase().replace( '.', '' );
525 ts
.monthNames
[name
] = i
+ 1;
526 regex
.push( mw
.RegExp
.escape( name
) );
529 // Build piped string
530 regex
= regex
.join( '|' );
533 // Any date formated with . , ' - or /
534 ts
.dateRegex
[0] = new RegExp( /^\s*(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{2,4})\s*?/i );
536 // Written Month name, dmy
537 ts
.dateRegex
[1] = new RegExp( '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
539 // Written Month name, mdy
540 ts
.dateRegex
[2] = new RegExp( '^\\s*(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
545 * Replace all rowspanned cells in the body with clones in each row, so sorting
546 * need not worry about them.
548 * @param $table jQuery object for a <table>
550 function explodeRowspans( $table
) {
551 var spanningRealCellIndex
, rowSpan
, colSpan
,
552 cell
, cellData
, i
, $tds
, $clone
, $nextRows
,
553 rowspanCells
= $table
.find( '> tbody > tr > [rowspan]' ).get();
556 if ( !rowspanCells
.length
) {
560 // First, we need to make a property like cellIndex but taking into
561 // account colspans. We also cache the rowIndex to avoid having to take
562 // cell.parentNode.rowIndex in the sorting function below.
563 $table
.find( '> tbody > tr' ).each( function () {
566 l
= this.cells
.length
;
567 for ( i
= 0; i
< l
; i
++ ) {
568 $( this.cells
[i
] ).data( 'tablesorter', {
570 realRowIndex
: this.rowIndex
572 col
+= this.cells
[i
].colSpan
;
576 // Split multi row cells into multiple cells with the same content.
577 // Sort by column then row index to avoid problems with odd table structures.
578 // Re-sort whenever a rowspanned cell's realCellIndex is changed, because it
579 // might change the sort order.
580 function resortCells() {
584 rowspanCells
= rowspanCells
.sort( function ( a
, b
) {
585 cellAData
= $.data( a
, 'tablesorter' );
586 cellBData
= $.data( b
, 'tablesorter' );
587 ret
= cellAData
.realCellIndex
- cellBData
.realCellIndex
;
589 ret
= cellAData
.realRowIndex
- cellBData
.realRowIndex
;
593 $.each( rowspanCells
, function () {
594 $.data( this, 'tablesorter' ).needResort
= false;
599 function filterfunc() {
600 return $.data( this, 'tablesorter' ).realCellIndex
>= spanningRealCellIndex
;
603 function fixTdCellIndex() {
604 $.data( this, 'tablesorter' ).realCellIndex
+= colSpan
;
605 if ( this.rowSpan
> 1 ) {
606 $.data( this, 'tablesorter' ).needResort
= true;
610 while ( rowspanCells
.length
) {
611 if ( $.data( rowspanCells
[0], 'tablesorter' ).needResort
) {
615 cell
= rowspanCells
.shift();
616 cellData
= $.data( cell
, 'tablesorter' );
617 rowSpan
= cell
.rowSpan
;
618 colSpan
= cell
.colSpan
;
619 spanningRealCellIndex
= cellData
.realCellIndex
;
621 $nextRows
= $( cell
).parent().nextAll();
622 for ( i
= 0; i
< rowSpan
- 1; i
++ ) {
623 $tds
= $( $nextRows
[i
].cells
).filter( filterfunc
);
624 $clone
= $( cell
).clone();
625 $clone
.data( 'tablesorter', {
626 realCellIndex
: spanningRealCellIndex
,
627 realRowIndex
: cellData
.realRowIndex
+ i
,
631 $tds
.each( fixTdCellIndex
);
632 $tds
.first().before( $clone
);
634 $nextRows
.eq( i
).append( $clone
);
640 function buildCollationTable() {
641 ts
.collationTable
= mw
.config
.get( 'tableSorterCollation' );
642 ts
.collationRegex
= null;
643 if ( ts
.collationTable
) {
647 // Build array of key names
648 for ( key
in ts
.collationTable
) {
649 // Check hasOwn to be safe
650 if ( ts
.collationTable
.hasOwnProperty( key
) ) {
655 ts
.collationRegex
= new RegExp( '[' + keys
.join( '' ) + ']', 'ig' );
660 function cacheRegexs() {
666 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/ )
669 new RegExp( /(^[£$€¥]|[£$€¥]$)/ ),
670 new RegExp( /[£$€¥]/g )
673 new RegExp( /^(https?|ftp|file):\/\/$/ ),
674 new RegExp( /(https?|ftp|file):\/\// )
677 new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/ )
680 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)))$/ )
683 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/ )
689 * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
690 * structure [ [ Integer , Integer ], ... ]
692 * @param sortObjects {Array} List of sort objects.
693 * @return {Array} List of internal sort definitions.
696 function convertSortList( sortObjects
) {
698 $.each( sortObjects
, function ( i
, sortObject
) {
699 $.each( sortObject
, function ( columnIndex
, order
) {
700 var orderIndex
= ( order
=== 'desc' ) ? 1 : 0;
701 sortList
.push( [parseInt( columnIndex
, 10 ), orderIndex
] );
711 cssHeader
: 'headerSort',
712 cssAsc
: 'headerSortUp',
713 cssDesc
: 'headerSortDown',
714 cssChildRow
: 'expand-child',
715 sortMultiSortKey
: 'shiftKey',
716 unsortableClass
: 'unsortable',
718 cancelSelection
: true,
729 * @param $tables {jQuery}
730 * @param settings {Object} (optional)
732 construct: function ( $tables
, settings
) {
733 return $tables
.each( function ( i
, table
) {
734 // Declare and cache.
735 var $headers
, cache
, config
, sortCSS
, sortMsg
,
740 if ( !table
.tBodies
) {
743 if ( !table
.tHead
) {
744 // No thead found. Look for rows with <th>s and
745 // move them into a <thead> tag or a <tfoot> tag
746 emulateTHeadAndFoot( $table
);
748 // Still no thead? Then quit
749 if ( !table
.tHead
) {
753 $table
.addClass( 'jquery-tablesorter' );
756 config
= $.extend( {}, $.tablesorter
.defaultOptions
, settings
);
758 // Save the settings where they read
759 $.data( table
, 'tablesorter', { config
: config
} );
761 // Get the CSS class names, could be done elsewhere
762 sortCSS
= [ config
.cssDesc
, config
.cssAsc
];
763 sortMsg
= [ mw
.msg( 'sort-descending' ), mw
.msg( 'sort-ascending' ) ];
766 $headers
= buildHeaders( table
, sortMsg
);
768 // Grab and process locale settings.
769 buildTransformTable();
772 // Precaching regexps can bring 10 fold
773 // performance improvements in some browsers.
776 function setupForFirstSort() {
779 // Defer buildCollationTable to first sort. As user and site scripts
780 // may customize tableSorterCollation but load after $.ready(), other
781 // scripts may call .tablesorter() before they have done the
782 // tableSorterCollation customizations.
783 buildCollationTable();
785 // Legacy fix of .sortbottoms
786 // Wrap them inside a tfoot (because that's what they actually want to be)
787 // and put the <tfoot> at the end of the <table>
789 $sortbottoms
= $table
.find( '> tbody > tr.sortbottom' );
790 if ( $sortbottoms
.length
) {
791 $tfoot
= $table
.children( 'tfoot' );
792 if ( $tfoot
.length
) {
793 $tfoot
.eq( 0 ).prepend( $sortbottoms
);
795 $table
.append( $( '<tfoot>' ).append( $sortbottoms
) );
799 explodeRowspans( $table
);
801 // Try to auto detect column type, and store in tables config
802 config
.parsers
= buildParserCache( table
, $headers
);
805 // Apply event handling to headers
806 // this is too big, perhaps break it out?
807 $headers
.not( '.' + config
.unsortableClass
).on( 'keypress click', function ( e
) {
808 var cell
, $cell
, columns
, newSortList
, i
,
812 if ( e
.type
=== 'click' && e
.target
.nodeName
.toLowerCase() === 'a' ) {
813 // The user clicked on a link inside a table header.
814 // Do nothing and let the default link click action continue.
818 if ( e
.type
=== 'keypress' && e
.which
!== 13 ) {
819 // Only handle keypresses on the "Enter" key.
827 // Build the cache for the tbody cells
828 // to share between calculations for this sort action.
829 // Re-calculated each time a sort action is performed due to possiblity
830 // that sort values change. Shouldn't be too expensive, but if it becomes
831 // too slow an event based system should be implemented somehow where
832 // cells get event .change() and bubbles up to the <table> here
833 cache
= buildCache( table
);
835 totalRows
= ( $table
[0].tBodies
[0] && $table
[0].tBodies
[0].rows
.length
) || 0;
836 if ( !table
.sortDisabled
&& totalRows
> 0 ) {
840 // Get current column sort order
842 order
: $cell
.data( 'count' ) % 2,
843 count
: $cell
.data( 'count' ) + 1
847 // Get current column index
848 columns
= config
.headerToColumns
[ $cell
.data( 'headerIndex' ) ];
849 newSortList
= $.map( columns
, function ( c
) {
850 // jQuery "helpfully" flattens the arrays...
851 return [[c
, $cell
.data( 'order' )]];
853 // Index of first column belonging to this header
856 if ( !e
[config
.sortMultiSortKey
] ) {
857 // User only wants to sort on one column set
858 // Flush the sort list and add new columns
859 config
.sortList
= newSortList
;
861 // Multi column sorting
862 // It is not possible for one column to belong to multiple headers,
863 // so this is okay - we don't need to check for every value in the columns array
864 if ( isValueInArray( i
, config
.sortList
) ) {
865 // The user has clicked on an already sorted column.
866 // Reverse the sorting direction for all tables.
867 for ( j
= 0; j
< config
.sortList
.length
; j
++ ) {
868 s
= config
.sortList
[j
];
869 o
= config
.headerList
[s
[0]];
870 if ( isValueInArray( s
[0], newSortList
) ) {
871 $( o
).data( 'count', s
[1] + 1 );
872 s
[1] = $( o
).data( 'count' ) % 2;
876 // Add columns to sort list array
877 config
.sortList
= config
.sortList
.concat( newSortList
);
881 // Reset order/counts of cells not affected by sorting
882 setHeadersOrder( $headers
, config
.sortList
, config
.headerToColumns
);
884 // Set CSS for headers
885 setHeadersCss( $table
[0], $headers
, config
.sortList
, sortCSS
, sortMsg
, config
.columnToHeader
);
887 $table
[0], multisort( $table
[0], config
.sortList
, cache
)
890 // Stop normal event by returning false
895 } ).mousedown( function () {
896 if ( config
.cancelSelection
) {
897 this.onselectstart = function () {
905 * Sorts the table. If no sorting is specified by passing a list of sort
906 * objects, the table is sorted according to the initial sorting order.
907 * Passing an empty array will reset sorting (basically just reset the headers
908 * making the table appear unsorted).
910 * @param sortList {Array} (optional) List of sort objects.
912 $table
.data( 'tablesorter' ).sort = function ( sortList
) {
918 if ( sortList
=== undefined ) {
919 sortList
= config
.sortList
;
920 } else if ( sortList
.length
> 0 ) {
921 sortList
= convertSortList( sortList
);
924 // Set each column's sort count to be able to determine the correct sort
925 // order when clicking on a header cell the next time
926 setHeadersOrder( $headers
, sortList
, config
.headerToColumns
);
928 // re-build the cache for the tbody cells
929 cache
= buildCache( table
);
931 // set css for headers
932 setHeadersCss( table
, $headers
, sortList
, sortCSS
, sortMsg
, config
.columnToHeader
);
934 // sort the table and append it to the dom
935 appendToTable( table
, multisort( table
, sortList
, cache
) );
939 if ( config
.sortList
.length
> 0 ) {
941 config
.sortList
= convertSortList( config
.sortList
);
942 $table
.data( 'tablesorter' ).sort();
948 addParser: function ( parser
) {
950 len
= parsers
.length
,
952 for ( i
= 0; i
< len
; i
++ ) {
953 if ( parsers
[i
].id
.toLowerCase() === parser
.id
.toLowerCase() ) {
958 parsers
.push( parser
);
962 formatDigit: function ( s
) {
964 if ( ts
.transformTable
!== false ) {
966 for ( p
= 0; p
< s
.length
; p
++ ) {
968 if ( c
in ts
.transformTable
) {
969 out
+= ts
.transformTable
[c
];
976 i
= parseFloat( s
.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
977 return isNaN( i
) ? 0 : i
;
980 formatFloat: function ( s
) {
981 var i
= parseFloat( s
);
982 return isNaN( i
) ? 0 : i
;
985 formatInt: function ( s
) {
986 var i
= parseInt( s
, 10 );
987 return isNaN( i
) ? 0 : i
;
990 clearTableBody: function ( table
) {
991 $( table
.tBodies
[0] ).empty();
994 getParser: function ( id
) {
995 buildTransformTable();
998 buildCollationTable();
1000 return getParserById( id
);
1007 // Register as jQuery prototype method
1008 $.fn
.tablesorter = function ( settings
) {
1009 return ts
.construct( this, settings
);
1012 // Add default parsers
1018 format: function ( s
) {
1019 s
= $.trim( s
.toLowerCase() );
1020 if ( ts
.collationRegex
) {
1021 var tsc
= ts
.collationTable
;
1022 s
= s
.replace( ts
.collationRegex
, function ( match
) {
1023 var r
= tsc
[match
] ? tsc
[match
] : tsc
[match
.toUpperCase()];
1024 return r
.toLowerCase();
1034 is: function ( s
) {
1035 return ts
.rgx
.IPAddress
[0].test( s
);
1037 format: function ( s
) {
1042 for ( i
= 0; i
< len
; i
++ ) {
1044 if ( item
.length
=== 1 ) {
1046 } else if ( item
.length
=== 2 ) {
1052 return $.tablesorter
.formatFloat( r
);
1059 is: function ( s
) {
1060 return ts
.rgx
.currency
[0].test( s
);
1062 format: function ( s
) {
1063 return $.tablesorter
.formatDigit( s
.replace( ts
.rgx
.currency
[1], '' ) );
1070 is: function ( s
) {
1071 return ts
.rgx
.url
[0].test( s
);
1073 format: function ( s
) {
1074 return $.trim( s
.replace( ts
.rgx
.url
[1], '' ) );
1081 is: function ( s
) {
1082 return ts
.rgx
.isoDate
[0].test( s
);
1084 format: function ( s
) {
1085 return $.tablesorter
.formatFloat( ( s
!== '' ) ? new Date( s
.replace(
1086 new RegExp( /-/g ), '/' ) ).getTime() : '0' );
1093 is: function ( s ) {
1094 return ts.rgx.usLongDate[0].test( s );
1096 format: function ( s ) {
1097 return $.tablesorter.formatFloat( new Date( s ).getTime() );
1104 is: function ( s ) {
1105 return ( ts.dateRegex[0].test( s ) || ts.dateRegex[1].test( s ) || ts.dateRegex[2].test( s ) );
1107 format: function ( s ) {
1109 s = $.trim( s.toLowerCase() );
1111 if ( ( match = s.match( ts.dateRegex[0] ) ) !== null ) {
1112 if ( mw.config.get( 'wgDefaultDateFormat
' ) === 'mdy
' || mw.config.get( 'wgPageContentLanguage
' ) === 'en
' ) {
1113 s = [ match[3], match[1], match[2] ];
1114 } else if ( mw.config.get( 'wgDefaultDateFormat
' ) === 'dmy
' ) {
1115 s = [ match[3], match[2], match[1] ];
1117 // If we get here, we don't know which order the dd
-dd
-dddd
1118 // date is in. So return something not entirely invalid.
1121 } else if ( ( match
= s
.match( ts
.dateRegex
[1] ) ) !== null ) {
1122 s
= [ match
[3], String( ts
.monthNames
[match
[2]] ), match
[1] ];
1123 } else if ( ( match
= s
.match( ts
.dateRegex
[2] ) ) !== null ) {
1124 s
= [ match
[3], String( ts
.monthNames
[match
[1]] ), match
[2] ];
1126 // Should never get here
1130 // Pad Month and Day
1131 if ( s
[1].length
=== 1 ) {
1134 if ( s
[2].length
=== 1 ) {
1138 if ( ( y
= parseInt( s
[0], 10 ) ) < 100 ) {
1139 // Guestimate years without centuries
1146 while ( s
[0].length
< 4 ) {
1149 return parseInt( s
.join( '' ), 10 );
1156 is: function ( s
) {
1157 return ts
.rgx
.time
[0].test( s
);
1159 format: function ( s
) {
1160 return $.tablesorter
.formatFloat( new Date( '2000/01/01 ' + s
).getTime() );
1167 is: function ( s
) {
1168 return $.tablesorter
.numberRegex
.test( $.trim( s
) );
1170 format: function ( s
) {
1171 return $.tablesorter
.formatDigit( s
);
1176 }( jQuery
, mediaWiki
) );