a5a17836016075310810c3da063939e6aa0d8484
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
50 /* Parser utility functions */
52 function getParserById( name
) {
54 for ( i
= 0; i
< parsers
.length
; i
++ ) {
55 if ( parsers
[ i
].id
.toLowerCase() === name
.toLowerCase() ) {
63 * @param {HTMLElement} node
66 function getElementSortKey( node
) {
67 var $node
= $( node
),
68 // Use data-sort-value attribute.
69 // Use data() instead of attr() so that live value changes
70 // are processed as well (T40152).
71 data
= $node
.data( 'sortValue' );
73 if ( data
!== null && data
!== undefined ) {
74 // Cast any numbers or other stuff to a string, methods
75 // like charAt, toLowerCase and split are expected.
76 return String( data
);
78 if ( node
.tagName
.toLowerCase() === 'img' ) {
79 return $node
.attr( 'alt' ) || ''; // handle undefined alt
81 return $.makeArray( node
.childNodes
).map( function ( elem
) {
82 if ( elem
.nodeType
=== Node
.ELEMENT_NODE
) {
83 if ( $( elem
).hasClass( 'reference' ) ) {
86 return getElementSortKey( elem
);
89 return $.text( elem
);
93 function detectParserForColumn( table
, rows
, column
) {
94 var l
= parsers
.length
,
95 config
= $( table
).data( 'tablesorter' ).config
,
99 // Start with 1 because 0 is the fallback parser
105 needed
= ( rows
.length
> 4 ) ? 5 : rows
.length
;
108 // if this is a child row, continue to the next row (as buildCache())
109 if ( rows
[ rowIndex
] && !$( rows
[ rowIndex
] ).hasClass( config
.cssChildRow
) ) {
110 if ( rowIndex
!== lastRowIndex
) {
111 lastRowIndex
= rowIndex
;
112 cellIndex
= $( rows
[ rowIndex
] ).data( 'columnToCell' )[ column
];
113 nodeValue
= getElementSortKey( rows
[ rowIndex
].cells
[ cellIndex
] ).trim();
119 if ( nodeValue
!== '' ) {
120 if ( parsers
[ i
].is( nodeValue
, table
) ) {
123 if ( concurrent
>= needed
) {
124 // Confirmed the parser for multiple cells, let's return it
127 } else if ( parsers
[ i
].id
.match( /isoDate/ ) && /^\D*(\d{1,4}) ?(\[.+\])?$/.test( nodeValue
) ) {
128 // For 1-4 digits and maybe reference(s) parser "isoDate" or "number" is possible, check next row
132 // Check next parser, reset rows
148 if ( rowIndex
>= rows
.length
) {
149 if ( concurrent
> 0 && concurrent
>= rows
.length
- empty
) {
150 // Confirmed the parser for all filled cells
153 // Check next parser, reset rows
162 // 0 is always the generic parser (text)
166 function buildParserCache( table
, $headers
) {
167 var sortType
, len
, j
, parser
,
168 rows
= table
.tBodies
[ 0 ].rows
,
169 config
= $( table
).data( 'tablesorter' ).config
,
173 len
= config
.columns
;
174 for ( j
= 0; j
< len
; j
++ ) {
176 sortType
= $headers
.eq( config
.columnToHeader
[ j
] ).data( 'sortType' );
177 if ( sortType
!== undefined ) {
178 parser
= getParserById( sortType
);
181 if ( parser
=== false ) {
182 parser
= detectParserForColumn( table
, rows
, j
);
185 parsers
.push( parser
);
191 /* Other utility functions */
193 function buildCache( table
) {
194 var i
, j
, $row
, cols
,
195 totalRows
= ( table
.tBodies
[ 0 ] && table
.tBodies
[ 0 ].rows
.length
) || 0,
196 config
= $( table
).data( 'tablesorter' ).config
,
197 parsers
= config
.parsers
,
198 len
= parsers
.length
,
205 for ( i
= 0; i
< totalRows
; i
++ ) {
207 // Add the table data to main data array
208 $row
= $( table
.tBodies
[ 0 ].rows
[ i
] );
211 // if this is a child row, add it to the last row's children and
212 // continue to the next row
213 if ( $row
.hasClass( config
.cssChildRow
) ) {
214 cache
.row
[ cache
.row
.length
- 1 ] = cache
.row
[ cache
.row
.length
- 1 ].add( $row
);
215 // go to the next for loop
219 cache
.row
.push( $row
);
221 for ( j
= 0; j
< len
; j
++ ) {
222 cellIndex
= $row
.data( 'columnToCell' )[ j
];
223 cols
.push( parsers
[ j
].format( getElementSortKey( $row
[ 0 ].cells
[ cellIndex
] ) ) );
226 cols
.push( cache
.normalized
.length
); // add position for rowCache
227 cache
.normalized
.push( cols
);
234 function appendToTable( table
, cache
) {
237 normalized
= cache
.normalized
,
238 totalRows
= normalized
.length
,
239 checkCell
= ( normalized
[ 0 ].length
- 1 ),
240 fragment
= document
.createDocumentFragment();
242 for ( i
= 0; i
< totalRows
; i
++ ) {
243 pos
= normalized
[ i
][ checkCell
];
245 l
= row
[ pos
].length
;
246 for ( j
= 0; j
< l
; j
++ ) {
247 fragment
.appendChild( row
[ pos
][ j
] );
251 table
.tBodies
[ 0 ].appendChild( fragment
);
253 $( table
).trigger( 'sortEnd.tablesorter' );
257 * Find all header rows in a thead-less table and put them in a <thead> tag.
258 * This only treats a row as a header row if it contains only <th>s (no <td>s)
259 * and if it is preceded entirely by header rows. The algorithm stops when
260 * it encounters the first non-header row.
262 * After this, it will look at all rows at the bottom for footer rows
263 * And place these in a tfoot using similar rules.
265 * @param {jQuery} $table object for a <table>
267 function emulateTHeadAndFoot( $table
) {
268 var $thead
, $tfoot
, i
, len
,
269 $rows
= $table
.find( '> tbody > tr' );
270 if ( !$table
.get( 0 ).tHead
) {
271 $thead
= $( '<thead>' );
272 $rows
.each( function () {
273 if ( $( this ).children( 'td' ).length
) {
274 // This row contains a <td>, so it's not a header row
278 $thead
.append( this );
280 $table
.find( ' > tbody:first' ).before( $thead
);
282 if ( !$table
.get( 0 ).tFoot
) {
283 $tfoot
= $( '<tfoot>' );
285 for ( i
= len
- 1; i
>= 0; i
-- ) {
286 if ( $( $rows
[ i
] ).children( 'td' ).length
) {
289 $tfoot
.prepend( $( $rows
[ i
] ) );
291 $table
.append( $tfoot
);
295 function uniqueElements( array
) {
297 array
.forEach( function ( elem
) {
298 if ( elem
!== undefined && uniques
.indexOf( elem
) === -1 ) {
299 uniques
.push( elem
);
305 function buildHeaders( table
, msg
) {
306 var config
= $( table
).data( 'tablesorter' ).config
,
318 $tableHeaders
= $( [] ),
319 $tableRows
= $( 'thead:eq(0) > tr', table
);
321 if ( $tableRows
.length
<= 1 ) {
322 $tableHeaders
= $tableRows
.children( 'th' );
326 // Loop through all the dom cells of the thead
327 $tableRows
.each( function ( rowIndex
, row
) {
328 // eslint-disable-next-line no-jquery/no-each-util
329 $.each( row
.cells
, function ( columnIndex
, cell
) {
333 rowspan
= Number( cell
.rowSpan
);
334 colspan
= Number( cell
.colSpan
);
336 // Skip the spots in the exploded matrix that are already filled
337 while ( exploded
[ rowIndex
] && exploded
[ rowIndex
][ columnIndex
] !== undefined ) {
341 // Find the actual dimensions of the thead, by placing each cell
342 // in the exploded matrix rowspan times colspan times, with the proper offsets
343 for ( matrixColumnIndex
= columnIndex
; matrixColumnIndex
< columnIndex
+ colspan
; ++matrixColumnIndex
) {
344 for ( matrixRowIndex
= rowIndex
; matrixRowIndex
< rowIndex
+ rowspan
; ++matrixRowIndex
) {
345 if ( !exploded
[ matrixRowIndex
] ) {
346 exploded
[ matrixRowIndex
] = [];
348 exploded
[ matrixRowIndex
][ matrixColumnIndex
] = cell
;
353 // We want to find the row that has the most columns (ignoring colspan)
354 exploded
.forEach( function ( cellArray
, index
) {
355 headerCount
= $( uniqueElements( cellArray
) ).filter( 'th' ).length
;
356 if ( headerCount
>= maxSeen
) {
357 maxSeen
= headerCount
;
361 // We cannot use $.unique() here because it sorts into dom order, which is undesirable
362 $tableHeaders
= $( uniqueElements( exploded
[ longestTR
] ) ).filter( 'th' );
365 // as each header can span over multiple columns (using colspan=N),
366 // we have to bidirectionally map headers to their columns and columns to their headers
367 config
.columnToHeader
= [];
368 config
.headerToColumns
= [];
369 config
.headerList
= [];
371 $tableHeaders
.each( function () {
375 if ( !$cell
.hasClass( config
.unsortableClass
) ) {
377 .addClass( config
.cssHeader
)
378 .prop( 'tabIndex', 0 )
380 role
: 'columnheader button',
384 for ( k
= 0; k
< this.colSpan
; k
++ ) {
385 config
.columnToHeader
[ colspanOffset
+ k
] = headerIndex
;
386 columns
.push( colspanOffset
+ k
);
389 config
.headerToColumns
[ headerIndex
] = columns
;
392 headerIndex
: headerIndex
,
397 // add only sortable cells to headerList
398 config
.headerList
[ headerIndex
] = this;
402 colspanOffset
+= this.colSpan
;
405 // number of columns with extended colspan, inclusive unsortable
406 // parsers[j], cache[][j], columnToHeader[j], columnToCell[j] have so many elements
407 config
.columns
= colspanOffset
;
409 return $tableHeaders
.not( '.' + config
.unsortableClass
);
412 function isValueInArray( v
, a
) {
414 for ( i
= 0; i
< a
.length
; i
++ ) {
415 if ( a
[ i
][ 0 ] === v
) {
423 * Sets the sort count of the columns that are not affected by the sorting to have them sorted
424 * in default (ascending) order when their header cell is clicked the next time.
426 * @param {jQuery} $headers
427 * @param {Array} sortList 2D number array
428 * @param {Array} headerToColumns 2D number array
430 function setHeadersOrder( $headers
, sortList
, headerToColumns
) {
431 // Loop through all headers to retrieve the indices of the columns the header spans across:
432 headerToColumns
.forEach( function ( columns
, headerIndex
) {
434 columns
.forEach( function ( columnIndex
, i
) {
436 header
= $headers
[ headerIndex
],
437 $header
= $( header
);
439 if ( !isValueInArray( columnIndex
, sortList
) ) {
440 // Column shall not be sorted: Reset header count and order.
446 // Column shall be sorted: Apply designated count and order.
447 for ( j
= 0; j
< sortList
.length
; j
++ ) {
448 sortColumn
= sortList
[ j
];
449 if ( sortColumn
[ 0 ] === i
) {
451 order
: sortColumn
[ 1 ],
452 count
: sortColumn
[ 1 ] + 1
463 function setHeadersCss( table
, $headers
, list
, css
, msg
, columnToHeader
) {
465 // Remove all header information and reset titles to default message
466 $headers
.removeClass( css
).attr( 'title', msg
[ 1 ] );
468 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
470 .eq( columnToHeader
[ list
[ i
][ 0 ] ] )
471 .addClass( css
[ list
[ i
][ 1 ] ] )
472 .attr( 'title', msg
[ list
[ i
][ 1 ] ] );
476 function sortText( a
, b
) {
477 return ( ( a
< b
) ? -1 : ( ( a
> b
) ? 1 : 0 ) );
480 function sortTextDesc( a
, b
) {
481 return ( ( b
< a
) ? -1 : ( ( b
> a
) ? 1 : 0 ) );
484 function multisort( table
, sortList
, cache
) {
488 for ( i
= 0; i
< sortList
.length
; i
++ ) {
489 sortFn
[ i
] = ( sortList
[ i
][ 1 ] ) ? sortTextDesc
: sortText
;
491 cache
.normalized
.sort( function ( array1
, array2
) {
493 for ( i
= 0; i
< sortList
.length
; i
++ ) {
494 col
= sortList
[ i
][ 0 ];
495 ret
= sortFn
[ i
].call( this, array1
[ col
], array2
[ col
] );
500 // Fall back to index number column to ensure stable sort
501 return sortText
.call( this, array1
[ array1
.length
- 1 ], array2
[ array2
.length
- 1 ] );
506 function buildTransformTable() {
507 var ascii
, localised
, i
, digitClass
,
508 digits
= '0123456789,.'.split( '' ),
509 separatorTransformTable
= mw
.config
.get( 'wgSeparatorTransformTable' ),
510 digitTransformTable
= mw
.config
.get( 'wgDigitTransformTable' );
512 if ( separatorTransformTable
=== null || ( separatorTransformTable
[ 0 ] === '' && digitTransformTable
[ 2 ] === '' ) ) {
513 ts
.transformTable
= false;
515 ts
.transformTable
= {};
517 // Unpack the transform table
518 ascii
= separatorTransformTable
[ 0 ].split( '\t' ).concat( digitTransformTable
[ 0 ].split( '\t' ) );
519 localised
= separatorTransformTable
[ 1 ].split( '\t' ).concat( digitTransformTable
[ 1 ].split( '\t' ) );
521 // Construct regexes for number identification
522 for ( i
= 0; i
< ascii
.length
; i
++ ) {
523 ts
.transformTable
[ localised
[ i
] ] = ascii
[ i
];
524 digits
.push( mw
.RegExp
.escape( localised
[ i
] ) );
527 digitClass
= '[' + digits
.join( '', digits
) + ']';
529 // We allow a trailing percent sign, which we just strip. This works fine
530 // if percents and regular numbers aren't being mixed.
531 ts
.numberRegex
= new RegExp(
533 '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
535 '[-+\u2212]?' + digitClass
+ '+[\\s\\xa0]*%?' + // Generic localised
541 function buildDateTable() {
547 for ( i
= 0; i
< 12; i
++ ) {
548 name
= mw
.language
.months
.names
[ i
].toLowerCase();
549 ts
.monthNames
[ name
] = i
+ 1;
550 regex
.push( mw
.RegExp
.escape( name
) );
551 name
= mw
.language
.months
.genitive
[ i
].toLowerCase();
552 ts
.monthNames
[ name
] = i
+ 1;
553 regex
.push( mw
.RegExp
.escape( name
) );
554 name
= mw
.language
.months
.abbrev
[ i
].toLowerCase().replace( '.', '' );
555 ts
.monthNames
[ name
] = i
+ 1;
556 regex
.push( mw
.RegExp
.escape( name
) );
559 // Build piped string
560 regex
= regex
.join( '|' );
563 // Any date formated with . , ' - or /
564 ts
.dateRegex
[ 0 ] = new RegExp( /^\s*(\d{1,2})[,.\-/'\s]{1,2}(\d{1,2})[,.\-/'\s
]{1,2}(\d
{2,4})\s
*?/i
);
566 // Written Month name, dmy
567 ts
.dateRegex
[ 1 ] = new RegExp(
568 '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(' +
571 '[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$',
575 // Written Month name, mdy
576 ts
.dateRegex
[ 2 ] = new RegExp(
577 '^\\s*(' + regex
+ ')' +
578 '[\\,\\.\\-\\/\'\\s]+(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$',
585 * Replace all rowspanned cells in the body with clones in each row, so sorting
586 * need not worry about them.
588 * @param {jQuery} $table jQuery object for a <table>
590 function explodeRowspans( $table
) {
591 var spanningRealCellIndex
, rowSpan
, colSpan
,
592 cell
, cellData
, i
, $tds
, $clone
, $nextRows
,
593 rowspanCells
= $table
.find( '> tbody > tr > [rowspan]' ).get();
596 if ( !rowspanCells
.length
) {
600 // First, we need to make a property like cellIndex but taking into
601 // account colspans. We also cache the rowIndex to avoid having to take
602 // cell.parentNode.rowIndex in the sorting function below.
603 $table
.find( '> tbody > tr' ).each( function () {
606 len
= this.cells
.length
;
607 for ( i
= 0; i
< len
; i
++ ) {
608 $( this.cells
[ i
] ).data( 'tablesorter', {
610 realRowIndex
: this.rowIndex
612 col
+= this.cells
[ i
].colSpan
;
616 // Split multi row cells into multiple cells with the same content.
617 // Sort by column then row index to avoid problems with odd table structures.
618 // Re-sort whenever a rowspanned cell's realCellIndex is changed, because it
619 // might change the sort order.
620 function resortCells() {
624 rowspanCells
= rowspanCells
.sort( function ( a
, b
) {
625 cellAData
= $.data( a
, 'tablesorter' );
626 cellBData
= $.data( b
, 'tablesorter' );
627 ret
= cellAData
.realCellIndex
- cellBData
.realCellIndex
;
629 ret
= cellAData
.realRowIndex
- cellBData
.realRowIndex
;
633 rowspanCells
.forEach( function ( cell
) {
634 $.data( cell
, 'tablesorter' ).needResort
= false;
639 function filterfunc() {
640 return $.data( this, 'tablesorter' ).realCellIndex
>= spanningRealCellIndex
;
643 function fixTdCellIndex() {
644 $.data( this, 'tablesorter' ).realCellIndex
+= colSpan
;
645 if ( this.rowSpan
> 1 ) {
646 $.data( this, 'tablesorter' ).needResort
= true;
650 while ( rowspanCells
.length
) {
651 if ( $.data( rowspanCells
[ 0 ], 'tablesorter' ).needResort
) {
655 cell
= rowspanCells
.shift();
656 cellData
= $.data( cell
, 'tablesorter' );
657 rowSpan
= cell
.rowSpan
;
658 colSpan
= cell
.colSpan
;
659 spanningRealCellIndex
= cellData
.realCellIndex
;
661 $nextRows
= $( cell
).parent().nextAll();
662 for ( i
= 0; i
< rowSpan
- 1; i
++ ) {
663 $tds
= $( $nextRows
[ i
].cells
).filter( filterfunc
);
664 $clone
= $( cell
).clone();
665 $clone
.data( 'tablesorter', {
666 realCellIndex
: spanningRealCellIndex
,
667 realRowIndex
: cellData
.realRowIndex
+ i
,
671 $tds
.each( fixTdCellIndex
);
672 $tds
.first().before( $clone
);
674 $nextRows
.eq( i
).append( $clone
);
681 * Build index to handle colspanned cells in the body.
682 * Set the cell index for each column in an array,
683 * so that colspaned cells set multiple in this array.
684 * columnToCell[collumnIndex] point at the real cell in this row.
686 * @param {jQuery} $table object for a <table>
688 function manageColspans( $table
) {
690 $rows
= $table
.find( '> tbody > tr' ),
691 totalRows
= $rows
.length
|| 0,
692 config
= $table
.data( 'tablesorter' ).config
,
693 columns
= config
.columns
,
694 columnToCell
, cellsInRow
, index
;
696 for ( i
= 0; i
< totalRows
; i
++ ) {
698 $row
= $rows
.eq( i
);
699 // if this is a child row, continue to the next row (as buildCache())
700 if ( $row
.hasClass( config
.cssChildRow
) ) {
701 // go to the next for loop
706 cellsInRow
= ( $row
[ 0 ].cells
.length
) || 0; // all cells in this row
707 index
= 0; // real cell index in this row
708 for ( j
= 0; j
< columns
; index
++ ) {
709 if ( index
=== cellsInRow
) {
710 // Row with cells less than columns: add empty cell
711 $row
.append( '<td>' );
714 for ( k
= 0; k
< $row
[ 0 ].cells
[ index
].colSpan
; k
++ ) {
715 columnToCell
[ j
++ ] = index
;
719 $row
.data( 'columnToCell', columnToCell
);
723 function buildCollationTable() {
725 ts
.collationTable
= mw
.config
.get( 'tableSorterCollation' );
726 ts
.collationRegex
= null;
727 if ( ts
.collationTable
) {
728 // Build array of key names
729 for ( key
in ts
.collationTable
) {
730 keys
.push( mw
.RegExp
.escape( key
) );
733 ts
.collationRegex
= new RegExp( keys
.join( '|' ), 'ig' );
738 function cacheRegexs() {
744 new RegExp( /^\d{1,3}[.]\d{1,3}[.]\d{1,3}[.]\d{1,3}$/ )
747 new RegExp( /(^[£$€¥]|[£$€¥]$)/ ),
748 new RegExp( /[£$€¥]/g )
751 new RegExp( /^(https?|ftp|file):\/\/$/ ),
752 new RegExp( /(https?|ftp|file):\/\// )
755 new RegExp( /^[^-\d]*(-?\d{1,4})-(0\d|1[0-2])(-([0-3]\d))?([T\s]([01]\d|2[0-4]):?(([0-5]\d):?(([0-5]\d|60)([.,]\d{1,3})?)?)?([zZ]|([-+])([01]\d|2[0-3]):?([0-5]\d)?)?)?/ ),
756 new RegExp( /^[^-\d]*(-?\d{1,4})-?(\d\d)?(-?(\d\d))?([T\s](\d\d):?((\d\d)?:?((\d\d)?([.,]\d{1,3})?)?)?([zZ]|([-+])(\d\d):?(\d\d)?)?)?/ )
759 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)))$/ )
762 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/ )
768 * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
769 * structure [ [ Integer, Integer ], ... ]
771 * @param {Array} sortObjects List of sort objects.
772 * @return {Array} List of internal sort definitions.
774 function convertSortList( sortObjects
) {
776 sortObjects
.forEach( function ( sortObject
) {
777 // eslint-disable-next-line no-jquery/no-each-util
778 $.each( sortObject
, function ( columnIndex
, order
) {
779 var orderIndex
= ( order
=== 'desc' ) ? 1 : 0;
780 sortList
.push( [ parseInt( columnIndex
, 10 ), orderIndex
] );
790 cssHeader
: 'headerSort',
791 cssAsc
: 'headerSortUp',
792 cssDesc
: 'headerSortDown',
793 cssChildRow
: 'expand-child',
794 sortMultiSortKey
: 'shiftKey',
795 unsortableClass
: 'unsortable',
797 cancelSelection
: true,
809 * @param {jQuery} $tables
810 * @param {Object} [settings]
813 construct: function ( $tables
, settings
) {
814 return $tables
.each( function ( i
, table
) {
815 // Declare and cache.
816 var $headers
, cache
, config
, sortCSS
, sortMsg
,
821 if ( !table
.tBodies
) {
824 if ( !table
.tHead
) {
825 // No thead found. Look for rows with <th>s and
826 // move them into a <thead> tag or a <tfoot> tag
827 emulateTHeadAndFoot( $table
);
829 // Still no thead? Then quit
830 if ( !table
.tHead
) {
834 // The `sortable` class is used to identify tables which will become sortable
835 // If not used it will create a FOUC but it should be added since the sortable class
836 // is responsible for certain crucial style elements. If the class is already present
837 // this action will be harmless.
838 $table
.addClass( 'jquery-tablesorter sortable' );
841 config
= $.extend( {}, $.tablesorter
.defaultOptions
, settings
);
843 // Save the settings where they read
844 $.data( table
, 'tablesorter', { config
: config
} );
846 // Get the CSS class names, could be done elsewhere
847 sortCSS
= [ config
.cssAsc
, config
.cssDesc
];
848 // Messages tell the user what the *next* state will be
849 // so are in reverse order to the CSS classes.
850 sortMsg
= [ mw
.msg( 'sort-descending' ), mw
.msg( 'sort-ascending' ) ];
853 $headers
= buildHeaders( table
, sortMsg
);
855 // Grab and process locale settings.
856 buildTransformTable();
859 // Precaching regexps can bring 10 fold
860 // performance improvements in some browsers.
863 function setupForFirstSort() {
864 var $tfoot
, $sortbottoms
;
868 // Defer buildCollationTable to first sort. As user and site scripts
869 // may customize tableSorterCollation but load after $.ready(), other
870 // scripts may call .tablesorter() before they have done the
871 // tableSorterCollation customizations.
872 buildCollationTable();
874 // Legacy fix of .sortbottoms
875 // Wrap them inside a tfoot (because that's what they actually want to be)
876 // and put the <tfoot> at the end of the <table>
877 $sortbottoms
= $table
.find( '> tbody > tr.sortbottom' );
878 if ( $sortbottoms
.length
) {
879 $tfoot
= $table
.children( 'tfoot' );
880 if ( $tfoot
.length
) {
881 $tfoot
.eq( 0 ).prepend( $sortbottoms
);
883 $table
.append( $( '<tfoot>' ).append( $sortbottoms
) );
887 explodeRowspans( $table
);
888 manageColspans( $table
);
890 // Try to auto detect column type, and store in tables config
891 config
.parsers
= buildParserCache( table
, $headers
);
894 // Apply event handling to headers
895 // this is too big, perhaps break it out?
896 $headers
.on( 'keypress click', function ( e
) {
897 var cell
, $cell
, columns
, newSortList
, i
,
901 if ( e
.type
=== 'click' && e
.target
.nodeName
.toLowerCase() === 'a' ) {
902 // The user clicked on a link inside a table header.
903 // Do nothing and let the default link click action continue.
907 if ( e
.type
=== 'keypress' && e
.which
!== 13 ) {
908 // Only handle keypresses on the "Enter" key.
916 // Build the cache for the tbody cells
917 // to share between calculations for this sort action.
918 // Re-calculated each time a sort action is performed due to possibility
919 // that sort values change. Shouldn't be too expensive, but if it becomes
920 // too slow an event based system should be implemented somehow where
921 // cells get event .change() and bubbles up to the <table> here
922 cache
= buildCache( table
);
924 totalRows
= ( $table
[ 0 ].tBodies
[ 0 ] && $table
[ 0 ].tBodies
[ 0 ].rows
.length
) || 0;
925 if ( totalRows
> 0 ) {
929 // Get current column sort order
931 order
: $cell
.data( 'count' ) % 2,
932 count
: $cell
.data( 'count' ) + 1
936 // Get current column index
937 columns
= config
.headerToColumns
[ $cell
.data( 'headerIndex' ) ];
938 newSortList
= columns
.map( function ( c
) {
939 return [ c
, $cell
.data( 'order' ) ];
941 // Index of first column belonging to this header
944 if ( !e
[ config
.sortMultiSortKey
] ) {
945 // User only wants to sort on one column set
946 // Flush the sort list and add new columns
947 config
.sortList
= newSortList
;
949 // Multi column sorting
950 // It is not possible for one column to belong to multiple headers,
951 // so this is okay - we don't need to check for every value in the columns array
952 if ( isValueInArray( i
, config
.sortList
) ) {
953 // The user has clicked on an already sorted column.
954 // Reverse the sorting direction for all tables.
955 for ( j
= 0; j
< config
.sortList
.length
; j
++ ) {
956 s
= config
.sortList
[ j
];
957 o
= config
.headerList
[ config
.columnToHeader
[ s
[ 0 ] ] ];
958 if ( isValueInArray( s
[ 0 ], newSortList
) ) {
959 $( o
).data( 'count', s
[ 1 ] + 1 );
960 s
[ 1 ] = $( o
).data( 'count' ) % 2;
964 // Add columns to sort list array
965 config
.sortList
= config
.sortList
.concat( newSortList
);
969 // Reset order/counts of cells not affected by sorting
970 setHeadersOrder( $headers
, config
.sortList
, config
.headerToColumns
);
972 // Set CSS for headers
973 setHeadersCss( $table
[ 0 ], $headers
, config
.sortList
, sortCSS
, sortMsg
, config
.columnToHeader
);
975 $table
[ 0 ], multisort( $table
[ 0 ], config
.sortList
, cache
)
978 // Stop normal event by returning false
983 } ).on( 'mousedown', function () {
984 if ( config
.cancelSelection
) {
985 this.onselectstart = function () {
993 * Sorts the table. If no sorting is specified by passing a list of sort
994 * objects, the table is sorted according to the initial sorting order.
995 * Passing an empty array will reset sorting (basically just reset the headers
996 * making the table appear unsorted).
998 * @param {Array} [sortList] List of sort objects.
1000 $table
.data( 'tablesorter' ).sort = function ( sortList
) {
1003 setupForFirstSort();
1006 if ( sortList
=== undefined ) {
1007 sortList
= config
.sortList
;
1008 } else if ( sortList
.length
> 0 ) {
1009 sortList
= convertSortList( sortList
);
1012 // Set each column's sort count to be able to determine the correct sort
1013 // order when clicking on a header cell the next time
1014 setHeadersOrder( $headers
, sortList
, config
.headerToColumns
);
1016 // re-build the cache for the tbody cells
1017 cache
= buildCache( table
);
1019 // set css for headers
1020 setHeadersCss( table
, $headers
, sortList
, sortCSS
, sortMsg
, config
.columnToHeader
);
1022 // sort the table and append it to the dom
1023 appendToTable( table
, multisort( table
, sortList
, cache
) );
1027 if ( config
.sortList
.length
> 0 ) {
1028 config
.sortList
= convertSortList( config
.sortList
);
1029 $table
.data( 'tablesorter' ).sort();
1035 addParser: function ( parser
) {
1036 if ( !getParserById( parser
.id
) ) {
1037 parsers
.push( parser
);
1041 formatDigit: function ( s
) {
1043 if ( ts
.transformTable
!== false ) {
1045 for ( p
= 0; p
< s
.length
; p
++ ) {
1047 if ( c
in ts
.transformTable
) {
1048 out
+= ts
.transformTable
[ c
];
1055 i
= parseFloat( s
.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
1056 return isNaN( i
) ? -Infinity
: i
;
1059 formatFloat: function ( s
) {
1060 var i
= parseFloat( s
);
1061 return isNaN( i
) ? -Infinity
: i
;
1064 formatInt: function ( s
) {
1065 var i
= parseInt( s
, 10 );
1066 return isNaN( i
) ? -Infinity
: i
;
1069 clearTableBody: function ( table
) {
1070 $( table
.tBodies
[ 0 ] ).empty();
1073 getParser: function ( id
) {
1074 buildTransformTable();
1077 buildCollationTable();
1079 return getParserById( id
);
1082 getParsers: function () { // for table diagnosis
1090 // Register as jQuery prototype method
1091 $.fn
.tablesorter = function ( settings
) {
1092 return ts
.construct( this, settings
);
1095 // Add default parsers
1101 format: function ( s
) {
1103 s
= s
.toLowerCase().trim();
1104 if ( ts
.collationRegex
) {
1105 tsc
= ts
.collationTable
;
1106 s
= s
.replace( ts
.collationRegex
, function ( match
) {
1107 var r
= tsc
[ match
] ? tsc
[ match
] : tsc
[ match
.toUpperCase() ];
1108 return r
.toLowerCase();
1118 is: function ( s
) {
1119 return ts
.rgx
.IPAddress
[ 0 ].test( s
);
1121 format: function ( s
) {
1125 for ( i
= 0; i
< a
.length
; i
++ ) {
1127 if ( item
.length
=== 1 ) {
1129 } else if ( item
.length
=== 2 ) {
1135 return $.tablesorter
.formatFloat( r
);
1142 is: function ( s
) {
1143 return ts
.rgx
.currency
[ 0 ].test( s
);
1145 format: function ( s
) {
1146 return $.tablesorter
.formatDigit( s
.replace( ts
.rgx
.currency
[ 1 ], '' ) );
1153 is: function ( s
) {
1154 return ts
.rgx
.url
[ 0 ].test( s
);
1156 format: function ( s
) {
1157 return s
.replace( ts
.rgx
.url
[ 1 ], '' ).trim();
1164 is: function ( s
) {
1165 return ts
.rgx
.isoDate
[ 0 ].test( s
);
1167 format: function ( s
) {
1168 var match
, i
, isodate
, ms
, hOffset
, mOffset
;
1169 match
= s
.match( ts
.rgx
.isoDate
[ 0 ] );
1170 if ( match
=== null ) {
1171 // Otherwise a signed number with 1-4 digit is parsed as isoDate
1172 match
= s
.match( ts
.rgx
.isoDate
[ 1 ] );
1178 for ( i
= 2; i
<= 4; i
+= 2 ) {
1179 if ( !match
[ i
] || match
[ i
].length
=== 0 ) {
1184 for ( i
= 6; i
<= 15; i
++ ) {
1185 if ( !match
[ i
] || match
[ i
].length
=== 0 ) {
1189 ms
= parseFloat( match
[ 11 ].replace( /,/, '.' ) ) * 1000;
1190 hOffset
= $.tablesorter
.formatInt( match
[ 13 ] + match
[ 14 ] );
1191 mOffset
= $.tablesorter
.formatInt( match
[ 13 ] + match
[ 15 ] );
1193 isodate
= new Date( 0 );
1194 // Because Date constructor changes year 0-99 to 1900-1999, use setUTCFullYear()
1195 isodate
.setUTCFullYear( match
[ 1 ], match
[ 2 ] - 1, match
[ 4 ] );
1196 isodate
.setUTCHours( match
[ 6 ] - hOffset
, match
[ 8 ] - mOffset
, match
[ 10 ], ms
);
1197 return isodate
.getTime();
1204 is: function ( s
) {
1205 return ts
.rgx
.usLongDate
[ 0 ].test( s
);
1207 format: function ( s
) {
1208 return $.tablesorter
.formatFloat( new Date( s
).getTime() );
1215 is: function ( s
) {
1216 return ( ts
.dateRegex
[ 0 ].test( s
) || ts
.dateRegex
[ 1 ].test( s
) || ts
.dateRegex
[ 2 ].test( s
) );
1218 format: function ( s
) {
1220 s
= s
.toLowerCase().trim();
1222 if ( ( match
= s
.match( ts
.dateRegex
[ 0 ] ) ) !== null ) {
1223 if ( mw
.config
.get( 'wgDefaultDateFormat' ) === 'mdy' || mw
.config
.get( 'wgPageContentLanguage' ) === 'en' ) {
1224 s
= [ match
[ 3 ], match
[ 1 ], match
[ 2 ] ];
1225 } else if ( mw
.config
.get( 'wgDefaultDateFormat' ) === 'dmy' ) {
1226 s
= [ match
[ 3 ], match
[ 2 ], match
[ 1 ] ];
1228 // If we get here, we don't know which order the dd-dd-dddd
1229 // date is in. So return something not entirely invalid.
1232 } else if ( ( match
= s
.match( ts
.dateRegex
[ 1 ] ) ) !== null ) {
1233 s
= [ match
[ 3 ], String( ts
.monthNames
[ match
[ 2 ] ] ), match
[ 1 ] ];
1234 } else if ( ( match
= s
.match( ts
.dateRegex
[ 2 ] ) ) !== null ) {
1235 s
= [ match
[ 3 ], String( ts
.monthNames
[ match
[ 1 ] ] ), match
[ 2 ] ];
1237 // Should never get here
1241 // Pad Month and Day
1242 if ( s
[ 1 ].length
=== 1 ) {
1243 s
[ 1 ] = '0' + s
[ 1 ];
1245 if ( s
[ 2 ].length
=== 1 ) {
1246 s
[ 2 ] = '0' + s
[ 2 ];
1249 if ( ( y
= parseInt( s
[ 0 ], 10 ) ) < 100 ) {
1250 // Guestimate years without centuries
1257 while ( s
[ 0 ].length
< 4 ) {
1258 s
[ 0 ] = '0' + s
[ 0 ];
1260 return parseInt( s
.join( '' ), 10 );
1267 is: function ( s
) {
1268 return ts
.rgx
.time
[ 0 ].test( s
);
1270 format: function ( s
) {
1271 return $.tablesorter
.formatFloat( new Date( '2000/01/01 ' + s
).getTime() );
1278 is: function ( s
) {
1279 return $.tablesorter
.numberRegex
.test( s
.trim() );
1281 format: function ( s
) {
1282 return $.tablesorter
.formatDigit( s
);