f6857e850f1f39e8e099a84326999fcbbb8cf3d1
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
, column
) {
109 var l
= parsers
.length
,
112 // Start with 1 because 0 is the fallback parser
118 needed
= ( rows
.length
> 4 ) ? 5 : rows
.length
;
121 if ( rows
[ rowIndex
] ) {
122 if ( rowIndex
!== lastRowIndex
) {
123 lastRowIndex
= rowIndex
;
124 cellIndex
= $( rows
[ rowIndex
] ).data( 'columnToCell' )[ column
];
125 nodeValue
= $.trim( getElementSortKey( rows
[ rowIndex
].cells
[ cellIndex
] ) );
131 if ( nodeValue
!== '' ) {
132 if ( parsers
[ i
].is( nodeValue
, table
) ) {
135 if ( concurrent
>= needed
) {
136 // Confirmed the parser for multiple cells, let's return it
140 // Check next parser, reset rows
150 if ( rowIndex
>= rows
.length
) {
151 if ( concurrent
>= rows
.length
- empty
) {
152 // Confirmed the parser for all filled cells
155 // Check next parser, reset rows
164 // 0 is always the generic parser (text)
168 function buildParserCache( table
, $headers
) {
169 var sortType
, len
, j
, parser
,
170 rows
= table
.tBodies
[ 0 ].rows
,
171 config
= $( table
).data( 'tablesorter' ).config
,
175 len
= config
.columns
;
176 for ( j
= 0; j
< len
; j
++ ) {
178 sortType
= $headers
.eq( config
.columnToHeader
[ j
] ).data( 'sortType' );
179 if ( sortType
!== undefined ) {
180 parser
= getParserById( sortType
);
183 if ( parser
=== false ) {
184 parser
= detectParserForColumn( table
, rows
, j
);
187 parsers
.push( parser
);
193 /* Other utility functions */
195 function buildCache( table
) {
196 var i
, j
, $row
, cols
,
197 totalRows
= ( table
.tBodies
[ 0 ] && table
.tBodies
[ 0 ].rows
.length
) || 0,
198 config
= $( table
).data( 'tablesorter' ).config
,
199 parsers
= config
.parsers
,
200 len
= parsers
.length
,
207 for ( i
= 0; i
< totalRows
; i
++ ) {
209 // Add the table data to main data array
210 $row
= $( table
.tBodies
[ 0 ].rows
[ i
] );
213 // if this is a child row, add it to the last row's children and
214 // continue to the next row
215 if ( $row
.hasClass( config
.cssChildRow
) ) {
216 cache
.row
[ cache
.row
.length
- 1 ] = cache
.row
[ cache
.row
.length
- 1 ].add( $row
);
217 // go to the next for loop
221 cache
.row
.push( $row
);
223 for ( j
= 0; j
< len
; j
++ ) {
224 cellIndex
= $row
.data( 'columnToCell' )[ j
];
225 cols
.push( parsers
[ j
].format( getElementSortKey( $row
[ 0 ].cells
[ cellIndex
] ) ) );
228 cols
.push( cache
.normalized
.length
); // add position for rowCache
229 cache
.normalized
.push( cols
);
236 function appendToTable( table
, cache
) {
239 normalized
= cache
.normalized
,
240 totalRows
= normalized
.length
,
241 checkCell
= ( normalized
[ 0 ].length
- 1 ),
242 fragment
= document
.createDocumentFragment();
244 for ( i
= 0; i
< totalRows
; i
++ ) {
245 pos
= normalized
[ i
][ checkCell
];
247 l
= row
[ pos
].length
;
249 for ( j
= 0; j
< l
; j
++ ) {
250 fragment
.appendChild( row
[ pos
][ j
] );
254 table
.tBodies
[ 0 ].appendChild( fragment
);
256 $( table
).trigger( 'sortEnd.tablesorter' );
260 * Find all header rows in a thead-less table and put them in a <thead> tag.
261 * This only treats a row as a header row if it contains only <th>s (no <td>s)
262 * and if it is preceded entirely by header rows. The algorithm stops when
263 * it encounters the first non-header row.
265 * After this, it will look at all rows at the bottom for footer rows
266 * And place these in a tfoot using similar rules.
268 * @param {jQuery} $table object for a <table>
270 function emulateTHeadAndFoot( $table
) {
271 var $thead
, $tfoot
, i
, len
,
272 $rows
= $table
.find( '> tbody > tr' );
273 if ( !$table
.get( 0 ).tHead
) {
274 $thead
= $( '<thead>' );
275 $rows
.each( function () {
276 if ( $( this ).children( 'td' ).length
) {
277 // This row contains a <td>, so it's not a header row
281 $thead
.append( this );
283 $table
.find( ' > tbody:first' ).before( $thead
);
285 if ( !$table
.get( 0 ).tFoot
) {
286 $tfoot
= $( '<tfoot>' );
288 for ( i
= len
- 1; i
>= 0; i
-- ) {
289 if ( $( $rows
[ i
] ).children( 'td' ).length
) {
292 $tfoot
.prepend( $( $rows
[ i
] ) );
294 $table
.append( $tfoot
);
298 function uniqueElements( array
) {
300 $.each( array
, function ( index
, elem
) {
301 if ( elem
!== undefined && $.inArray( elem
, uniques
) === -1 ) {
302 uniques
.push( elem
);
308 function buildHeaders( table
, msg
) {
309 var config
= $( table
).data( 'tablesorter' ).config
,
321 $tableHeaders
= $( [] ),
322 $tableRows
= $( 'thead:eq(0) > tr', table
);
323 if ( $tableRows
.length
<= 1 ) {
324 $tableHeaders
= $tableRows
.children( 'th' );
328 // Loop through all the dom cells of the thead
329 $tableRows
.each( function ( rowIndex
, row
) {
330 $.each( row
.cells
, function ( columnIndex
, cell
) {
334 rowspan
= Number( cell
.rowSpan
);
335 colspan
= Number( cell
.colSpan
);
337 // Skip the spots in the exploded matrix that are already filled
338 while ( exploded
[ rowIndex
] && exploded
[ rowIndex
][ columnIndex
] !== undefined ) {
342 // Find the actual dimensions of the thead, by placing each cell
343 // in the exploded matrix rowspan times colspan times, with the proper offsets
344 for ( matrixColumnIndex
= columnIndex
; matrixColumnIndex
< columnIndex
+ colspan
; ++matrixColumnIndex
) {
345 for ( matrixRowIndex
= rowIndex
; matrixRowIndex
< rowIndex
+ rowspan
; ++matrixRowIndex
) {
346 if ( !exploded
[ matrixRowIndex
] ) {
347 exploded
[ matrixRowIndex
] = [];
349 exploded
[ matrixRowIndex
][ matrixColumnIndex
] = cell
;
354 // We want to find the row that has the most columns (ignoring colspan)
355 $.each( exploded
, function ( index
, cellArray
) {
356 headerCount
= $( uniqueElements( cellArray
) ).filter( 'th' ).length
;
357 if ( headerCount
>= maxSeen
) {
358 maxSeen
= headerCount
;
362 // We cannot use $.unique() here because it sorts into dom order, which is undesirable
363 $tableHeaders
= $( uniqueElements( exploded
[ longestTR
] ) ).filter( 'th' );
366 // as each header can span over multiple columns (using colspan=N),
367 // we have to bidirectionally map headers to their columns and columns to their headers
368 config
.columnToHeader
= [];
369 config
.headerToColumns
= [];
370 config
.headerList
= [];
372 $tableHeaders
.each( function () {
376 if ( !$cell
.hasClass( config
.unsortableClass
) ) {
378 .addClass( config
.cssHeader
)
379 .prop( 'tabIndex', 0 )
381 role
: 'columnheader button',
385 for ( k
= 0; k
< this.colSpan
; k
++ ) {
386 config
.columnToHeader
[ colspanOffset
+ k
] = headerIndex
;
387 columns
.push( colspanOffset
+ k
);
390 config
.headerToColumns
[ headerIndex
] = columns
;
393 headerIndex
: headerIndex
,
398 // add only sortable cells to headerList
399 config
.headerList
[ headerIndex
] = this;
403 colspanOffset
+= this.colSpan
;
406 // number of columns with extended colspan, inclusive unsortable
407 // parsers[j], cache[][j], columnToHeader[j], columnToCell[j] have so many elements
408 config
.columns
= colspanOffset
;
410 return $tableHeaders
.not( '.' + config
.unsortableClass
);
413 function isValueInArray( v
, a
) {
416 for ( i
= 0; i
< len
; i
++ ) {
417 if ( a
[ i
][ 0 ] === v
) {
425 * Sets the sort count of the columns that are not affected by the sorting to have them sorted
426 * in default (ascending) order when their header cell is clicked the next time.
428 * @param {jQuery} $headers
429 * @param {Number[][]} sortList
430 * @param {Number[][]} headerToColumns
432 function setHeadersOrder( $headers
, sortList
, headerToColumns
) {
433 // Loop through all headers to retrieve the indices of the columns the header spans across:
434 $.each( headerToColumns
, function ( headerIndex
, columns
) {
436 $.each( columns
, function ( i
, columnIndex
) {
437 var header
= $headers
[ headerIndex
],
438 $header
= $( header
);
440 if ( !isValueInArray( columnIndex
, sortList
) ) {
441 // Column shall not be sorted: Reset header count and order.
447 // Column shall be sorted: Apply designated count and order.
448 $.each( sortList
, function ( j
, sortColumn
) {
449 if ( sortColumn
[ 0 ] === i
) {
451 order
: sortColumn
[ 1 ],
452 count
: sortColumn
[ 1 ] + 1
463 function setHeadersCss( table
, $headers
, list
, css
, msg
, columnToHeader
) {
464 // Remove all header information and reset titles to default message
465 $headers
.removeClass( css
[ 0 ] ).removeClass( css
[ 1 ] ).attr( 'title', msg
[ 1 ] );
467 for ( var i
= 0; i
< list
.length
; i
++ ) {
468 $headers
.eq( columnToHeader
[ list
[ i
][ 0 ] ] )
469 .addClass( css
[ list
[ i
][ 1 ] ] )
470 .attr( 'title', msg
[ list
[ i
][ 1 ] ] );
474 function sortText( a
, b
) {
475 return ( ( a
< b
) ? -1 : ( ( a
> b
) ? 1 : 0 ) );
478 function sortTextDesc( a
, b
) {
479 return ( ( b
< a
) ? -1 : ( ( b
> a
) ? 1 : 0 ) );
482 function multisort( table
, sortList
, cache
) {
485 len
= sortList
.length
;
486 for ( i
= 0; i
< len
; i
++ ) {
487 sortFn
[ i
] = ( sortList
[ i
][ 1 ] ) ? sortTextDesc
: sortText
;
489 cache
.normalized
.sort( function ( array1
, array2
) {
491 for ( i
= 0; i
< len
; i
++ ) {
492 col
= sortList
[ i
][ 0 ];
493 ret
= sortFn
[ i
].call( this, array1
[ col
], array2
[ col
] );
498 // Fall back to index number column to ensure stable sort
499 return sortText
.call( this, array1
[ array1
.length
- 1 ], array2
[ array2
.length
- 1 ] );
504 function buildTransformTable() {
505 var ascii
, localised
, i
, digitClass
,
506 digits
= '0123456789,.'.split( '' ),
507 separatorTransformTable
= mw
.config
.get( 'wgSeparatorTransformTable' ),
508 digitTransformTable
= mw
.config
.get( 'wgDigitTransformTable' );
510 if ( separatorTransformTable
=== null || ( separatorTransformTable
[ 0 ] === '' && digitTransformTable
[ 2 ] === '' ) ) {
511 ts
.transformTable
= false;
513 ts
.transformTable
= {};
515 // Unpack the transform table
516 ascii
= separatorTransformTable
[ 0 ].split( '\t' ).concat( digitTransformTable
[ 0 ].split( '\t' ) );
517 localised
= separatorTransformTable
[ 1 ].split( '\t' ).concat( digitTransformTable
[ 1 ].split( '\t' ) );
519 // Construct regex for number identification
520 for ( i
= 0; i
< ascii
.length
; i
++ ) {
521 ts
.transformTable
[ localised
[ i
] ] = ascii
[ i
];
522 digits
.push( mw
.RegExp
.escape( localised
[ i
] ) );
525 digitClass
= '[' + digits
.join( '', digits
) + ']';
527 // We allow a trailing percent sign, which we just strip. This works fine
528 // if percents and regular numbers aren't being mixed.
529 ts
.numberRegex
= new RegExp( '^(' + '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
530 '|' + '[-+\u2212]?' + digitClass
+ '+[\\s\\xa0]*%?' + // Generic localised
534 function buildDateTable() {
540 for ( i
= 0; i
< 12; i
++ ) {
541 name
= mw
.language
.months
.names
[ i
].toLowerCase();
542 ts
.monthNames
[ name
] = i
+ 1;
543 regex
.push( mw
.RegExp
.escape( name
) );
544 name
= mw
.language
.months
.genitive
[ i
].toLowerCase();
545 ts
.monthNames
[ name
] = i
+ 1;
546 regex
.push( mw
.RegExp
.escape( name
) );
547 name
= mw
.language
.months
.abbrev
[ i
].toLowerCase().replace( '.', '' );
548 ts
.monthNames
[ name
] = i
+ 1;
549 regex
.push( mw
.RegExp
.escape( name
) );
552 // Build piped string
553 regex
= regex
.join( '|' );
556 // Any date formated with . , ' - or /
557 ts
.dateRegex
[ 0 ] = new RegExp( /^\s*(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{2,4})\s*?/i );
559 // Written Month name, dmy
560 ts
.dateRegex
[ 1 ] = new RegExp( '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
562 // Written Month name, mdy
563 ts
.dateRegex
[ 2 ] = new RegExp( '^\\s*(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
568 * Replace all rowspanned cells in the body with clones in each row, so sorting
569 * need not worry about them.
571 * @param {jQuery} $table jQuery object for a <table>
573 function explodeRowspans( $table
) {
574 var spanningRealCellIndex
, rowSpan
, colSpan
,
575 cell
, cellData
, i
, $tds
, $clone
, $nextRows
,
576 rowspanCells
= $table
.find( '> tbody > tr > [rowspan]' ).get();
579 if ( !rowspanCells
.length
) {
583 // First, we need to make a property like cellIndex but taking into
584 // account colspans. We also cache the rowIndex to avoid having to take
585 // cell.parentNode.rowIndex in the sorting function below.
586 $table
.find( '> tbody > tr' ).each( function () {
589 l
= this.cells
.length
;
590 for ( i
= 0; i
< l
; i
++ ) {
591 $( this.cells
[ i
] ).data( 'tablesorter', {
593 realRowIndex
: this.rowIndex
595 col
+= this.cells
[ i
].colSpan
;
599 // Split multi row cells into multiple cells with the same content.
600 // Sort by column then row index to avoid problems with odd table structures.
601 // Re-sort whenever a rowspanned cell's realCellIndex is changed, because it
602 // might change the sort order.
603 function resortCells() {
607 rowspanCells
= rowspanCells
.sort( function ( a
, b
) {
608 cellAData
= $.data( a
, 'tablesorter' );
609 cellBData
= $.data( b
, 'tablesorter' );
610 ret
= cellAData
.realCellIndex
- cellBData
.realCellIndex
;
612 ret
= cellAData
.realRowIndex
- cellBData
.realRowIndex
;
616 $.each( rowspanCells
, function () {
617 $.data( this, 'tablesorter' ).needResort
= false;
622 function filterfunc() {
623 return $.data( this, 'tablesorter' ).realCellIndex
>= spanningRealCellIndex
;
626 function fixTdCellIndex() {
627 $.data( this, 'tablesorter' ).realCellIndex
+= colSpan
;
628 if ( this.rowSpan
> 1 ) {
629 $.data( this, 'tablesorter' ).needResort
= true;
633 while ( rowspanCells
.length
) {
634 if ( $.data( rowspanCells
[ 0 ], 'tablesorter' ).needResort
) {
638 cell
= rowspanCells
.shift();
639 cellData
= $.data( cell
, 'tablesorter' );
640 rowSpan
= cell
.rowSpan
;
641 colSpan
= cell
.colSpan
;
642 spanningRealCellIndex
= cellData
.realCellIndex
;
644 $nextRows
= $( cell
).parent().nextAll();
645 for ( i
= 0; i
< rowSpan
- 1; i
++ ) {
646 $tds
= $( $nextRows
[ i
].cells
).filter( filterfunc
);
647 $clone
= $( cell
).clone();
648 $clone
.data( 'tablesorter', {
649 realCellIndex
: spanningRealCellIndex
,
650 realRowIndex
: cellData
.realRowIndex
+ i
,
654 $tds
.each( fixTdCellIndex
);
655 $tds
.first().before( $clone
);
657 $nextRows
.eq( i
).append( $clone
);
664 * Build index to handle colspanned cells in the body.
665 * Set the cell index for each column in an array,
666 * so that colspaned cells set multiple in this array.
667 * columnToCell[collumnIndex] point at the real cell in this row.
669 * @param {jQuery} $table object for a <table>
671 function manageColspans( $table
) {
673 $rows
= $table
.find( '> tbody > tr' ),
674 totalRows
= $rows
.length
|| 0,
675 config
= $table
.data( 'tablesorter' ).config
,
676 columns
= config
.columns
,
677 columnToCell
, cellsInRow
, index
;
679 for ( i
= 0; i
< totalRows
; i
++ ) {
681 $row
= $rows
.eq( i
);
682 // if this is a child row, continue to the next row (as buildCache())
683 if ( $row
.hasClass( config
.cssChildRow
) ) {
684 // go to the next for loop
689 cellsInRow
= ( $row
[ 0 ].cells
.length
) || 0; // all cells in this row
690 index
= 0; // real cell index in this row
691 for ( j
= 0; j
< columns
; index
++ ) {
692 if ( index
=== cellsInRow
) {
693 // Row with cells less than columns: add empty cell
694 $row
.append( '<td>' );
697 for ( k
= 0; k
< $row
[ 0 ].cells
[ index
].colSpan
; k
++ ) {
698 columnToCell
[ j
++ ] = index
;
702 $row
.data( 'columnToCell', columnToCell
);
706 function buildCollationTable() {
707 ts
.collationTable
= mw
.config
.get( 'tableSorterCollation' );
708 ts
.collationRegex
= null;
709 if ( ts
.collationTable
) {
713 // Build array of key names
714 for ( key
in ts
.collationTable
) {
715 // Check hasOwn to be safe
716 if ( ts
.collationTable
.hasOwnProperty( key
) ) {
721 ts
.collationRegex
= new RegExp( '[' + keys
.join( '' ) + ']', 'ig' );
726 function cacheRegexs() {
732 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/ )
735 new RegExp( /(^[£$€¥]|[£$€¥]$)/ ),
736 new RegExp( /[£$€¥]/g )
739 new RegExp( /^(https?|ftp|file):\/\/$/ ),
740 new RegExp( /(https?|ftp|file):\/\// )
743 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))?([.,]\d+)?)([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?/ ),
744 new RegExp( /^([-+]?\d{1,4})-([01]\d)-([0-3]\d)/ )
747 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)))$/ )
750 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/ )
756 * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
757 * structure [ [ Integer , Integer ], ... ]
759 * @param sortObjects {Array} List of sort objects.
760 * @return {Array} List of internal sort definitions.
763 function convertSortList( sortObjects
) {
765 $.each( sortObjects
, function ( i
, sortObject
) {
766 $.each( sortObject
, function ( columnIndex
, order
) {
767 var orderIndex
= ( order
=== 'desc' ) ? 1 : 0;
768 sortList
.push( [ parseInt( columnIndex
, 10 ), orderIndex
] );
778 cssHeader
: 'headerSort',
779 cssAsc
: 'headerSortUp',
780 cssDesc
: 'headerSortDown',
781 cssChildRow
: 'expand-child',
782 sortMultiSortKey
: 'shiftKey',
783 unsortableClass
: 'unsortable',
785 cancelSelection
: true,
797 * @param {jQuery} $tables
798 * @param {Object} [settings]
800 construct: function ( $tables
, settings
) {
801 return $tables
.each( function ( i
, table
) {
802 // Declare and cache.
803 var $headers
, cache
, config
, sortCSS
, sortMsg
,
808 if ( !table
.tBodies
) {
811 if ( !table
.tHead
) {
812 // No thead found. Look for rows with <th>s and
813 // move them into a <thead> tag or a <tfoot> tag
814 emulateTHeadAndFoot( $table
);
816 // Still no thead? Then quit
817 if ( !table
.tHead
) {
821 $table
.addClass( 'jquery-tablesorter' );
824 config
= $.extend( {}, $.tablesorter
.defaultOptions
, settings
);
826 // Save the settings where they read
827 $.data( table
, 'tablesorter', { config
: config
} );
829 // Get the CSS class names, could be done elsewhere
830 sortCSS
= [ config
.cssDesc
, config
.cssAsc
];
831 sortMsg
= [ mw
.msg( 'sort-descending' ), mw
.msg( 'sort-ascending' ) ];
834 $headers
= buildHeaders( table
, sortMsg
);
836 // Grab and process locale settings.
837 buildTransformTable();
840 // Precaching regexps can bring 10 fold
841 // performance improvements in some browsers.
844 function setupForFirstSort() {
847 // Defer buildCollationTable to first sort. As user and site scripts
848 // may customize tableSorterCollation but load after $.ready(), other
849 // scripts may call .tablesorter() before they have done the
850 // tableSorterCollation customizations.
851 buildCollationTable();
853 // Legacy fix of .sortbottoms
854 // Wrap them inside a tfoot (because that's what they actually want to be)
855 // and put the <tfoot> at the end of the <table>
857 $sortbottoms
= $table
.find( '> tbody > tr.sortbottom' );
858 if ( $sortbottoms
.length
) {
859 $tfoot
= $table
.children( 'tfoot' );
860 if ( $tfoot
.length
) {
861 $tfoot
.eq( 0 ).prepend( $sortbottoms
);
863 $table
.append( $( '<tfoot>' ).append( $sortbottoms
) );
867 explodeRowspans( $table
);
868 manageColspans( $table
);
870 // Try to auto detect column type, and store in tables config
871 config
.parsers
= buildParserCache( table
, $headers
);
874 // Apply event handling to headers
875 // this is too big, perhaps break it out?
876 $headers
.on( 'keypress click', function ( e
) {
877 var cell
, $cell
, columns
, newSortList
, i
,
881 if ( e
.type
=== 'click' && e
.target
.nodeName
.toLowerCase() === 'a' ) {
882 // The user clicked on a link inside a table header.
883 // Do nothing and let the default link click action continue.
887 if ( e
.type
=== 'keypress' && e
.which
!== 13 ) {
888 // Only handle keypresses on the "Enter" key.
896 // Build the cache for the tbody cells
897 // to share between calculations for this sort action.
898 // Re-calculated each time a sort action is performed due to possiblity
899 // that sort values change. Shouldn't be too expensive, but if it becomes
900 // too slow an event based system should be implemented somehow where
901 // cells get event .change() and bubbles up to the <table> here
902 cache
= buildCache( table
);
904 totalRows
= ( $table
[ 0 ].tBodies
[ 0 ] && $table
[ 0 ].tBodies
[ 0 ].rows
.length
) || 0;
905 if ( totalRows
> 0 ) {
909 // Get current column sort order
911 order
: $cell
.data( 'count' ) % 2,
912 count
: $cell
.data( 'count' ) + 1
916 // Get current column index
917 columns
= config
.headerToColumns
[ $cell
.data( 'headerIndex' ) ];
918 newSortList
= $.map( columns
, function ( c
) {
919 // jQuery "helpfully" flattens the arrays...
920 return [ [ c
, $cell
.data( 'order' ) ] ];
922 // Index of first column belonging to this header
925 if ( !e
[ config
.sortMultiSortKey
] ) {
926 // User only wants to sort on one column set
927 // Flush the sort list and add new columns
928 config
.sortList
= newSortList
;
930 // Multi column sorting
931 // It is not possible for one column to belong to multiple headers,
932 // so this is okay - we don't need to check for every value in the columns array
933 if ( isValueInArray( i
, config
.sortList
) ) {
934 // The user has clicked on an already sorted column.
935 // Reverse the sorting direction for all tables.
936 for ( j
= 0; j
< config
.sortList
.length
; j
++ ) {
937 s
= config
.sortList
[ j
];
938 o
= config
.headerList
[ config
.columnToHeader
[ s
[ 0 ] ] ];
939 if ( isValueInArray( s
[ 0 ], newSortList
) ) {
940 $( o
).data( 'count', s
[ 1 ] + 1 );
941 s
[ 1 ] = $( o
).data( 'count' ) % 2;
945 // Add columns to sort list array
946 config
.sortList
= config
.sortList
.concat( newSortList
);
950 // Reset order/counts of cells not affected by sorting
951 setHeadersOrder( $headers
, config
.sortList
, config
.headerToColumns
);
953 // Set CSS for headers
954 setHeadersCss( $table
[ 0 ], $headers
, config
.sortList
, sortCSS
, sortMsg
, config
.columnToHeader
);
956 $table
[ 0 ], multisort( $table
[ 0 ], config
.sortList
, cache
)
959 // Stop normal event by returning false
964 } ).mousedown( function () {
965 if ( config
.cancelSelection
) {
966 this.onselectstart = function () {
974 * Sorts the table. If no sorting is specified by passing a list of sort
975 * objects, the table is sorted according to the initial sorting order.
976 * Passing an empty array will reset sorting (basically just reset the headers
977 * making the table appear unsorted).
979 * @param {Array} [sortList] List of sort objects.
981 $table
.data( 'tablesorter' ).sort = function ( sortList
) {
987 if ( sortList
=== undefined ) {
988 sortList
= config
.sortList
;
989 } else if ( sortList
.length
> 0 ) {
990 sortList
= convertSortList( sortList
);
993 // Set each column's sort count to be able to determine the correct sort
994 // order when clicking on a header cell the next time
995 setHeadersOrder( $headers
, sortList
, config
.headerToColumns
);
997 // re-build the cache for the tbody cells
998 cache
= buildCache( table
);
1000 // set css for headers
1001 setHeadersCss( table
, $headers
, sortList
, sortCSS
, sortMsg
, config
.columnToHeader
);
1003 // sort the table and append it to the dom
1004 appendToTable( table
, multisort( table
, sortList
, cache
) );
1008 if ( config
.sortList
.length
> 0 ) {
1009 config
.sortList
= convertSortList( config
.sortList
);
1010 $table
.data( 'tablesorter' ).sort();
1016 addParser: function ( parser
) {
1018 len
= parsers
.length
,
1020 for ( i
= 0; i
< len
; i
++ ) {
1021 if ( parsers
[ i
].id
.toLowerCase() === parser
.id
.toLowerCase() ) {
1026 parsers
.push( parser
);
1030 formatDigit: function ( s
) {
1032 if ( ts
.transformTable
!== false ) {
1034 for ( p
= 0; p
< s
.length
; p
++ ) {
1036 if ( c
in ts
.transformTable
) {
1037 out
+= ts
.transformTable
[ c
];
1044 i
= parseFloat( s
.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
1045 return isNaN( i
) ? 0 : i
;
1048 formatFloat: function ( s
) {
1049 var i
= parseFloat( s
);
1050 return isNaN( i
) ? 0 : i
;
1053 formatInt: function ( s
) {
1054 var i
= parseInt( s
, 10 );
1055 return isNaN( i
) ? 0 : i
;
1058 clearTableBody: function ( table
) {
1059 $( table
.tBodies
[ 0 ] ).empty();
1062 getParser: function ( id
) {
1063 buildTransformTable();
1066 buildCollationTable();
1068 return getParserById( id
);
1071 getParsers: function () { // for table diagnosis
1079 // Register as jQuery prototype method
1080 $.fn
.tablesorter = function ( settings
) {
1081 return ts
.construct( this, settings
);
1084 // Add default parsers
1090 format: function ( s
) {
1091 s
= $.trim( s
.toLowerCase() );
1092 if ( ts
.collationRegex
) {
1093 var tsc
= ts
.collationTable
;
1094 s
= s
.replace( ts
.collationRegex
, function ( match
) {
1095 var r
= tsc
[ match
] ? tsc
[ match
] : tsc
[ match
.toUpperCase() ];
1096 return r
.toLowerCase();
1106 is: function ( s
) {
1107 return ts
.rgx
.IPAddress
[ 0 ].test( s
);
1109 format: function ( s
) {
1114 for ( i
= 0; i
< len
; i
++ ) {
1116 if ( item
.length
=== 1 ) {
1118 } else if ( item
.length
=== 2 ) {
1124 return $.tablesorter
.formatFloat( r
);
1131 is: function ( s
) {
1132 return ts
.rgx
.currency
[ 0 ].test( s
);
1134 format: function ( s
) {
1135 return $.tablesorter
.formatDigit( s
.replace( ts
.rgx
.currency
[ 1 ], '' ) );
1142 is: function ( s
) {
1143 return ts
.rgx
.url
[ 0 ].test( s
);
1145 format: function ( s
) {
1146 return $.trim( s
.replace( ts
.rgx
.url
[ 1 ], '' ) );
1153 is: function ( s
) {
1154 return ts
.rgx
.isoDate
[ 0 ].test( s
);
1156 format: function ( s
) {
1159 if ( !Date
.prototype.toISOString
) {
1160 // Old browsers don't understand iso, Fallback to US date parsing and ignore the time part.
1161 matches
= $.trim( s
).match( ts
.rgx
.isoDate
[ 1 ] );
1163 isodate
= new Date( matches
[ 2 ] + '/' + matches
[ 3 ] + '/' + matches
[ 1 ] );
1165 return $.tablesorter
.formatFloat( 0 );
1168 isodate
= new Date( $.trim( s
) );
1170 return $.tablesorter
.formatFloat( ( isodate
!== undefined ) ? isodate
.getTime() : 0 );
1177 is: function ( s
) {
1178 return ts
.rgx
.usLongDate
[ 0 ].test( s
);
1180 format: function ( s
) {
1181 return $.tablesorter
.formatFloat( new Date( s
).getTime() );
1188 is: function ( s
) {
1189 return ( ts
.dateRegex
[ 0 ].test( s
) || ts
.dateRegex
[ 1 ].test( s
) || ts
.dateRegex
[ 2 ].test( s
) );
1191 format: function ( s
) {
1193 s
= $.trim( s
.toLowerCase() );
1195 if ( ( match
= s
.match( ts
.dateRegex
[ 0 ] ) ) !== null ) {
1196 if ( mw
.config
.get( 'wgDefaultDateFormat' ) === 'mdy' || mw
.config
.get( 'wgPageContentLanguage' ) === 'en' ) {
1197 s
= [ match
[ 3 ], match
[ 1 ], match
[ 2 ] ];
1198 } else if ( mw
.config
.get( 'wgDefaultDateFormat' ) === 'dmy' ) {
1199 s
= [ match
[ 3 ], match
[ 2 ], match
[ 1 ] ];
1201 // If we get here, we don't know which order the dd-dd-dddd
1202 // date is in. So return something not entirely invalid.
1205 } else if ( ( match
= s
.match( ts
.dateRegex
[ 1 ] ) ) !== null ) {
1206 s
= [ match
[ 3 ], String( ts
.monthNames
[ match
[ 2 ] ] ), match
[ 1 ] ];
1207 } else if ( ( match
= s
.match( ts
.dateRegex
[ 2 ] ) ) !== null ) {
1208 s
= [ match
[ 3 ], String( ts
.monthNames
[ match
[ 1 ] ] ), match
[ 2 ] ];
1210 // Should never get here
1214 // Pad Month and Day
1215 if ( s
[ 1 ].length
=== 1 ) {
1216 s
[ 1 ] = '0' + s
[ 1 ];
1218 if ( s
[ 2 ].length
=== 1 ) {
1219 s
[ 2 ] = '0' + s
[ 2 ];
1222 if ( ( y
= parseInt( s
[ 0 ], 10 ) ) < 100 ) {
1223 // Guestimate years without centuries
1230 while ( s
[ 0 ].length
< 4 ) {
1231 s
[ 0 ] = '0' + s
[ 0 ];
1233 return parseInt( s
.join( '' ), 10 );
1240 is: function ( s
) {
1241 return ts
.rgx
.time
[ 0 ].test( s
);
1243 format: function ( s
) {
1244 return $.tablesorter
.formatFloat( new Date( '2000/01/01 ' + s
).getTime() );
1251 is: function ( s
) {
1252 return $.tablesorter
.numberRegex
.test( $.trim( s
) );
1254 format: function ( s
) {
1255 return $.tablesorter
.formatDigit( s
);
1260 }( jQuery
, mediaWiki
) );