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)
16 * Create a sortable table with multi-column sorting capabilities
18 * // Create a simple tablesorter interface
19 * $( 'table' ).tablesorter();
21 * // Create a tablesorter interface, initially sorting on the first and second column
22 * $( 'table' ).tablesorter( { sortList: [ { 0: 'desc' }, { 1: 'asc' } ] } );
24 * @param {string} [cssHeader="header"] A string of the class name to be appended to sortable
25 * tr elements in the thead of the table.
27 * @param {string} [cssAsc="headerSortUp"] A string of the class name to be appended to
28 * sortable tr elements in the thead on a ascending sort.
30 * @param {string} [cssDesc="headerSortDown"] A string of the class name to be appended to
31 * sortable tr elements in the thead on a descending sort.
33 * @param {string} [sortMultisortKey="shiftKey"] A string of the multi-column sort key.
35 * @param {boolean} [cancelSelection=true] Boolean flag indicating iftablesorter should cancel
36 * selection of the table headers text.
38 * @param {Array} [sortList] An array containing objects specifying sorting. By passing more
39 * than one object, multi-sorting will be applied. Object structure:
40 * { <Integer column index>: <String 'asc' or 'desc'> }
42 * @event sortEnd.tablesorter: Triggered as soon as any sorting has been applied.
44 * @author Christian Bach/christian.bach@polyester.se
46 ( function ( $, mw
) {
50 /* Parser utility functions */
52 function getParserById( name
) {
54 for ( i
= 0; i
< parsers
.length
; i
++ ) {
55 if ( parsers
[ i
].id
.toLowerCase() === name
.toLowerCase() ) {
62 function getElementSortKey( node
) {
63 var $node
= $( node
),
64 // Use data-sort-value attribute.
65 // Use data() instead of attr() so that live value changes
66 // are processed as well (bug 38152).
67 data
= $node
.data( 'sortValue' );
69 if ( data
!== null && data
!== undefined ) {
70 // Cast any numbers or other stuff to a string, methods
71 // like charAt, toLowerCase and split are expected.
72 return String( data
);
77 if ( node
.tagName
.toLowerCase() === 'img' ) {
78 return $node
.attr( 'alt' ) || ''; // handle undefined alt
80 return $.map( $.makeArray( node
.childNodes
), function ( elem
) {
81 if ( elem
.nodeType
=== Node
.ELEMENT_NODE
) {
82 return getElementSortKey( elem
);
84 return $.text( elem
);
88 function detectParserForColumn( table
, rows
, column
) {
89 var l
= parsers
.length
,
90 config
= $( table
).data( 'tablesorter' ).config
,
93 // Start with 1 because 0 is the fallback parser
99 needed
= ( rows
.length
> 4 ) ? 5 : rows
.length
;
102 // if this is a child row, continue to the next row (as buildCache())
103 if ( rows
[ rowIndex
] && !$( rows
[ rowIndex
] ).hasClass( config
.cssChildRow
) ) {
104 if ( rowIndex
!== lastRowIndex
) {
105 lastRowIndex
= rowIndex
;
106 cellIndex
= $( rows
[ rowIndex
] ).data( 'columnToCell' )[ column
];
107 nodeValue
= $.trim( getElementSortKey( rows
[ rowIndex
].cells
[ cellIndex
] ) );
113 if ( nodeValue
!== '' ) {
114 if ( parsers
[ i
].is( nodeValue
, table
) ) {
117 if ( concurrent
>= needed
) {
118 // Confirmed the parser for multiple cells, let's return it
122 // Check next parser, reset rows
132 if ( rowIndex
>= rows
.length
) {
133 if ( concurrent
>= rows
.length
- empty
) {
134 // Confirmed the parser for all filled cells
137 // Check next parser, reset rows
146 // 0 is always the generic parser (text)
150 function buildParserCache( table
, $headers
) {
151 var sortType
, len
, j
, parser
,
152 rows
= table
.tBodies
[ 0 ].rows
,
153 config
= $( table
).data( 'tablesorter' ).config
,
157 len
= config
.columns
;
158 for ( j
= 0; j
< len
; j
++ ) {
160 sortType
= $headers
.eq( config
.columnToHeader
[ j
] ).data( 'sortType' );
161 if ( sortType
!== undefined ) {
162 parser
= getParserById( sortType
);
165 if ( parser
=== false ) {
166 parser
= detectParserForColumn( table
, rows
, j
);
169 parsers
.push( parser
);
175 /* Other utility functions */
177 function buildCache( table
) {
178 var i
, j
, $row
, cols
,
179 totalRows
= ( table
.tBodies
[ 0 ] && table
.tBodies
[ 0 ].rows
.length
) || 0,
180 config
= $( table
).data( 'tablesorter' ).config
,
181 parsers
= config
.parsers
,
182 len
= parsers
.length
,
189 for ( i
= 0; i
< totalRows
; i
++ ) {
191 // Add the table data to main data array
192 $row
= $( table
.tBodies
[ 0 ].rows
[ i
] );
195 // if this is a child row, add it to the last row's children and
196 // continue to the next row
197 if ( $row
.hasClass( config
.cssChildRow
) ) {
198 cache
.row
[ cache
.row
.length
- 1 ] = cache
.row
[ cache
.row
.length
- 1 ].add( $row
);
199 // go to the next for loop
203 cache
.row
.push( $row
);
205 for ( j
= 0; j
< len
; j
++ ) {
206 cellIndex
= $row
.data( 'columnToCell' )[ j
];
207 cols
.push( parsers
[ j
].format( getElementSortKey( $row
[ 0 ].cells
[ cellIndex
] ) ) );
210 cols
.push( cache
.normalized
.length
); // add position for rowCache
211 cache
.normalized
.push( cols
);
218 function appendToTable( table
, cache
) {
221 normalized
= cache
.normalized
,
222 totalRows
= normalized
.length
,
223 checkCell
= ( normalized
[ 0 ].length
- 1 ),
224 fragment
= document
.createDocumentFragment();
226 for ( i
= 0; i
< totalRows
; i
++ ) {
227 pos
= normalized
[ i
][ checkCell
];
229 l
= row
[ pos
].length
;
230 for ( j
= 0; j
< l
; j
++ ) {
231 fragment
.appendChild( row
[ pos
][ j
] );
235 table
.tBodies
[ 0 ].appendChild( fragment
);
237 $( table
).trigger( 'sortEnd.tablesorter' );
241 * Find all header rows in a thead-less table and put them in a <thead> tag.
242 * This only treats a row as a header row if it contains only <th>s (no <td>s)
243 * and if it is preceded entirely by header rows. The algorithm stops when
244 * it encounters the first non-header row.
246 * After this, it will look at all rows at the bottom for footer rows
247 * And place these in a tfoot using similar rules.
249 * @param {jQuery} $table object for a <table>
251 function emulateTHeadAndFoot( $table
) {
252 var $thead
, $tfoot
, i
, len
,
253 $rows
= $table
.find( '> tbody > tr' );
254 if ( !$table
.get( 0 ).tHead
) {
255 $thead
= $( '<thead>' );
256 $rows
.each( function () {
257 if ( $( this ).children( 'td' ).length
) {
258 // This row contains a <td>, so it's not a header row
262 $thead
.append( this );
264 $table
.find( ' > tbody:first' ).before( $thead
);
266 if ( !$table
.get( 0 ).tFoot
) {
267 $tfoot
= $( '<tfoot>' );
269 for ( i
= len
- 1; i
>= 0; i
-- ) {
270 if ( $( $rows
[ i
] ).children( 'td' ).length
) {
273 $tfoot
.prepend( $( $rows
[ i
] ) );
275 $table
.append( $tfoot
);
279 function uniqueElements( array
) {
281 $.each( array
, function ( i
, elem
) {
282 if ( elem
!== undefined && $.inArray( elem
, uniques
) === -1 ) {
283 uniques
.push( elem
);
289 function buildHeaders( table
, msg
) {
290 var config
= $( table
).data( 'tablesorter' ).config
,
302 $tableHeaders
= $( [] ),
303 $tableRows
= $( 'thead:eq(0) > tr', table
);
305 if ( $tableRows
.length
<= 1 ) {
306 $tableHeaders
= $tableRows
.children( 'th' );
310 // Loop through all the dom cells of the thead
311 $tableRows
.each( function ( rowIndex
, row
) {
312 $.each( row
.cells
, function ( columnIndex
, cell
) {
316 rowspan
= Number( cell
.rowSpan
);
317 colspan
= Number( cell
.colSpan
);
319 // Skip the spots in the exploded matrix that are already filled
320 while ( exploded
[ rowIndex
] && exploded
[ rowIndex
][ columnIndex
] !== undefined ) {
324 // Find the actual dimensions of the thead, by placing each cell
325 // in the exploded matrix rowspan times colspan times, with the proper offsets
326 for ( matrixColumnIndex
= columnIndex
; matrixColumnIndex
< columnIndex
+ colspan
; ++matrixColumnIndex
) {
327 for ( matrixRowIndex
= rowIndex
; matrixRowIndex
< rowIndex
+ rowspan
; ++matrixRowIndex
) {
328 if ( !exploded
[ matrixRowIndex
] ) {
329 exploded
[ matrixRowIndex
] = [];
331 exploded
[ matrixRowIndex
][ matrixColumnIndex
] = cell
;
336 // We want to find the row that has the most columns (ignoring colspan)
337 $.each( exploded
, function ( index
, cellArray
) {
338 headerCount
= $( uniqueElements( cellArray
) ).filter( 'th' ).length
;
339 if ( headerCount
>= maxSeen
) {
340 maxSeen
= headerCount
;
344 // We cannot use $.unique() here because it sorts into dom order, which is undesirable
345 $tableHeaders
= $( uniqueElements( exploded
[ longestTR
] ) ).filter( 'th' );
348 // as each header can span over multiple columns (using colspan=N),
349 // we have to bidirectionally map headers to their columns and columns to their headers
350 config
.columnToHeader
= [];
351 config
.headerToColumns
= [];
352 config
.headerList
= [];
354 $tableHeaders
.each( function () {
358 if ( !$cell
.hasClass( config
.unsortableClass
) ) {
360 .addClass( config
.cssHeader
)
361 .prop( 'tabIndex', 0 )
363 role
: 'columnheader button',
367 for ( k
= 0; k
< this.colSpan
; k
++ ) {
368 config
.columnToHeader
[ colspanOffset
+ k
] = headerIndex
;
369 columns
.push( colspanOffset
+ k
);
372 config
.headerToColumns
[ headerIndex
] = columns
;
375 headerIndex
: headerIndex
,
380 // add only sortable cells to headerList
381 config
.headerList
[ headerIndex
] = this;
385 colspanOffset
+= this.colSpan
;
388 // number of columns with extended colspan, inclusive unsortable
389 // parsers[j], cache[][j], columnToHeader[j], columnToCell[j] have so many elements
390 config
.columns
= colspanOffset
;
392 return $tableHeaders
.not( '.' + config
.unsortableClass
);
395 function isValueInArray( v
, a
) {
397 for ( i
= 0; i
< a
.length
; i
++ ) {
398 if ( a
[ i
][ 0 ] === v
) {
406 * Sets the sort count of the columns that are not affected by the sorting to have them sorted
407 * in default (ascending) order when their header cell is clicked the next time.
409 * @param {jQuery} $headers
410 * @param {number[][]} sortList
411 * @param {number[][]} headerToColumns
413 function setHeadersOrder( $headers
, sortList
, headerToColumns
) {
414 // Loop through all headers to retrieve the indices of the columns the header spans across:
415 $.each( headerToColumns
, function ( headerIndex
, columns
) {
417 $.each( columns
, function ( i
, columnIndex
) {
418 var header
= $headers
[ headerIndex
],
419 $header
= $( header
);
421 if ( !isValueInArray( columnIndex
, sortList
) ) {
422 // Column shall not be sorted: Reset header count and order.
428 // Column shall be sorted: Apply designated count and order.
429 $.each( sortList
, function ( j
, sortColumn
) {
430 if ( sortColumn
[ 0 ] === i
) {
432 order
: sortColumn
[ 1 ],
433 count
: sortColumn
[ 1 ] + 1
444 function setHeadersCss( table
, $headers
, list
, css
, msg
, columnToHeader
) {
445 // Remove all header information and reset titles to default message
446 $headers
.removeClass( css
[ 0 ] ).removeClass( css
[ 1 ] ).attr( 'title', msg
[ 1 ] );
448 for ( var i
= 0; i
< list
.length
; i
++ ) {
450 .eq( columnToHeader
[ list
[ i
][ 0 ] ] )
451 .addClass( css
[ list
[ i
][ 1 ] ] )
452 .attr( 'title', msg
[ list
[ i
][ 1 ] ] );
456 function sortText( a
, b
) {
457 return ( ( a
< b
) ? -1 : ( ( a
> b
) ? 1 : 0 ) );
460 function sortTextDesc( a
, b
) {
461 return ( ( b
< a
) ? -1 : ( ( b
> a
) ? 1 : 0 ) );
464 function multisort( table
, sortList
, cache
) {
468 for ( i
= 0; i
< sortList
.length
; i
++ ) {
469 sortFn
[ i
] = ( sortList
[ i
][ 1 ] ) ? sortTextDesc
: sortText
;
471 cache
.normalized
.sort( function ( array1
, array2
) {
473 for ( i
= 0; i
< sortList
.length
; i
++ ) {
474 col
= sortList
[ i
][ 0 ];
475 ret
= sortFn
[ i
].call( this, array1
[ col
], array2
[ col
] );
480 // Fall back to index number column to ensure stable sort
481 return sortText
.call( this, array1
[ array1
.length
- 1 ], array2
[ array2
.length
- 1 ] );
486 function buildTransformTable() {
487 var ascii
, localised
, i
, digitClass
,
488 digits
= '0123456789,.'.split( '' ),
489 separatorTransformTable
= mw
.config
.get( 'wgSeparatorTransformTable' ),
490 digitTransformTable
= mw
.config
.get( 'wgDigitTransformTable' );
492 if ( separatorTransformTable
=== null || ( separatorTransformTable
[ 0 ] === '' && digitTransformTable
[ 2 ] === '' ) ) {
493 ts
.transformTable
= false;
495 ts
.transformTable
= {};
497 // Unpack the transform table
498 ascii
= separatorTransformTable
[ 0 ].split( '\t' ).concat( digitTransformTable
[ 0 ].split( '\t' ) );
499 localised
= separatorTransformTable
[ 1 ].split( '\t' ).concat( digitTransformTable
[ 1 ].split( '\t' ) );
501 // Construct regexes for number identification
502 for ( i
= 0; i
< ascii
.length
; i
++ ) {
503 ts
.transformTable
[ localised
[ i
] ] = ascii
[ i
];
504 digits
.push( mw
.RegExp
.escape( localised
[ i
] ) );
507 digitClass
= '[' + digits
.join( '', digits
) + ']';
509 // We allow a trailing percent sign, which we just strip. This works fine
510 // if percents and regular numbers aren't being mixed.
511 ts
.numberRegex
= new RegExp( '^(' + '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
512 '|' + '[-+\u2212]?' + digitClass
+ '+[\\s\\xa0]*%?' + // Generic localised
516 function buildDateTable() {
522 for ( i
= 0; i
< 12; i
++ ) {
523 name
= mw
.language
.months
.names
[ i
].toLowerCase();
524 ts
.monthNames
[ name
] = i
+ 1;
525 regex
.push( mw
.RegExp
.escape( name
) );
526 name
= mw
.language
.months
.genitive
[ i
].toLowerCase();
527 ts
.monthNames
[ name
] = i
+ 1;
528 regex
.push( mw
.RegExp
.escape( name
) );
529 name
= mw
.language
.months
.abbrev
[ i
].toLowerCase().replace( '.', '' );
530 ts
.monthNames
[ name
] = i
+ 1;
531 regex
.push( mw
.RegExp
.escape( name
) );
534 // Build piped string
535 regex
= regex
.join( '|' );
538 // Any date formated with . , ' - or /
539 ts
.dateRegex
[ 0 ] = new RegExp( /^\s*(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{2,4})\s*?/i );
541 // Written Month name, dmy
542 ts
.dateRegex
[ 1 ] = new RegExp( '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
544 // Written Month name, mdy
545 ts
.dateRegex
[ 2 ] = new RegExp( '^\\s*(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
550 * Replace all rowspanned cells in the body with clones in each row, so sorting
551 * need not worry about them.
553 * @param {jQuery} $table jQuery object for a <table>
555 function explodeRowspans( $table
) {
556 var spanningRealCellIndex
, rowSpan
, colSpan
,
557 cell
, cellData
, i
, $tds
, $clone
, $nextRows
,
558 rowspanCells
= $table
.find( '> tbody > tr > [rowspan]' ).get();
561 if ( !rowspanCells
.length
) {
565 // First, we need to make a property like cellIndex but taking into
566 // account colspans. We also cache the rowIndex to avoid having to take
567 // cell.parentNode.rowIndex in the sorting function below.
568 $table
.find( '> tbody > tr' ).each( function () {
571 len
= this.cells
.length
;
572 for ( i
= 0; i
< len
; i
++ ) {
573 $( this.cells
[ i
] ).data( 'tablesorter', {
575 realRowIndex
: this.rowIndex
577 col
+= this.cells
[ i
].colSpan
;
581 // Split multi row cells into multiple cells with the same content.
582 // Sort by column then row index to avoid problems with odd table structures.
583 // Re-sort whenever a rowspanned cell's realCellIndex is changed, because it
584 // might change the sort order.
585 function resortCells() {
589 rowspanCells
= rowspanCells
.sort( function ( a
, b
) {
590 cellAData
= $.data( a
, 'tablesorter' );
591 cellBData
= $.data( b
, 'tablesorter' );
592 ret
= cellAData
.realCellIndex
- cellBData
.realCellIndex
;
594 ret
= cellAData
.realRowIndex
- cellBData
.realRowIndex
;
598 $.each( rowspanCells
, function () {
599 $.data( this, 'tablesorter' ).needResort
= false;
604 function filterfunc() {
605 return $.data( this, 'tablesorter' ).realCellIndex
>= spanningRealCellIndex
;
608 function fixTdCellIndex() {
609 $.data( this, 'tablesorter' ).realCellIndex
+= colSpan
;
610 if ( this.rowSpan
> 1 ) {
611 $.data( this, 'tablesorter' ).needResort
= true;
615 while ( rowspanCells
.length
) {
616 if ( $.data( rowspanCells
[ 0 ], 'tablesorter' ).needResort
) {
620 cell
= rowspanCells
.shift();
621 cellData
= $.data( cell
, 'tablesorter' );
622 rowSpan
= cell
.rowSpan
;
623 colSpan
= cell
.colSpan
;
624 spanningRealCellIndex
= cellData
.realCellIndex
;
626 $nextRows
= $( cell
).parent().nextAll();
627 for ( i
= 0; i
< rowSpan
- 1; i
++ ) {
628 $tds
= $( $nextRows
[ i
].cells
).filter( filterfunc
);
629 $clone
= $( cell
).clone();
630 $clone
.data( 'tablesorter', {
631 realCellIndex
: spanningRealCellIndex
,
632 realRowIndex
: cellData
.realRowIndex
+ i
,
636 $tds
.each( fixTdCellIndex
);
637 $tds
.first().before( $clone
);
639 $nextRows
.eq( i
).append( $clone
);
646 * Build index to handle colspanned cells in the body.
647 * Set the cell index for each column in an array,
648 * so that colspaned cells set multiple in this array.
649 * columnToCell[collumnIndex] point at the real cell in this row.
651 * @param {jQuery} $table object for a <table>
653 function manageColspans( $table
) {
655 $rows
= $table
.find( '> tbody > tr' ),
656 totalRows
= $rows
.length
|| 0,
657 config
= $table
.data( 'tablesorter' ).config
,
658 columns
= config
.columns
,
659 columnToCell
, cellsInRow
, index
;
661 for ( i
= 0; i
< totalRows
; i
++ ) {
663 $row
= $rows
.eq( i
);
664 // if this is a child row, continue to the next row (as buildCache())
665 if ( $row
.hasClass( config
.cssChildRow
) ) {
666 // go to the next for loop
671 cellsInRow
= ( $row
[ 0 ].cells
.length
) || 0; // all cells in this row
672 index
= 0; // real cell index in this row
673 for ( j
= 0; j
< columns
; index
++ ) {
674 if ( index
=== cellsInRow
) {
675 // Row with cells less than columns: add empty cell
676 $row
.append( '<td>' );
679 for ( k
= 0; k
< $row
[ 0 ].cells
[ index
].colSpan
; k
++ ) {
680 columnToCell
[ j
++ ] = index
;
684 $row
.data( 'columnToCell', columnToCell
);
688 function buildCollationTable() {
689 ts
.collationTable
= mw
.config
.get( 'tableSorterCollation' );
690 ts
.collationRegex
= null;
691 if ( ts
.collationTable
) {
695 // Build array of key names
696 for ( key
in ts
.collationTable
) {
697 // Check hasOwn to be safe
698 if ( ts
.collationTable
.hasOwnProperty( key
) ) {
703 ts
.collationRegex
= new RegExp( '[' + keys
.join( '' ) + ']', 'ig' );
708 function cacheRegexs() {
714 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/ )
717 new RegExp( /(^[£$€¥]|[£$€¥]$)/ ),
718 new RegExp( /[£$€¥]/g )
721 new RegExp( /^(https?|ftp|file):\/\/$/ ),
722 new RegExp( /(https?|ftp|file):\/\// )
725 new RegExp( /^([-+]?\d{1,4})-([01]\d)-([0-3]\d)([T\s]((([01]\d|2[0-3])(:?[0-5]\d)?|24:?00)?(:?([0-5]\d|60))?([.,]\d+)?)([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?/ ),
726 new RegExp( /^([-+]?\d{1,4})-([01]\d)-([0-3]\d)/ )
729 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)))$/ )
732 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/ )
738 * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
739 * structure [ [ Integer , Integer ], ... ]
741 * @param {Array} sortObjects List of sort objects.
742 * @return {Array} List of internal sort definitions.
744 function convertSortList( sortObjects
) {
746 $.each( sortObjects
, function ( i
, sortObject
) {
747 $.each( sortObject
, function ( columnIndex
, order
) {
748 var orderIndex
= ( order
=== 'desc' ) ? 1 : 0;
749 sortList
.push( [ parseInt( columnIndex
, 10 ), orderIndex
] );
759 cssHeader
: 'headerSort',
760 cssAsc
: 'headerSortUp',
761 cssDesc
: 'headerSortDown',
762 cssChildRow
: 'expand-child',
763 sortMultiSortKey
: 'shiftKey',
764 unsortableClass
: 'unsortable',
766 cancelSelection
: true,
778 * @param {jQuery} $tables
779 * @param {Object} [settings]
781 construct: function ( $tables
, settings
) {
782 return $tables
.each( function ( i
, table
) {
783 // Declare and cache.
784 var $headers
, cache
, config
, sortCSS
, sortMsg
,
789 if ( !table
.tBodies
) {
792 if ( !table
.tHead
) {
793 // No thead found. Look for rows with <th>s and
794 // move them into a <thead> tag or a <tfoot> tag
795 emulateTHeadAndFoot( $table
);
797 // Still no thead? Then quit
798 if ( !table
.tHead
) {
802 $table
.addClass( 'jquery-tablesorter' );
805 config
= $.extend( {}, $.tablesorter
.defaultOptions
, settings
);
807 // Save the settings where they read
808 $.data( table
, 'tablesorter', { config
: config
} );
810 // Get the CSS class names, could be done elsewhere
811 sortCSS
= [ config
.cssDesc
, config
.cssAsc
];
812 sortMsg
= [ mw
.msg( 'sort-descending' ), mw
.msg( 'sort-ascending' ) ];
815 $headers
= buildHeaders( table
, sortMsg
);
817 // Grab and process locale settings.
818 buildTransformTable();
821 // Precaching regexps can bring 10 fold
822 // performance improvements in some browsers.
825 function setupForFirstSort() {
828 // Defer buildCollationTable to first sort. As user and site scripts
829 // may customize tableSorterCollation but load after $.ready(), other
830 // scripts may call .tablesorter() before they have done the
831 // tableSorterCollation customizations.
832 buildCollationTable();
834 // Legacy fix of .sortbottoms
835 // Wrap them inside a tfoot (because that's what they actually want to be)
836 // and put the <tfoot> at the end of the <table>
838 $sortbottoms
= $table
.find( '> tbody > tr.sortbottom' );
839 if ( $sortbottoms
.length
) {
840 $tfoot
= $table
.children( 'tfoot' );
841 if ( $tfoot
.length
) {
842 $tfoot
.eq( 0 ).prepend( $sortbottoms
);
844 $table
.append( $( '<tfoot>' ).append( $sortbottoms
) );
848 explodeRowspans( $table
);
849 manageColspans( $table
);
851 // Try to auto detect column type, and store in tables config
852 config
.parsers
= buildParserCache( table
, $headers
);
855 // Apply event handling to headers
856 // this is too big, perhaps break it out?
857 $headers
.on( 'keypress click', function ( e
) {
858 var cell
, $cell
, columns
, newSortList
, i
,
862 if ( e
.type
=== 'click' && e
.target
.nodeName
.toLowerCase() === 'a' ) {
863 // The user clicked on a link inside a table header.
864 // Do nothing and let the default link click action continue.
868 if ( e
.type
=== 'keypress' && e
.which
!== 13 ) {
869 // Only handle keypresses on the "Enter" key.
877 // Build the cache for the tbody cells
878 // to share between calculations for this sort action.
879 // Re-calculated each time a sort action is performed due to possiblity
880 // that sort values change. Shouldn't be too expensive, but if it becomes
881 // too slow an event based system should be implemented somehow where
882 // cells get event .change() and bubbles up to the <table> here
883 cache
= buildCache( table
);
885 totalRows
= ( $table
[ 0 ].tBodies
[ 0 ] && $table
[ 0 ].tBodies
[ 0 ].rows
.length
) || 0;
886 if ( totalRows
> 0 ) {
890 // Get current column sort order
892 order
: $cell
.data( 'count' ) % 2,
893 count
: $cell
.data( 'count' ) + 1
897 // Get current column index
898 columns
= config
.headerToColumns
[ $cell
.data( 'headerIndex' ) ];
899 newSortList
= $.map( columns
, function ( c
) {
900 // jQuery "helpfully" flattens the arrays...
901 return [ [ c
, $cell
.data( 'order' ) ] ];
903 // Index of first column belonging to this header
906 if ( !e
[ config
.sortMultiSortKey
] ) {
907 // User only wants to sort on one column set
908 // Flush the sort list and add new columns
909 config
.sortList
= newSortList
;
911 // Multi column sorting
912 // It is not possible for one column to belong to multiple headers,
913 // so this is okay - we don't need to check for every value in the columns array
914 if ( isValueInArray( i
, config
.sortList
) ) {
915 // The user has clicked on an already sorted column.
916 // Reverse the sorting direction for all tables.
917 for ( j
= 0; j
< config
.sortList
.length
; j
++ ) {
918 s
= config
.sortList
[ j
];
919 o
= config
.headerList
[ config
.columnToHeader
[ s
[ 0 ] ] ];
920 if ( isValueInArray( s
[ 0 ], newSortList
) ) {
921 $( o
).data( 'count', s
[ 1 ] + 1 );
922 s
[ 1 ] = $( o
).data( 'count' ) % 2;
926 // Add columns to sort list array
927 config
.sortList
= config
.sortList
.concat( newSortList
);
931 // Reset order/counts of cells not affected by sorting
932 setHeadersOrder( $headers
, config
.sortList
, config
.headerToColumns
);
934 // Set CSS for headers
935 setHeadersCss( $table
[ 0 ], $headers
, config
.sortList
, sortCSS
, sortMsg
, config
.columnToHeader
);
937 $table
[ 0 ], multisort( $table
[ 0 ], config
.sortList
, cache
)
940 // Stop normal event by returning false
945 } ).mousedown( function () {
946 if ( config
.cancelSelection
) {
947 this.onselectstart = function () {
955 * Sorts the table. If no sorting is specified by passing a list of sort
956 * objects, the table is sorted according to the initial sorting order.
957 * Passing an empty array will reset sorting (basically just reset the headers
958 * making the table appear unsorted).
960 * @param {Array} [sortList] List of sort objects.
962 $table
.data( 'tablesorter' ).sort = function ( sortList
) {
968 if ( sortList
=== undefined ) {
969 sortList
= config
.sortList
;
970 } else if ( sortList
.length
> 0 ) {
971 sortList
= convertSortList( sortList
);
974 // Set each column's sort count to be able to determine the correct sort
975 // order when clicking on a header cell the next time
976 setHeadersOrder( $headers
, sortList
, config
.headerToColumns
);
978 // re-build the cache for the tbody cells
979 cache
= buildCache( table
);
981 // set css for headers
982 setHeadersCss( table
, $headers
, sortList
, sortCSS
, sortMsg
, config
.columnToHeader
);
984 // sort the table and append it to the dom
985 appendToTable( table
, multisort( table
, sortList
, cache
) );
989 if ( config
.sortList
.length
> 0 ) {
990 config
.sortList
= convertSortList( config
.sortList
);
991 $table
.data( 'tablesorter' ).sort();
997 addParser: function ( parser
) {
998 if ( !getParserById( parser
.id
) ) {
999 parsers
.push( parser
);
1003 formatDigit: function ( s
) {
1005 if ( ts
.transformTable
!== false ) {
1007 for ( p
= 0; p
< s
.length
; p
++ ) {
1009 if ( c
in ts
.transformTable
) {
1010 out
+= ts
.transformTable
[ c
];
1017 i
= parseFloat( s
.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
1018 return isNaN( i
) ? 0 : i
;
1021 formatFloat: function ( s
) {
1022 var i
= parseFloat( s
);
1023 return isNaN( i
) ? 0 : i
;
1026 formatInt: function ( s
) {
1027 var i
= parseInt( s
, 10 );
1028 return isNaN( i
) ? 0 : i
;
1031 clearTableBody: function ( table
) {
1032 $( table
.tBodies
[ 0 ] ).empty();
1035 getParser: function ( id
) {
1036 buildTransformTable();
1039 buildCollationTable();
1041 return getParserById( id
);
1044 getParsers: function () { // for table diagnosis
1052 // Register as jQuery prototype method
1053 $.fn
.tablesorter = function ( settings
) {
1054 return ts
.construct( this, settings
);
1057 // Add default parsers
1063 format: function ( s
) {
1064 s
= $.trim( s
.toLowerCase() );
1065 if ( ts
.collationRegex
) {
1066 var tsc
= ts
.collationTable
;
1067 s
= s
.replace( ts
.collationRegex
, function ( match
) {
1068 var r
= tsc
[ match
] ? tsc
[ match
] : tsc
[ match
.toUpperCase() ];
1069 return r
.toLowerCase();
1079 is: function ( s
) {
1080 return ts
.rgx
.IPAddress
[ 0 ].test( s
);
1082 format: function ( s
) {
1086 for ( i
= 0; i
< a
.length
; i
++ ) {
1088 if ( item
.length
=== 1 ) {
1090 } else if ( item
.length
=== 2 ) {
1096 return $.tablesorter
.formatFloat( r
);
1103 is: function ( s
) {
1104 return ts
.rgx
.currency
[ 0 ].test( s
);
1106 format: function ( s
) {
1107 return $.tablesorter
.formatDigit( s
.replace( ts
.rgx
.currency
[ 1 ], '' ) );
1114 is: function ( s
) {
1115 return ts
.rgx
.url
[ 0 ].test( s
);
1117 format: function ( s
) {
1118 return $.trim( s
.replace( ts
.rgx
.url
[ 1 ], '' ) );
1125 is: function ( s
) {
1126 return ts
.rgx
.isoDate
[ 0 ].test( s
);
1128 format: function ( s
) {
1129 var isodate
, matches
;
1130 if ( !Date
.prototype.toISOString
) {
1131 // Old browsers don't understand iso, Fallback to US date parsing and ignore the time part.
1132 matches
= $.trim( s
).match( ts
.rgx
.isoDate
[ 1 ] );
1134 return $.tablesorter
.formatFloat( 0 );
1136 isodate
= new Date( matches
[ 2 ] + '/' + matches
[ 3 ] + '/' + matches
[ 1 ] );
1138 matches
= s
.match( ts
.rgx
.isoDate
[ 0 ] );
1140 return $.tablesorter
.formatFloat( 0 );
1142 isodate
= new Date( $.trim( matches
[ 0 ] ) );
1144 return $.tablesorter
.formatFloat( ( isodate
!== undefined ) ? isodate
.getTime() : 0 );
1151 is: function ( s
) {
1152 return ts
.rgx
.usLongDate
[ 0 ].test( s
);
1154 format: function ( s
) {
1155 return $.tablesorter
.formatFloat( new Date( s
).getTime() );
1162 is: function ( s
) {
1163 return ( ts
.dateRegex
[ 0 ].test( s
) || ts
.dateRegex
[ 1 ].test( s
) || ts
.dateRegex
[ 2 ].test( s
) );
1165 format: function ( s
) {
1167 s
= $.trim( s
.toLowerCase() );
1169 if ( ( match
= s
.match( ts
.dateRegex
[ 0 ] ) ) !== null ) {
1170 if ( mw
.config
.get( 'wgDefaultDateFormat' ) === 'mdy' || mw
.config
.get( 'wgPageContentLanguage' ) === 'en' ) {
1171 s
= [ match
[ 3 ], match
[ 1 ], match
[ 2 ] ];
1172 } else if ( mw
.config
.get( 'wgDefaultDateFormat' ) === 'dmy' ) {
1173 s
= [ match
[ 3 ], match
[ 2 ], match
[ 1 ] ];
1175 // If we get here, we don't know which order the dd-dd-dddd
1176 // date is in. So return something not entirely invalid.
1179 } else if ( ( match
= s
.match( ts
.dateRegex
[ 1 ] ) ) !== null ) {
1180 s
= [ match
[ 3 ], String( ts
.monthNames
[ match
[ 2 ] ] ), match
[ 1 ] ];
1181 } else if ( ( match
= s
.match( ts
.dateRegex
[ 2 ] ) ) !== null ) {
1182 s
= [ match
[ 3 ], String( ts
.monthNames
[ match
[ 1 ] ] ), match
[ 2 ] ];
1184 // Should never get here
1188 // Pad Month and Day
1189 if ( s
[ 1 ].length
=== 1 ) {
1190 s
[ 1 ] = '0' + s
[ 1 ];
1192 if ( s
[ 2 ].length
=== 1 ) {
1193 s
[ 2 ] = '0' + s
[ 2 ];
1196 if ( ( y
= parseInt( s
[ 0 ], 10 ) ) < 100 ) {
1197 // Guestimate years without centuries
1204 while ( s
[ 0 ].length
< 4 ) {
1205 s
[ 0 ] = '0' + s
[ 0 ];
1207 return parseInt( s
.join( '' ), 10 );
1214 is: function ( s
) {
1215 return ts
.rgx
.time
[ 0 ].test( s
);
1217 format: function ( s
) {
1218 return $.tablesorter
.formatFloat( new Date( '2000/01/01 ' + s
).getTime() );
1225 is: function ( s
) {
1226 return $.tablesorter
.numberRegex
.test( $.trim( s
) );
1228 format: function ( s
) {
1229 return $.tablesorter
.formatDigit( s
);
1234 }( jQuery
, mediaWiki
) );