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 // Get data-sort-value attribute. Uses jQuery to allow live value
68 // changes from other code paths via data(), which reside only in jQuery.
69 // Must use $().data() instead of $.data(), as the latter *only*
70 // accesses the live values, without reading HTML5 attribs first (T40152).
71 var 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' ) {
81 // Iterate the NodeList (not an array).
82 // Also uses null-return as filter in the same pass.
83 // eslint-disable-next-line no-jquery/no-map-util
84 return $.map( node
.childNodes
, function ( elem
) {
85 if ( elem
.nodeType
=== Node
.ELEMENT_NODE
) {
86 if ( $( elem
).hasClass( 'reference' ) ) {
89 return getElementSortKey( elem
);
91 if ( elem
.nodeType
=== Node
.TEXT_NODE
) {
92 return elem
.textContent
;
94 // Ignore other node types, such as HTML comments.
99 function detectParserForColumn( table
, rows
, column
) {
100 var l
= parsers
.length
,
101 config
= $( table
).data( 'tablesorter' ).config
,
105 // Start with 1 because 0 is the fallback parser
111 needed
= ( rows
.length
> 4 ) ? 5 : rows
.length
;
114 // if this is a child row, continue to the next row (as buildCache())
115 if ( rows
[ rowIndex
] && !$( rows
[ rowIndex
] ).hasClass( config
.cssChildRow
) ) {
116 if ( rowIndex
!== lastRowIndex
) {
117 lastRowIndex
= rowIndex
;
118 cellIndex
= $( rows
[ rowIndex
] ).data( 'columnToCell' )[ column
];
119 nodeValue
= getElementSortKey( rows
[ rowIndex
].cells
[ cellIndex
] ).trim();
125 if ( nodeValue
!== '' ) {
126 if ( parsers
[ i
].is( nodeValue
, table
) ) {
129 if ( concurrent
>= needed
) {
130 // Confirmed the parser for multiple cells, let's return it
133 } else if ( parsers
[ i
].id
.match( /isoDate/ ) && /^\D*(\d{1,4}) ?(\[.+\])?$/.test( nodeValue
) ) {
134 // For 1-4 digits and maybe reference(s) parser "isoDate" or "number" is possible, check next row
138 // Check next parser, reset rows
154 if ( rowIndex
>= rows
.length
) {
155 if ( concurrent
> 0 && concurrent
>= rows
.length
- empty
) {
156 // Confirmed the parser for all filled cells
159 // Check next parser, reset rows
168 // 0 is always the generic parser (text)
172 function buildParserCache( table
, $headers
) {
173 var sortType
, len
, j
, parser
,
174 rows
= table
.tBodies
[ 0 ].rows
,
175 config
= $( table
).data( 'tablesorter' ).config
,
179 len
= config
.columns
;
180 for ( j
= 0; j
< len
; j
++ ) {
182 sortType
= $headers
.eq( config
.columnToHeader
[ j
] ).data( 'sortType' );
183 if ( sortType
!== undefined ) {
184 parser
= getParserById( sortType
);
187 if ( parser
=== false ) {
188 parser
= detectParserForColumn( table
, rows
, j
);
191 parsers
.push( parser
);
197 /* Other utility functions */
199 function buildCache( table
) {
200 var i
, j
, $row
, cols
,
201 totalRows
= ( table
.tBodies
[ 0 ] && table
.tBodies
[ 0 ].rows
.length
) || 0,
202 config
= $( table
).data( 'tablesorter' ).config
,
203 parsers
= config
.parsers
,
204 len
= parsers
.length
,
211 for ( i
= 0; i
< totalRows
; i
++ ) {
213 // Add the table data to main data array
214 $row
= $( table
.tBodies
[ 0 ].rows
[ i
] );
217 // if this is a child row, add it to the last row's children and
218 // continue to the next row
219 if ( $row
.hasClass( config
.cssChildRow
) ) {
220 cache
.row
[ cache
.row
.length
- 1 ] = cache
.row
[ cache
.row
.length
- 1 ].add( $row
);
221 // go to the next for loop
225 cache
.row
.push( $row
);
227 for ( j
= 0; j
< len
; j
++ ) {
228 cellIndex
= $row
.data( 'columnToCell' )[ j
];
229 cols
.push( parsers
[ j
].format( getElementSortKey( $row
[ 0 ].cells
[ cellIndex
] ) ) );
232 cols
.push( cache
.normalized
.length
); // add position for rowCache
233 cache
.normalized
.push( cols
);
240 function appendToTable( table
, cache
) {
243 normalized
= cache
.normalized
,
244 totalRows
= normalized
.length
,
245 checkCell
= ( normalized
[ 0 ].length
- 1 ),
246 fragment
= document
.createDocumentFragment();
248 for ( i
= 0; i
< totalRows
; i
++ ) {
249 pos
= normalized
[ i
][ checkCell
];
251 l
= row
[ pos
].length
;
252 for ( j
= 0; j
< l
; j
++ ) {
253 fragment
.appendChild( row
[ pos
][ j
] );
257 table
.tBodies
[ 0 ].appendChild( fragment
);
259 $( table
).trigger( 'sortEnd.tablesorter' );
263 * Find all header rows in a thead-less table and put them in a <thead> tag.
264 * This only treats a row as a header row if it contains only <th>s (no <td>s)
265 * and if it is preceded entirely by header rows. The algorithm stops when
266 * it encounters the first non-header row.
268 * After this, it will look at all rows at the bottom for footer rows
269 * And place these in a tfoot using similar rules.
271 * @param {jQuery} $table object for a <table>
273 function emulateTHeadAndFoot( $table
) {
274 var $thead
, $tfoot
, i
, len
,
275 $rows
= $table
.find( '> tbody > tr' );
276 if ( !$table
.get( 0 ).tHead
) {
277 $thead
= $( '<thead>' );
278 $rows
.each( function () {
279 if ( $( this ).children( 'td' ).length
) {
280 // This row contains a <td>, so it's not a header row
284 $thead
.append( this );
286 $table
.find( ' > tbody:first' ).before( $thead
);
288 if ( !$table
.get( 0 ).tFoot
) {
289 $tfoot
= $( '<tfoot>' );
291 for ( i
= len
- 1; i
>= 0; i
-- ) {
292 if ( $( $rows
[ i
] ).children( 'td' ).length
) {
295 $tfoot
.prepend( $( $rows
[ i
] ) );
297 $table
.append( $tfoot
);
301 function uniqueElements( array
) {
303 array
.forEach( function ( elem
) {
304 if ( elem
!== undefined && uniques
.indexOf( elem
) === -1 ) {
305 uniques
.push( elem
);
311 function buildHeaders( table
, msg
) {
312 var config
= $( table
).data( 'tablesorter' ).config
,
324 $tableHeaders
= $( [] ),
325 $tableRows
= $( 'thead:eq(0) > tr', table
);
327 if ( $tableRows
.length
<= 1 ) {
328 $tableHeaders
= $tableRows
.children( 'th' );
332 // Loop through all the dom cells of the thead
333 $tableRows
.each( function ( rowIndex
, row
) {
334 // eslint-disable-next-line no-jquery/no-each-util
335 $.each( row
.cells
, function ( columnIndex
, cell
) {
339 rowspan
= Number( cell
.rowSpan
);
340 colspan
= Number( cell
.colSpan
);
342 // Skip the spots in the exploded matrix that are already filled
343 while ( exploded
[ rowIndex
] && exploded
[ rowIndex
][ columnIndex
] !== undefined ) {
347 // Find the actual dimensions of the thead, by placing each cell
348 // in the exploded matrix rowspan times colspan times, with the proper offsets
349 for ( matrixColumnIndex
= columnIndex
; matrixColumnIndex
< columnIndex
+ colspan
; ++matrixColumnIndex
) {
350 for ( matrixRowIndex
= rowIndex
; matrixRowIndex
< rowIndex
+ rowspan
; ++matrixRowIndex
) {
351 if ( !exploded
[ matrixRowIndex
] ) {
352 exploded
[ matrixRowIndex
] = [];
354 exploded
[ matrixRowIndex
][ matrixColumnIndex
] = cell
;
359 // We want to find the row that has the most columns (ignoring colspan)
360 exploded
.forEach( function ( cellArray
, index
) {
361 headerCount
= $( uniqueElements( cellArray
) ).filter( 'th' ).length
;
362 if ( headerCount
>= maxSeen
) {
363 maxSeen
= headerCount
;
367 // We cannot use $.unique() here because it sorts into dom order, which is undesirable
368 $tableHeaders
= $( uniqueElements( exploded
[ longestTR
] ) ).filter( 'th' );
371 // as each header can span over multiple columns (using colspan=N),
372 // we have to bidirectionally map headers to their columns and columns to their headers
373 config
.columnToHeader
= [];
374 config
.headerToColumns
= [];
375 config
.headerList
= [];
377 $tableHeaders
.each( function () {
381 if ( !$cell
.hasClass( config
.unsortableClass
) ) {
383 .addClass( config
.cssHeader
)
384 .prop( 'tabIndex', 0 )
386 role
: 'columnheader button',
390 for ( k
= 0; k
< this.colSpan
; k
++ ) {
391 config
.columnToHeader
[ colspanOffset
+ k
] = headerIndex
;
392 columns
.push( colspanOffset
+ k
);
395 config
.headerToColumns
[ headerIndex
] = columns
;
398 headerIndex
: headerIndex
,
403 // add only sortable cells to headerList
404 config
.headerList
[ headerIndex
] = this;
408 colspanOffset
+= this.colSpan
;
411 // number of columns with extended colspan, inclusive unsortable
412 // parsers[j], cache[][j], columnToHeader[j], columnToCell[j] have so many elements
413 config
.columns
= colspanOffset
;
415 return $tableHeaders
.not( '.' + config
.unsortableClass
);
418 function isValueInArray( v
, a
) {
420 for ( i
= 0; i
< a
.length
; i
++ ) {
421 if ( a
[ i
][ 0 ] === v
) {
429 * Sets the sort count of the columns that are not affected by the sorting to have them sorted
430 * in default (ascending) order when their header cell is clicked the next time.
432 * @param {jQuery} $headers
433 * @param {Array} sortList 2D number array
434 * @param {Array} headerToColumns 2D number array
436 function setHeadersOrder( $headers
, sortList
, headerToColumns
) {
437 // Loop through all headers to retrieve the indices of the columns the header spans across:
438 headerToColumns
.forEach( function ( columns
, headerIndex
) {
440 columns
.forEach( function ( columnIndex
, i
) {
442 header
= $headers
[ headerIndex
],
443 $header
= $( header
);
445 if ( !isValueInArray( columnIndex
, sortList
) ) {
446 // Column shall not be sorted: Reset header count and order.
452 // Column shall be sorted: Apply designated count and order.
453 for ( j
= 0; j
< sortList
.length
; j
++ ) {
454 sortColumn
= sortList
[ j
];
455 if ( sortColumn
[ 0 ] === i
) {
457 order
: sortColumn
[ 1 ],
458 count
: sortColumn
[ 1 ] + 1
469 function setHeadersCss( table
, $headers
, list
, css
, msg
, columnToHeader
) {
471 // Remove all header information and reset titles to default message
472 $headers
.removeClass( css
).attr( 'title', msg
[ 1 ] );
474 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
476 .eq( columnToHeader
[ list
[ i
][ 0 ] ] )
477 .addClass( css
[ list
[ i
][ 1 ] ] )
478 .attr( 'title', msg
[ list
[ i
][ 1 ] ] );
482 function sortText( a
, b
) {
483 return ( ( a
< b
) ? -1 : ( ( a
> b
) ? 1 : 0 ) );
486 function sortTextDesc( a
, b
) {
487 return ( ( b
< a
) ? -1 : ( ( b
> a
) ? 1 : 0 ) );
490 function multisort( table
, sortList
, cache
) {
494 for ( i
= 0; i
< sortList
.length
; i
++ ) {
495 sortFn
[ i
] = ( sortList
[ i
][ 1 ] ) ? sortTextDesc
: sortText
;
497 cache
.normalized
.sort( function ( array1
, array2
) {
499 for ( i
= 0; i
< sortList
.length
; i
++ ) {
500 col
= sortList
[ i
][ 0 ];
501 ret
= sortFn
[ i
].call( this, array1
[ col
], array2
[ col
] );
506 // Fall back to index number column to ensure stable sort
507 return sortText
.call( this, array1
[ array1
.length
- 1 ], array2
[ array2
.length
- 1 ] );
512 function buildTransformTable() {
513 var ascii
, localised
, i
, digitClass
,
514 digits
= '0123456789,.'.split( '' ),
515 separatorTransformTable
= mw
.config
.get( 'wgSeparatorTransformTable' ),
516 digitTransformTable
= mw
.config
.get( 'wgDigitTransformTable' );
518 if ( separatorTransformTable
=== null || ( separatorTransformTable
[ 0 ] === '' && digitTransformTable
[ 2 ] === '' ) ) {
519 ts
.transformTable
= false;
521 ts
.transformTable
= {};
523 // Unpack the transform table
524 ascii
= separatorTransformTable
[ 0 ].split( '\t' ).concat( digitTransformTable
[ 0 ].split( '\t' ) );
525 localised
= separatorTransformTable
[ 1 ].split( '\t' ).concat( digitTransformTable
[ 1 ].split( '\t' ) );
527 // Construct regexes for number identification
528 for ( i
= 0; i
< ascii
.length
; i
++ ) {
529 ts
.transformTable
[ localised
[ i
] ] = ascii
[ i
];
530 digits
.push( mw
.RegExp
.escape( localised
[ i
] ) );
533 digitClass
= '[' + digits
.join( '', digits
) + ']';
535 // We allow a trailing percent sign, which we just strip. This works fine
536 // if percents and regular numbers aren't being mixed.
537 ts
.numberRegex
= new RegExp(
539 '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
541 '[-+\u2212]?' + digitClass
+ '+[\\s\\xa0]*%?' + // Generic localised
547 function buildDateTable() {
553 for ( i
= 0; i
< 12; i
++ ) {
554 name
= mw
.language
.months
.names
[ i
].toLowerCase();
555 ts
.monthNames
[ name
] = i
+ 1;
556 regex
.push( mw
.RegExp
.escape( name
) );
557 name
= mw
.language
.months
.genitive
[ i
].toLowerCase();
558 ts
.monthNames
[ name
] = i
+ 1;
559 regex
.push( mw
.RegExp
.escape( name
) );
560 name
= mw
.language
.months
.abbrev
[ i
].toLowerCase().replace( '.', '' );
561 ts
.monthNames
[ name
] = i
+ 1;
562 regex
.push( mw
.RegExp
.escape( name
) );
565 // Build piped string
566 regex
= regex
.join( '|' );
569 // Any date formated with . , ' - or /
570 ts
.dateRegex
[ 0 ] = new RegExp( /^\s*(\d{1,2})[,.\-/'\s]{1,2}(\d{1,2})[,.\-/'\s
]{1,2}(\d
{2,4})\s
*?/i
);
572 // Written Month name, dmy
573 ts
.dateRegex
[ 1 ] = new RegExp(
574 '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(' +
577 '[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$',
581 // Written Month name, mdy
582 ts
.dateRegex
[ 2 ] = new RegExp(
583 '^\\s*(' + regex
+ ')' +
584 '[\\,\\.\\-\\/\'\\s]+(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$',
591 * Replace all rowspanned cells in the body with clones in each row, so sorting
592 * need not worry about them.
594 * @param {jQuery} $table jQuery object for a <table>
596 function explodeRowspans( $table
) {
597 var spanningRealCellIndex
, rowSpan
, colSpan
,
598 cell
, cellData
, i
, $tds
, $clone
, $nextRows
,
599 rowspanCells
= $table
.find( '> tbody > tr > [rowspan]' ).get();
602 if ( !rowspanCells
.length
) {
606 // First, we need to make a property like cellIndex but taking into
607 // account colspans. We also cache the rowIndex to avoid having to take
608 // cell.parentNode.rowIndex in the sorting function below.
609 $table
.find( '> tbody > tr' ).each( function () {
612 len
= this.cells
.length
;
613 for ( i
= 0; i
< len
; i
++ ) {
614 $( this.cells
[ i
] ).data( 'tablesorter', {
616 realRowIndex
: this.rowIndex
618 col
+= this.cells
[ i
].colSpan
;
622 // Split multi row cells into multiple cells with the same content.
623 // Sort by column then row index to avoid problems with odd table structures.
624 // Re-sort whenever a rowspanned cell's realCellIndex is changed, because it
625 // might change the sort order.
626 function resortCells() {
630 rowspanCells
= rowspanCells
.sort( function ( a
, b
) {
631 cellAData
= $.data( a
, 'tablesorter' );
632 cellBData
= $.data( b
, 'tablesorter' );
633 ret
= cellAData
.realCellIndex
- cellBData
.realCellIndex
;
635 ret
= cellAData
.realRowIndex
- cellBData
.realRowIndex
;
639 rowspanCells
.forEach( function ( cell
) {
640 $.data( cell
, 'tablesorter' ).needResort
= false;
645 function filterfunc() {
646 return $.data( this, 'tablesorter' ).realCellIndex
>= spanningRealCellIndex
;
649 function fixTdCellIndex() {
650 $.data( this, 'tablesorter' ).realCellIndex
+= colSpan
;
651 if ( this.rowSpan
> 1 ) {
652 $.data( this, 'tablesorter' ).needResort
= true;
656 while ( rowspanCells
.length
) {
657 if ( $.data( rowspanCells
[ 0 ], 'tablesorter' ).needResort
) {
661 cell
= rowspanCells
.shift();
662 cellData
= $.data( cell
, 'tablesorter' );
663 rowSpan
= cell
.rowSpan
;
664 colSpan
= cell
.colSpan
;
665 spanningRealCellIndex
= cellData
.realCellIndex
;
667 $nextRows
= $( cell
).parent().nextAll();
668 for ( i
= 0; i
< rowSpan
- 1; i
++ ) {
669 $tds
= $( $nextRows
[ i
].cells
).filter( filterfunc
);
670 $clone
= $( cell
).clone();
671 $clone
.data( 'tablesorter', {
672 realCellIndex
: spanningRealCellIndex
,
673 realRowIndex
: cellData
.realRowIndex
+ i
,
677 $tds
.each( fixTdCellIndex
);
678 $tds
.first().before( $clone
);
680 $nextRows
.eq( i
).append( $clone
);
687 * Build index to handle colspanned cells in the body.
688 * Set the cell index for each column in an array,
689 * so that colspaned cells set multiple in this array.
690 * columnToCell[collumnIndex] point at the real cell in this row.
692 * @param {jQuery} $table object for a <table>
694 function manageColspans( $table
) {
696 $rows
= $table
.find( '> tbody > tr' ),
697 totalRows
= $rows
.length
|| 0,
698 config
= $table
.data( 'tablesorter' ).config
,
699 columns
= config
.columns
,
700 columnToCell
, cellsInRow
, index
;
702 for ( i
= 0; i
< totalRows
; i
++ ) {
704 $row
= $rows
.eq( i
);
705 // if this is a child row, continue to the next row (as buildCache())
706 if ( $row
.hasClass( config
.cssChildRow
) ) {
707 // go to the next for loop
712 cellsInRow
= ( $row
[ 0 ].cells
.length
) || 0; // all cells in this row
713 index
= 0; // real cell index in this row
714 for ( j
= 0; j
< columns
; index
++ ) {
715 if ( index
=== cellsInRow
) {
716 // Row with cells less than columns: add empty cell
717 $row
.append( '<td>' );
720 for ( k
= 0; k
< $row
[ 0 ].cells
[ index
].colSpan
; k
++ ) {
721 columnToCell
[ j
++ ] = index
;
725 $row
.data( 'columnToCell', columnToCell
);
729 function buildCollationTable() {
731 ts
.collationTable
= mw
.config
.get( 'tableSorterCollation' );
732 ts
.collationRegex
= null;
733 if ( ts
.collationTable
) {
734 // Build array of key names
735 for ( key
in ts
.collationTable
) {
736 keys
.push( mw
.RegExp
.escape( key
) );
739 ts
.collationRegex
= new RegExp( keys
.join( '|' ), 'ig' );
744 function cacheRegexs() {
750 new RegExp( /^\d{1,3}[.]\d{1,3}[.]\d{1,3}[.]\d{1,3}$/ )
753 new RegExp( /(^[£$€¥]|[£$€¥]$)/ ),
754 new RegExp( /[£$€¥]/g )
757 new RegExp( /^(https?|ftp|file):\/\/$/ ),
758 new RegExp( /(https?|ftp|file):\/\// )
761 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)?)?)?/ ),
762 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)?)?)?/ )
765 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)))$/ )
768 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/ )
774 * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
775 * structure [ [ Integer, Integer ], ... ]
777 * @param {Array} sortObjects List of sort objects.
778 * @return {Array} List of internal sort definitions.
780 function convertSortList( sortObjects
) {
782 sortObjects
.forEach( function ( sortObject
) {
783 // eslint-disable-next-line no-jquery/no-each-util
784 $.each( sortObject
, function ( columnIndex
, order
) {
785 var orderIndex
= ( order
=== 'desc' ) ? 1 : 0;
786 sortList
.push( [ parseInt( columnIndex
, 10 ), orderIndex
] );
796 cssHeader
: 'headerSort',
797 cssAsc
: 'headerSortUp',
798 cssDesc
: 'headerSortDown',
799 cssChildRow
: 'expand-child',
800 sortMultiSortKey
: 'shiftKey',
801 unsortableClass
: 'unsortable',
803 cancelSelection
: true,
815 * @param {jQuery} $tables
816 * @param {Object} [settings]
819 construct: function ( $tables
, settings
) {
820 return $tables
.each( function ( i
, table
) {
821 // Declare and cache.
822 var $headers
, cache
, config
, sortCSS
, sortMsg
,
826 // Don't construct twice on the same table
827 if ( $.data( table
, 'tablesorter' ) ) {
831 if ( !table
.tBodies
) {
834 if ( !table
.tHead
) {
835 // No thead found. Look for rows with <th>s and
836 // move them into a <thead> tag or a <tfoot> tag
837 emulateTHeadAndFoot( $table
);
839 // Still no thead? Then quit
840 if ( !table
.tHead
) {
844 // The `sortable` class is used to identify tables which will become sortable
845 // If not used it will create a FOUC but it should be added since the sortable class
846 // is responsible for certain crucial style elements. If the class is already present
847 // this action will be harmless.
848 $table
.addClass( 'jquery-tablesorter sortable' );
851 config
= $.extend( {}, $.tablesorter
.defaultOptions
, settings
);
853 // Save the settings where they read
854 $.data( table
, 'tablesorter', { config
: config
} );
856 // Get the CSS class names, could be done elsewhere
857 sortCSS
= [ config
.cssAsc
, config
.cssDesc
];
858 // Messages tell the user what the *next* state will be
859 // so are in reverse order to the CSS classes.
860 sortMsg
= [ mw
.msg( 'sort-descending' ), mw
.msg( 'sort-ascending' ) ];
863 $headers
= buildHeaders( table
, sortMsg
);
865 // Grab and process locale settings.
866 buildTransformTable();
869 // Precaching regexps can bring 10 fold
870 // performance improvements in some browsers.
873 function setupForFirstSort() {
874 var $tfoot
, $sortbottoms
;
878 // Defer buildCollationTable to first sort. As user and site scripts
879 // may customize tableSorterCollation but load after $.ready(), other
880 // scripts may call .tablesorter() before they have done the
881 // tableSorterCollation customizations.
882 buildCollationTable();
884 // Legacy fix of .sortbottoms
885 // Wrap them inside a tfoot (because that's what they actually want to be)
886 // and put the <tfoot> at the end of the <table>
887 $sortbottoms
= $table
.find( '> tbody > tr.sortbottom' );
888 if ( $sortbottoms
.length
) {
889 $tfoot
= $table
.children( 'tfoot' );
890 if ( $tfoot
.length
) {
891 $tfoot
.eq( 0 ).prepend( $sortbottoms
);
893 $table
.append( $( '<tfoot>' ).append( $sortbottoms
) );
897 explodeRowspans( $table
);
898 manageColspans( $table
);
900 // Try to auto detect column type, and store in tables config
901 config
.parsers
= buildParserCache( table
, $headers
);
904 // Apply event handling to headers
905 // this is too big, perhaps break it out?
906 $headers
.on( 'keypress click', function ( e
) {
907 var cell
, $cell
, columns
, newSortList
, i
,
911 if ( e
.type
=== 'click' && e
.target
.nodeName
.toLowerCase() === 'a' ) {
912 // The user clicked on a link inside a table header.
913 // Do nothing and let the default link click action continue.
917 if ( e
.type
=== 'keypress' && e
.which
!== 13 ) {
918 // Only handle keypresses on the "Enter" key.
926 // Build the cache for the tbody cells
927 // to share between calculations for this sort action.
928 // Re-calculated each time a sort action is performed due to possibility
929 // that sort values change. Shouldn't be too expensive, but if it becomes
930 // too slow an event based system should be implemented somehow where
931 // cells get event .change() and bubbles up to the <table> here
932 cache
= buildCache( table
);
934 totalRows
= ( $table
[ 0 ].tBodies
[ 0 ] && $table
[ 0 ].tBodies
[ 0 ].rows
.length
) || 0;
935 if ( totalRows
> 0 ) {
939 // Get current column sort order
941 order
: $cell
.data( 'count' ) % 2,
942 count
: $cell
.data( 'count' ) + 1
946 // Get current column index
947 columns
= config
.headerToColumns
[ $cell
.data( 'headerIndex' ) ];
948 newSortList
= columns
.map( function ( c
) {
949 return [ c
, $cell
.data( 'order' ) ];
951 // Index of first column belonging to this header
954 if ( !e
[ config
.sortMultiSortKey
] ) {
955 // User only wants to sort on one column set
956 // Flush the sort list and add new columns
957 config
.sortList
= newSortList
;
959 // Multi column sorting
960 // It is not possible for one column to belong to multiple headers,
961 // so this is okay - we don't need to check for every value in the columns array
962 if ( isValueInArray( i
, config
.sortList
) ) {
963 // The user has clicked on an already sorted column.
964 // Reverse the sorting direction for all tables.
965 for ( j
= 0; j
< config
.sortList
.length
; j
++ ) {
966 s
= config
.sortList
[ j
];
967 o
= config
.headerList
[ config
.columnToHeader
[ s
[ 0 ] ] ];
968 if ( isValueInArray( s
[ 0 ], newSortList
) ) {
969 $( o
).data( 'count', s
[ 1 ] + 1 );
970 s
[ 1 ] = $( o
).data( 'count' ) % 2;
974 // Add columns to sort list array
975 config
.sortList
= config
.sortList
.concat( newSortList
);
979 // Reset order/counts of cells not affected by sorting
980 setHeadersOrder( $headers
, config
.sortList
, config
.headerToColumns
);
982 // Set CSS for headers
983 setHeadersCss( $table
[ 0 ], $headers
, config
.sortList
, sortCSS
, sortMsg
, config
.columnToHeader
);
985 $table
[ 0 ], multisort( $table
[ 0 ], config
.sortList
, cache
)
988 // Stop normal event by returning false
993 } ).on( 'mousedown', function () {
994 if ( config
.cancelSelection
) {
995 this.onselectstart = function () {
1003 * Sorts the table. If no sorting is specified by passing a list of sort
1004 * objects, the table is sorted according to the initial sorting order.
1005 * Passing an empty array will reset sorting (basically just reset the headers
1006 * making the table appear unsorted).
1008 * @param {Array} [sortList] List of sort objects.
1010 $table
.data( 'tablesorter' ).sort = function ( sortList
) {
1013 setupForFirstSort();
1016 if ( sortList
=== undefined ) {
1017 sortList
= config
.sortList
;
1018 } else if ( sortList
.length
> 0 ) {
1019 sortList
= convertSortList( sortList
);
1022 // Set each column's sort count to be able to determine the correct sort
1023 // order when clicking on a header cell the next time
1024 setHeadersOrder( $headers
, sortList
, config
.headerToColumns
);
1026 // re-build the cache for the tbody cells
1027 cache
= buildCache( table
);
1029 // set css for headers
1030 setHeadersCss( table
, $headers
, sortList
, sortCSS
, sortMsg
, config
.columnToHeader
);
1032 // sort the table and append it to the dom
1033 appendToTable( table
, multisort( table
, sortList
, cache
) );
1037 if ( config
.sortList
.length
> 0 ) {
1038 config
.sortList
= convertSortList( config
.sortList
);
1039 $table
.data( 'tablesorter' ).sort();
1045 addParser: function ( parser
) {
1046 if ( !getParserById( parser
.id
) ) {
1047 parsers
.push( parser
);
1051 formatDigit: function ( s
) {
1053 if ( ts
.transformTable
!== false ) {
1055 for ( p
= 0; p
< s
.length
; p
++ ) {
1057 if ( c
in ts
.transformTable
) {
1058 out
+= ts
.transformTable
[ c
];
1065 i
= parseFloat( s
.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
1066 return isNaN( i
) ? -Infinity
: i
;
1069 formatFloat: function ( s
) {
1070 var i
= parseFloat( s
);
1071 return isNaN( i
) ? -Infinity
: i
;
1074 formatInt: function ( s
) {
1075 var i
= parseInt( s
, 10 );
1076 return isNaN( i
) ? -Infinity
: i
;
1079 clearTableBody: function ( table
) {
1080 $( table
.tBodies
[ 0 ] ).empty();
1083 getParser: function ( id
) {
1084 buildTransformTable();
1087 buildCollationTable();
1089 return getParserById( id
);
1092 getParsers: function () { // for table diagnosis
1100 // Register as jQuery prototype method
1101 $.fn
.tablesorter = function ( settings
) {
1102 return ts
.construct( this, settings
);
1105 // Add default parsers
1111 format: function ( s
) {
1113 s
= s
.toLowerCase().trim();
1114 if ( ts
.collationRegex
) {
1115 tsc
= ts
.collationTable
;
1116 s
= s
.replace( ts
.collationRegex
, function ( match
) {
1117 var r
= tsc
[ match
] ? tsc
[ match
] : tsc
[ match
.toUpperCase() ];
1118 return r
.toLowerCase();
1128 is: function ( s
) {
1129 return ts
.rgx
.IPAddress
[ 0 ].test( s
);
1131 format: function ( s
) {
1135 for ( i
= 0; i
< a
.length
; i
++ ) {
1137 if ( item
.length
=== 1 ) {
1139 } else if ( item
.length
=== 2 ) {
1145 return $.tablesorter
.formatFloat( r
);
1152 is: function ( s
) {
1153 return ts
.rgx
.currency
[ 0 ].test( s
);
1155 format: function ( s
) {
1156 return $.tablesorter
.formatDigit( s
.replace( ts
.rgx
.currency
[ 1 ], '' ) );
1163 is: function ( s
) {
1164 return ts
.rgx
.url
[ 0 ].test( s
);
1166 format: function ( s
) {
1167 return s
.replace( ts
.rgx
.url
[ 1 ], '' ).trim();
1174 is: function ( s
) {
1175 return ts
.rgx
.isoDate
[ 0 ].test( s
);
1177 format: function ( s
) {
1178 var match
, i
, isodate
, ms
, hOffset
, mOffset
;
1179 match
= s
.match( ts
.rgx
.isoDate
[ 0 ] );
1180 if ( match
=== null ) {
1181 // Otherwise a signed number with 1-4 digit is parsed as isoDate
1182 match
= s
.match( ts
.rgx
.isoDate
[ 1 ] );
1188 for ( i
= 2; i
<= 4; i
+= 2 ) {
1189 if ( !match
[ i
] || match
[ i
].length
=== 0 ) {
1194 for ( i
= 6; i
<= 15; i
++ ) {
1195 if ( !match
[ i
] || match
[ i
].length
=== 0 ) {
1199 ms
= parseFloat( match
[ 11 ].replace( /,/, '.' ) ) * 1000;
1200 hOffset
= $.tablesorter
.formatInt( match
[ 13 ] + match
[ 14 ] );
1201 mOffset
= $.tablesorter
.formatInt( match
[ 13 ] + match
[ 15 ] );
1203 isodate
= new Date( 0 );
1204 // Because Date constructor changes year 0-99 to 1900-1999, use setUTCFullYear()
1205 isodate
.setUTCFullYear( match
[ 1 ], match
[ 2 ] - 1, match
[ 4 ] );
1206 isodate
.setUTCHours( match
[ 6 ] - hOffset
, match
[ 8 ] - mOffset
, match
[ 10 ], ms
);
1207 return isodate
.getTime();
1214 is: function ( s
) {
1215 return ts
.rgx
.usLongDate
[ 0 ].test( s
);
1217 format: function ( s
) {
1218 return $.tablesorter
.formatFloat( new Date( s
).getTime() );
1225 is: function ( s
) {
1226 return ( ts
.dateRegex
[ 0 ].test( s
) || ts
.dateRegex
[ 1 ].test( s
) || ts
.dateRegex
[ 2 ].test( s
) );
1228 format: function ( s
) {
1230 s
= s
.toLowerCase().trim();
1232 if ( ( match
= s
.match( ts
.dateRegex
[ 0 ] ) ) !== null ) {
1233 if ( mw
.config
.get( 'wgDefaultDateFormat' ) === 'mdy' || mw
.config
.get( 'wgPageContentLanguage' ) === 'en' ) {
1234 s
= [ match
[ 3 ], match
[ 1 ], match
[ 2 ] ];
1235 } else if ( mw
.config
.get( 'wgDefaultDateFormat' ) === 'dmy' ) {
1236 s
= [ match
[ 3 ], match
[ 2 ], match
[ 1 ] ];
1238 // If we get here, we don't know which order the dd-dd-dddd
1239 // date is in. So return something not entirely invalid.
1242 } else if ( ( match
= s
.match( ts
.dateRegex
[ 1 ] ) ) !== null ) {
1243 s
= [ match
[ 3 ], String( ts
.monthNames
[ match
[ 2 ] ] ), match
[ 1 ] ];
1244 } else if ( ( match
= s
.match( ts
.dateRegex
[ 2 ] ) ) !== null ) {
1245 s
= [ match
[ 3 ], String( ts
.monthNames
[ match
[ 1 ] ] ), match
[ 2 ] ];
1247 // Should never get here
1251 // Pad Month and Day
1252 if ( s
[ 1 ].length
=== 1 ) {
1253 s
[ 1 ] = '0' + s
[ 1 ];
1255 if ( s
[ 2 ].length
=== 1 ) {
1256 s
[ 2 ] = '0' + s
[ 2 ];
1259 if ( ( y
= parseInt( s
[ 0 ], 10 ) ) < 100 ) {
1260 // Guestimate years without centuries
1267 while ( s
[ 0 ].length
< 4 ) {
1268 s
[ 0 ] = '0' + s
[ 0 ];
1270 return parseInt( s
.join( '' ), 10 );
1277 is: function ( s
) {
1278 return ts
.rgx
.time
[ 0 ].test( s
);
1280 format: function ( s
) {
1281 return $.tablesorter
.formatFloat( new Date( '2000/01/01 ' + s
).getTime() );
1288 is: function ( s
) {
1289 return $.tablesorter
.numberRegex
.test( s
.trim() );
1291 format: function ( s
) {
1292 return $.tablesorter
.formatDigit( s
);