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 // eslint-disable-next-line no-jquery/no-class-state
87 if ( $( elem
).hasClass( 'reference' ) ) {
90 return getElementSortKey( elem
);
92 if ( elem
.nodeType
=== Node
.TEXT_NODE
) {
93 return elem
.textContent
;
95 // Ignore other node types, such as HTML comments.
100 function detectParserForColumn( table
, rows
, column
) {
101 var l
= parsers
.length
,
102 config
= $( table
).data( 'tablesorter' ).config
,
106 // Start with 1 because 0 is the fallback parser
112 needed
= ( rows
.length
> 4 ) ? 5 : rows
.length
;
115 // if this is a child row, continue to the next row (as buildCache())
116 // eslint-disable-next-line no-jquery/no-class-state
117 if ( rows
[ rowIndex
] && !$( rows
[ rowIndex
] ).hasClass( config
.cssChildRow
) ) {
118 if ( rowIndex
!== lastRowIndex
) {
119 lastRowIndex
= rowIndex
;
120 cellIndex
= $( rows
[ rowIndex
] ).data( 'columnToCell' )[ column
];
121 nodeValue
= getElementSortKey( rows
[ rowIndex
].cells
[ cellIndex
] ).trim();
127 if ( nodeValue
!== '' ) {
128 if ( parsers
[ i
].is( nodeValue
, table
) ) {
131 if ( concurrent
>= needed
) {
132 // Confirmed the parser for multiple cells, let's return it
135 } else if ( parsers
[ i
].id
.match( /isoDate/ ) && /^\D*(\d{1,4}) ?(\[.+\])?$/.test( nodeValue
) ) {
136 // For 1-4 digits and maybe reference(s) parser "isoDate" or "number" is possible, check next row
140 // Check next parser, reset rows
156 if ( rowIndex
>= rows
.length
) {
157 if ( concurrent
> 0 && concurrent
>= rows
.length
- empty
) {
158 // Confirmed the parser for all filled cells
161 // Check next parser, reset rows
170 // 0 is always the generic parser (text)
174 function buildParserCache( table
, $headers
) {
175 var sortType
, len
, j
, parser
,
176 rows
= table
.tBodies
[ 0 ].rows
,
177 config
= $( table
).data( 'tablesorter' ).config
,
181 len
= config
.columns
;
182 for ( j
= 0; j
< len
; j
++ ) {
184 sortType
= $headers
.eq( config
.columnToHeader
[ j
] ).data( 'sortType' );
185 if ( sortType
!== undefined ) {
186 parser
= getParserById( sortType
);
189 if ( parser
=== false ) {
190 parser
= detectParserForColumn( table
, rows
, j
);
193 parsers
.push( parser
);
199 /* Other utility functions */
201 function buildCache( table
) {
202 var i
, j
, $row
, cols
,
203 totalRows
= ( table
.tBodies
[ 0 ] && table
.tBodies
[ 0 ].rows
.length
) || 0,
204 config
= $( table
).data( 'tablesorter' ).config
,
205 parsers
= config
.parsers
,
206 len
= parsers
.length
,
213 for ( i
= 0; i
< totalRows
; i
++ ) {
215 // Add the table data to main data array
216 $row
= $( table
.tBodies
[ 0 ].rows
[ i
] );
219 // if this is a child row, add it to the last row's children and
220 // continue to the next row
221 // eslint-disable-next-line no-jquery/no-class-state
222 if ( $row
.hasClass( config
.cssChildRow
) ) {
223 cache
.row
[ cache
.row
.length
- 1 ] = cache
.row
[ cache
.row
.length
- 1 ].add( $row
);
224 // go to the next for loop
228 cache
.row
.push( $row
);
230 for ( j
= 0; j
< len
; j
++ ) {
231 cellIndex
= $row
.data( 'columnToCell' )[ j
];
232 cols
.push( parsers
[ j
].format( getElementSortKey( $row
[ 0 ].cells
[ cellIndex
] ) ) );
235 cols
.push( cache
.normalized
.length
); // add position for rowCache
236 cache
.normalized
.push( cols
);
243 function appendToTable( table
, cache
) {
246 normalized
= cache
.normalized
,
247 totalRows
= normalized
.length
,
248 checkCell
= ( normalized
[ 0 ].length
- 1 ),
249 fragment
= document
.createDocumentFragment();
251 for ( i
= 0; i
< totalRows
; i
++ ) {
252 pos
= normalized
[ i
][ checkCell
];
254 l
= row
[ pos
].length
;
255 for ( j
= 0; j
< l
; j
++ ) {
256 fragment
.appendChild( row
[ pos
][ j
] );
260 table
.tBodies
[ 0 ].appendChild( fragment
);
262 $( table
).trigger( 'sortEnd.tablesorter' );
266 * Find all header rows in a thead-less table and put them in a <thead> tag.
267 * This only treats a row as a header row if it contains only <th>s (no <td>s)
268 * and if it is preceded entirely by header rows. The algorithm stops when
269 * it encounters the first non-header row.
271 * After this, it will look at all rows at the bottom for footer rows
272 * And place these in a tfoot using similar rules.
274 * @param {jQuery} $table object for a <table>
276 function emulateTHeadAndFoot( $table
) {
277 var $thead
, $tfoot
, i
, len
,
278 $rows
= $table
.find( '> tbody > tr' );
279 if ( !$table
.get( 0 ).tHead
) {
280 $thead
= $( '<thead>' );
281 $rows
.each( function () {
282 if ( $( this ).children( 'td' ).length
) {
283 // This row contains a <td>, so it's not a header row
287 $thead
.append( this );
289 $table
.find( ' > tbody' ).first().before( $thead
);
291 if ( !$table
.get( 0 ).tFoot
) {
292 $tfoot
= $( '<tfoot>' );
294 for ( i
= len
- 1; i
>= 0; i
-- ) {
295 if ( $( $rows
[ i
] ).children( 'td' ).length
) {
298 $tfoot
.prepend( $( $rows
[ i
] ) );
300 $table
.append( $tfoot
);
304 function uniqueElements( array
) {
306 array
.forEach( function ( elem
) {
307 if ( elem
!== undefined && uniques
.indexOf( elem
) === -1 ) {
308 uniques
.push( elem
);
314 function buildHeaders( table
, msg
) {
315 var config
= $( table
).data( 'tablesorter' ).config
,
327 $tableHeaders
= $( [] ),
328 $tableRows
= $( table
).find( 'thead' ).eq( 0 ).find( '> tr' );
330 if ( $tableRows
.length
<= 1 ) {
331 $tableHeaders
= $tableRows
.children( 'th' );
335 // Loop through all the dom cells of the thead
336 $tableRows
.each( function ( rowIndex
, row
) {
337 // eslint-disable-next-line no-jquery/no-each-util
338 $.each( row
.cells
, function ( columnIndex
, cell
) {
342 rowspan
= Number( cell
.rowSpan
);
343 colspan
= Number( cell
.colSpan
);
345 // Skip the spots in the exploded matrix that are already filled
346 while ( exploded
[ rowIndex
] && exploded
[ rowIndex
][ columnIndex
] !== undefined ) {
350 // Find the actual dimensions of the thead, by placing each cell
351 // in the exploded matrix rowspan times colspan times, with the proper offsets
352 for ( matrixColumnIndex
= columnIndex
; matrixColumnIndex
< columnIndex
+ colspan
; ++matrixColumnIndex
) {
353 for ( matrixRowIndex
= rowIndex
; matrixRowIndex
< rowIndex
+ rowspan
; ++matrixRowIndex
) {
354 if ( !exploded
[ matrixRowIndex
] ) {
355 exploded
[ matrixRowIndex
] = [];
357 exploded
[ matrixRowIndex
][ matrixColumnIndex
] = cell
;
362 // We want to find the row that has the most columns (ignoring colspan)
363 exploded
.forEach( function ( cellArray
, index
) {
364 headerCount
= $( uniqueElements( cellArray
) ).filter( 'th' ).length
;
365 if ( headerCount
>= maxSeen
) {
366 maxSeen
= headerCount
;
370 // We cannot use $.unique() here because it sorts into dom order, which is undesirable
371 $tableHeaders
= $( uniqueElements( exploded
[ longestTR
] ) ).filter( 'th' );
374 // as each header can span over multiple columns (using colspan=N),
375 // we have to bidirectionally map headers to their columns and columns to their headers
376 config
.columnToHeader
= [];
377 config
.headerToColumns
= [];
378 config
.headerList
= [];
380 $tableHeaders
.each( function () {
384 // eslint-disable-next-line no-jquery/no-class-state
385 if ( !$cell
.hasClass( config
.unsortableClass
) ) {
387 .addClass( config
.cssHeader
)
388 .prop( 'tabIndex', 0 )
390 role
: 'columnheader button',
394 for ( k
= 0; k
< this.colSpan
; k
++ ) {
395 config
.columnToHeader
[ colspanOffset
+ k
] = headerIndex
;
396 columns
.push( colspanOffset
+ k
);
399 config
.headerToColumns
[ headerIndex
] = columns
;
402 headerIndex
: headerIndex
,
407 // add only sortable cells to headerList
408 config
.headerList
[ headerIndex
] = this;
412 colspanOffset
+= this.colSpan
;
415 // number of columns with extended colspan, inclusive unsortable
416 // parsers[j], cache[][j], columnToHeader[j], columnToCell[j] have so many elements
417 config
.columns
= colspanOffset
;
419 return $tableHeaders
.not( '.' + config
.unsortableClass
);
422 function isValueInArray( v
, a
) {
424 for ( i
= 0; i
< a
.length
; i
++ ) {
425 if ( a
[ i
][ 0 ] === v
) {
433 * Sets the sort count of the columns that are not affected by the sorting to have them sorted
434 * in default (ascending) order when their header cell is clicked the next time.
436 * @param {jQuery} $headers
437 * @param {Array} sortList 2D number array
438 * @param {Array} headerToColumns 2D number array
440 function setHeadersOrder( $headers
, sortList
, headerToColumns
) {
441 // Loop through all headers to retrieve the indices of the columns the header spans across:
442 headerToColumns
.forEach( function ( columns
, headerIndex
) {
444 columns
.forEach( function ( columnIndex
, i
) {
446 header
= $headers
[ headerIndex
],
447 $header
= $( header
);
449 if ( !isValueInArray( columnIndex
, sortList
) ) {
450 // Column shall not be sorted: Reset header count and order.
456 // Column shall be sorted: Apply designated count and order.
457 for ( j
= 0; j
< sortList
.length
; j
++ ) {
458 sortColumn
= sortList
[ j
];
459 if ( sortColumn
[ 0 ] === i
) {
461 order
: sortColumn
[ 1 ],
462 count
: sortColumn
[ 1 ] + 1
473 function setHeadersCss( table
, $headers
, list
, css
, msg
, columnToHeader
) {
475 // Remove all header information and reset titles to default message
476 $headers
.removeClass( css
).attr( 'title', msg
[ 1 ] );
478 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
480 .eq( columnToHeader
[ list
[ i
][ 0 ] ] )
481 .addClass( css
[ list
[ i
][ 1 ] ] )
482 .attr( 'title', msg
[ list
[ i
][ 1 ] ] );
486 function sortText( a
, b
) {
487 return ts
.collator
.compare( a
, b
);
490 function sortNumeric( a
, b
) {
491 return ( ( a
< b
) ? -1 : ( ( a
> b
) ? 1 : 0 ) );
494 function multisort( table
, sortList
, cache
) {
497 parsers
= $( table
).data( 'tablesorter' ).config
.parsers
;
499 for ( i
= 0; i
< sortList
.length
; i
++ ) {
500 // Android doesn't support Intl.Collator
501 if ( window
.Intl
&& Intl
.Collator
&& parsers
[ sortList
[ i
][ 0 ] ].type
=== 'text' ) {
502 sortFn
[ i
] = sortText
;
504 sortFn
[ i
] = sortNumeric
;
507 cache
.normalized
.sort( function ( array1
, array2
) {
509 for ( i
= 0; i
< sortList
.length
; i
++ ) {
510 col
= sortList
[ i
][ 0 ];
511 if ( sortList
[ i
][ 1 ] ) {
513 ret
= sortFn
[ i
].call( this, array2
[ col
], array1
[ col
] );
516 ret
= sortFn
[ i
].call( this, array1
[ col
], array2
[ col
] );
522 // Fall back to index number column to ensure stable sort
523 return sortText
.call( this, array1
[ array1
.length
- 1 ], array2
[ array2
.length
- 1 ] );
528 function buildTransformTable() {
529 var ascii
, localised
, i
, digitClass
,
530 digits
= '0123456789,.'.split( '' ),
531 separatorTransformTable
= mw
.config
.get( 'wgSeparatorTransformTable' ),
532 digitTransformTable
= mw
.config
.get( 'wgDigitTransformTable' );
534 if ( separatorTransformTable
=== null || ( separatorTransformTable
[ 0 ] === '' && digitTransformTable
[ 2 ] === '' ) ) {
535 ts
.transformTable
= false;
537 ts
.transformTable
= {};
539 // Unpack the transform table
540 ascii
= separatorTransformTable
[ 0 ].split( '\t' ).concat( digitTransformTable
[ 0 ].split( '\t' ) );
541 localised
= separatorTransformTable
[ 1 ].split( '\t' ).concat( digitTransformTable
[ 1 ].split( '\t' ) );
543 // Construct regexes for number identification
544 for ( i
= 0; i
< ascii
.length
; i
++ ) {
545 ts
.transformTable
[ localised
[ i
] ] = ascii
[ i
];
546 digits
.push( mw
.RegExp
.escape( localised
[ i
] ) );
549 digitClass
= '[' + digits
.join( '', digits
) + ']';
551 // We allow a trailing percent sign, which we just strip. This works fine
552 // if percents and regular numbers aren't being mixed.
553 ts
.numberRegex
= new RegExp(
555 '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
557 '[-+\u2212]?' + digitClass
+ '+[\\s\\xa0]*%?' + // Generic localised
563 function buildDateTable() {
569 for ( i
= 0; i
< 12; i
++ ) {
570 name
= mw
.language
.months
.names
[ i
].toLowerCase();
571 ts
.monthNames
[ name
] = i
+ 1;
572 regex
.push( mw
.RegExp
.escape( name
) );
573 name
= mw
.language
.months
.genitive
[ i
].toLowerCase();
574 ts
.monthNames
[ name
] = i
+ 1;
575 regex
.push( mw
.RegExp
.escape( name
) );
576 name
= mw
.language
.months
.abbrev
[ i
].toLowerCase().replace( '.', '' );
577 ts
.monthNames
[ name
] = i
+ 1;
578 regex
.push( mw
.RegExp
.escape( name
) );
581 // Build piped string
582 regex
= regex
.join( '|' );
585 // Any date formated with . , ' - or /
586 ts
.dateRegex
[ 0 ] = new RegExp( /^\s*(\d{1,2})[,.\-/'\s]{1,2}(\d{1,2})[,.\-/'\s
]{1,2}(\d
{2,4})\s
*?/i
);
588 // Written Month name, dmy
589 ts
.dateRegex
[ 1 ] = new RegExp(
590 '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(' +
593 '[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$',
597 // Written Month name, mdy
598 ts
.dateRegex
[ 2 ] = new RegExp(
599 '^\\s*(' + regex
+ ')' +
600 '[\\,\\.\\-\\/\'\\s]+(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$',
607 * Replace all rowspanned cells in the body with clones in each row, so sorting
608 * need not worry about them.
610 * @param {jQuery} $table jQuery object for a <table>
612 function explodeRowspans( $table
) {
613 var spanningRealCellIndex
, rowSpan
, colSpan
,
614 cell
, cellData
, i
, $tds
, $clone
, $nextRows
,
615 rowspanCells
= $table
.find( '> tbody > tr > [rowspan]' ).get();
618 if ( !rowspanCells
.length
) {
622 // First, we need to make a property like cellIndex but taking into
623 // account colspans. We also cache the rowIndex to avoid having to take
624 // cell.parentNode.rowIndex in the sorting function below.
625 $table
.find( '> tbody > tr' ).each( function () {
628 len
= this.cells
.length
;
629 for ( i
= 0; i
< len
; i
++ ) {
630 $( this.cells
[ i
] ).data( 'tablesorter', {
632 realRowIndex
: this.rowIndex
634 col
+= this.cells
[ i
].colSpan
;
638 // Split multi row cells into multiple cells with the same content.
639 // Sort by column then row index to avoid problems with odd table structures.
640 // Re-sort whenever a rowspanned cell's realCellIndex is changed, because it
641 // might change the sort order.
642 function resortCells() {
646 rowspanCells
= rowspanCells
.sort( function ( a
, b
) {
647 cellAData
= $.data( a
, 'tablesorter' );
648 cellBData
= $.data( b
, 'tablesorter' );
649 ret
= cellAData
.realCellIndex
- cellBData
.realCellIndex
;
651 ret
= cellAData
.realRowIndex
- cellBData
.realRowIndex
;
655 rowspanCells
.forEach( function ( cell
) {
656 $.data( cell
, 'tablesorter' ).needResort
= false;
661 function filterfunc() {
662 return $.data( this, 'tablesorter' ).realCellIndex
>= spanningRealCellIndex
;
665 function fixTdCellIndex() {
666 $.data( this, 'tablesorter' ).realCellIndex
+= colSpan
;
667 if ( this.rowSpan
> 1 ) {
668 $.data( this, 'tablesorter' ).needResort
= true;
672 while ( rowspanCells
.length
) {
673 if ( $.data( rowspanCells
[ 0 ], 'tablesorter' ).needResort
) {
677 cell
= rowspanCells
.shift();
678 cellData
= $.data( cell
, 'tablesorter' );
679 rowSpan
= cell
.rowSpan
;
680 colSpan
= cell
.colSpan
;
681 spanningRealCellIndex
= cellData
.realCellIndex
;
683 $nextRows
= $( cell
).parent().nextAll();
684 for ( i
= 0; i
< rowSpan
- 1; i
++ ) {
685 $tds
= $( $nextRows
[ i
].cells
).filter( filterfunc
);
686 $clone
= $( cell
).clone();
687 $clone
.data( 'tablesorter', {
688 realCellIndex
: spanningRealCellIndex
,
689 realRowIndex
: cellData
.realRowIndex
+ i
,
693 $tds
.each( fixTdCellIndex
);
694 $tds
.first().before( $clone
);
696 $nextRows
.eq( i
).append( $clone
);
703 * Build index to handle colspanned cells in the body.
704 * Set the cell index for each column in an array,
705 * so that colspaned cells set multiple in this array.
706 * columnToCell[collumnIndex] point at the real cell in this row.
708 * @param {jQuery} $table object for a <table>
710 function manageColspans( $table
) {
712 $rows
= $table
.find( '> tbody > tr' ),
713 totalRows
= $rows
.length
|| 0,
714 config
= $table
.data( 'tablesorter' ).config
,
715 columns
= config
.columns
,
716 columnToCell
, cellsInRow
, index
;
718 for ( i
= 0; i
< totalRows
; i
++ ) {
720 $row
= $rows
.eq( i
);
721 // if this is a child row, continue to the next row (as buildCache())
722 // eslint-disable-next-line no-jquery/no-class-state
723 if ( $row
.hasClass( config
.cssChildRow
) ) {
724 // go to the next for loop
729 cellsInRow
= ( $row
[ 0 ].cells
.length
) || 0; // all cells in this row
730 index
= 0; // real cell index in this row
731 for ( j
= 0; j
< columns
; index
++ ) {
732 if ( index
=== cellsInRow
) {
733 // Row with cells less than columns: add empty cell
734 $row
.append( '<td>' );
737 for ( k
= 0; k
< $row
[ 0 ].cells
[ index
].colSpan
; k
++ ) {
738 columnToCell
[ j
++ ] = index
;
742 $row
.data( 'columnToCell', columnToCell
);
746 function buildCollation() {
748 ts
.collationTable
= mw
.config
.get( 'tableSorterCollation' );
749 ts
.collationRegex
= null;
750 if ( ts
.collationTable
) {
751 // Build array of key names
752 for ( key
in ts
.collationTable
) {
753 keys
.push( mw
.RegExp
.escape( key
) );
756 ts
.collationRegex
= new RegExp( keys
.join( '|' ), 'ig' );
759 if ( window
.Intl
&& Intl
.Collator
) {
760 ts
.collator
= new Intl
.Collator( [
761 mw
.config
.get( 'wgPageContentLanguage' ),
762 mw
.config
.get( 'wgUserLanguage' )
769 function cacheRegexs() {
775 new RegExp( /^\d{1,3}[.]\d{1,3}[.]\d{1,3}[.]\d{1,3}$/ )
778 new RegExp( /(^[£$€¥]|[£$€¥]$)/ ),
779 new RegExp( /[£$€¥]/g )
782 new RegExp( /^(https?|ftp|file):\/\/$/ ),
783 new RegExp( /(https?|ftp|file):\/\// )
786 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)?)?)?/ ),
787 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)?)?)?/ )
790 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)))$/ )
793 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/ )
799 * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
800 * structure [ [ Integer, Integer ], ... ]
802 * @param {Array} sortObjects List of sort objects.
803 * @return {Array} List of internal sort definitions.
805 function convertSortList( sortObjects
) {
807 sortObjects
.forEach( function ( sortObject
) {
808 // eslint-disable-next-line no-jquery/no-each-util
809 $.each( sortObject
, function ( columnIndex
, order
) {
810 var orderIndex
= ( order
=== 'desc' ) ? 1 : 0;
811 sortList
.push( [ parseInt( columnIndex
, 10 ), orderIndex
] );
821 cssHeader
: 'headerSort',
822 cssAsc
: 'headerSortUp',
823 cssDesc
: 'headerSortDown',
824 cssChildRow
: 'expand-child',
825 sortMultiSortKey
: 'shiftKey',
826 unsortableClass
: 'unsortable',
828 cancelSelection
: true,
840 * @param {jQuery} $tables
841 * @param {Object} [settings]
844 construct: function ( $tables
, settings
) {
845 return $tables
.each( function ( i
, table
) {
846 // Declare and cache.
847 var $headers
, cache
, config
, sortCSS
, sortMsg
,
851 // Don't construct twice on the same table
852 if ( $.data( table
, 'tablesorter' ) ) {
856 if ( !table
.tBodies
) {
859 if ( !table
.tHead
) {
860 // No thead found. Look for rows with <th>s and
861 // move them into a <thead> tag or a <tfoot> tag
862 emulateTHeadAndFoot( $table
);
864 // Still no thead? Then quit
865 if ( !table
.tHead
) {
869 // The `sortable` class is used to identify tables which will become sortable
870 // If not used it will create a FOUC but it should be added since the sortable class
871 // is responsible for certain crucial style elements. If the class is already present
872 // this action will be harmless.
873 $table
.addClass( 'jquery-tablesorter sortable' );
876 config
= $.extend( {}, $.tablesorter
.defaultOptions
, settings
);
878 // Save the settings where they read
879 $.data( table
, 'tablesorter', { config
: config
} );
881 // Get the CSS class names, could be done elsewhere
882 sortCSS
= [ config
.cssAsc
, config
.cssDesc
];
883 // Messages tell the user what the *next* state will be
884 // so are in reverse order to the CSS classes.
885 sortMsg
= [ mw
.msg( 'sort-descending' ), mw
.msg( 'sort-ascending' ) ];
888 $headers
= buildHeaders( table
, sortMsg
);
890 // Grab and process locale settings.
891 buildTransformTable();
894 // Precaching regexps can bring 10 fold
895 // performance improvements in some browsers.
898 function setupForFirstSort() {
899 var $tfoot
, $sortbottoms
;
903 // Defer buildCollationTable to first sort. As user and site scripts
904 // may customize tableSorterCollation but load after $.ready(), other
905 // scripts may call .tablesorter() before they have done the
906 // tableSorterCollation customizations.
909 // Legacy fix of .sortbottoms
910 // Wrap them inside a tfoot (because that's what they actually want to be)
911 // and put the <tfoot> at the end of the <table>
912 $sortbottoms
= $table
.find( '> tbody > tr.sortbottom' );
913 if ( $sortbottoms
.length
) {
914 $tfoot
= $table
.children( 'tfoot' );
915 if ( $tfoot
.length
) {
916 $tfoot
.eq( 0 ).prepend( $sortbottoms
);
918 $table
.append( $( '<tfoot>' ).append( $sortbottoms
) );
922 explodeRowspans( $table
);
923 manageColspans( $table
);
925 // Try to auto detect column type, and store in tables config
926 config
.parsers
= buildParserCache( table
, $headers
);
929 // Apply event handling to headers
930 // this is too big, perhaps break it out?
931 $headers
.on( 'keypress click', function ( e
) {
932 var cell
, $cell
, columns
, newSortList
, i
,
936 if ( e
.type
=== 'click' && e
.target
.nodeName
.toLowerCase() === 'a' ) {
937 // The user clicked on a link inside a table header.
938 // Do nothing and let the default link click action continue.
942 if ( e
.type
=== 'keypress' && e
.which
!== 13 ) {
943 // Only handle keypresses on the "Enter" key.
951 // Build the cache for the tbody cells
952 // to share between calculations for this sort action.
953 // Re-calculated each time a sort action is performed due to possibility
954 // that sort values change. Shouldn't be too expensive, but if it becomes
955 // too slow an event based system should be implemented somehow where
956 // cells get event .change() and bubbles up to the <table> here
957 cache
= buildCache( table
);
959 totalRows
= ( $table
[ 0 ].tBodies
[ 0 ] && $table
[ 0 ].tBodies
[ 0 ].rows
.length
) || 0;
960 if ( totalRows
> 0 ) {
964 // Get current column sort order
966 order
: $cell
.data( 'count' ) % 2,
967 count
: $cell
.data( 'count' ) + 1
971 // Get current column index
972 columns
= config
.headerToColumns
[ $cell
.data( 'headerIndex' ) ];
973 newSortList
= columns
.map( function ( c
) {
974 return [ c
, $cell
.data( 'order' ) ];
976 // Index of first column belonging to this header
979 if ( !e
[ config
.sortMultiSortKey
] ) {
980 // User only wants to sort on one column set
981 // Flush the sort list and add new columns
982 config
.sortList
= newSortList
;
984 // Multi column sorting
985 // It is not possible for one column to belong to multiple headers,
986 // so this is okay - we don't need to check for every value in the columns array
987 if ( isValueInArray( i
, config
.sortList
) ) {
988 // The user has clicked on an already sorted column.
989 // Reverse the sorting direction for all tables.
990 for ( j
= 0; j
< config
.sortList
.length
; j
++ ) {
991 s
= config
.sortList
[ j
];
992 o
= config
.headerList
[ config
.columnToHeader
[ s
[ 0 ] ] ];
993 if ( isValueInArray( s
[ 0 ], newSortList
) ) {
994 $( o
).data( 'count', s
[ 1 ] + 1 );
995 s
[ 1 ] = $( o
).data( 'count' ) % 2;
999 // Add columns to sort list array
1000 config
.sortList
= config
.sortList
.concat( newSortList
);
1004 // Reset order/counts of cells not affected by sorting
1005 setHeadersOrder( $headers
, config
.sortList
, config
.headerToColumns
);
1007 // Set CSS for headers
1008 setHeadersCss( $table
[ 0 ], $headers
, config
.sortList
, sortCSS
, sortMsg
, config
.columnToHeader
);
1010 $table
[ 0 ], multisort( $table
[ 0 ], config
.sortList
, cache
)
1013 // Stop normal event by returning false
1018 } ).on( 'mousedown', function () {
1019 if ( config
.cancelSelection
) {
1020 this.onselectstart = function () {
1028 * Sorts the table. If no sorting is specified by passing a list of sort
1029 * objects, the table is sorted according to the initial sorting order.
1030 * Passing an empty array will reset sorting (basically just reset the headers
1031 * making the table appear unsorted).
1033 * @param {Array} [sortList] List of sort objects.
1035 $table
.data( 'tablesorter' ).sort = function ( sortList
) {
1038 setupForFirstSort();
1041 if ( sortList
=== undefined ) {
1042 sortList
= config
.sortList
;
1043 } else if ( sortList
.length
> 0 ) {
1044 sortList
= convertSortList( sortList
);
1047 // Set each column's sort count to be able to determine the correct sort
1048 // order when clicking on a header cell the next time
1049 setHeadersOrder( $headers
, sortList
, config
.headerToColumns
);
1051 // re-build the cache for the tbody cells
1052 cache
= buildCache( table
);
1054 // set css for headers
1055 setHeadersCss( table
, $headers
, sortList
, sortCSS
, sortMsg
, config
.columnToHeader
);
1057 // sort the table and append it to the dom
1058 appendToTable( table
, multisort( table
, sortList
, cache
) );
1062 if ( config
.sortList
.length
> 0 ) {
1063 config
.sortList
= convertSortList( config
.sortList
);
1064 $table
.data( 'tablesorter' ).sort();
1070 addParser: function ( parser
) {
1071 if ( !getParserById( parser
.id
) ) {
1072 parsers
.push( parser
);
1076 formatDigit: function ( s
) {
1078 if ( ts
.transformTable
!== false ) {
1080 for ( p
= 0; p
< s
.length
; p
++ ) {
1082 if ( c
in ts
.transformTable
) {
1083 out
+= ts
.transformTable
[ c
];
1090 i
= parseFloat( s
.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
1091 return isNaN( i
) ? -Infinity
: i
;
1094 formatFloat: function ( s
) {
1095 var i
= parseFloat( s
);
1096 return isNaN( i
) ? -Infinity
: i
;
1099 formatInt: function ( s
) {
1100 var i
= parseInt( s
, 10 );
1101 return isNaN( i
) ? -Infinity
: i
;
1104 clearTableBody: function ( table
) {
1105 $( table
.tBodies
[ 0 ] ).empty();
1108 getParser: function ( id
) {
1109 buildTransformTable();
1114 return getParserById( id
);
1117 getParsers: function () { // for table diagnosis
1125 // Register as jQuery prototype method
1126 $.fn
.tablesorter = function ( settings
) {
1127 return ts
.construct( this, settings
);
1130 // Add default parsers
1136 format: function ( s
) {
1139 if ( ts
.collationRegex
) {
1140 tsc
= ts
.collationTable
;
1141 s
= s
.replace( ts
.collationRegex
, function ( match
) {
1143 upper
= match
.toUpperCase(),
1144 lower
= match
.toLowerCase();
1145 if ( upper
=== match
&& !lower
=== match
) {
1146 r
= tsc
[ lower
] ? tsc
[ lower
] : tsc
[ upper
];
1147 r
= r
.toUpperCase();
1149 r
= tsc
[ match
.toLowerCase() ];
1161 is: function ( s
) {
1162 return ts
.rgx
.IPAddress
[ 0 ].test( s
);
1164 format: function ( s
) {
1168 for ( i
= 0; i
< a
.length
; i
++ ) {
1170 if ( item
.length
=== 1 ) {
1172 } else if ( item
.length
=== 2 ) {
1178 return $.tablesorter
.formatFloat( r
);
1185 is: function ( s
) {
1186 return ts
.rgx
.currency
[ 0 ].test( s
);
1188 format: function ( s
) {
1189 return $.tablesorter
.formatDigit( s
.replace( ts
.rgx
.currency
[ 1 ], '' ) );
1196 is: function ( s
) {
1197 return ts
.rgx
.url
[ 0 ].test( s
);
1199 format: function ( s
) {
1200 return s
.replace( ts
.rgx
.url
[ 1 ], '' ).trim();
1207 is: function ( s
) {
1208 return ts
.rgx
.isoDate
[ 0 ].test( s
);
1210 format: function ( s
) {
1211 var match
, i
, isodate
, ms
, hOffset
, mOffset
;
1212 match
= s
.match( ts
.rgx
.isoDate
[ 0 ] );
1213 if ( match
=== null ) {
1214 // Otherwise a signed number with 1-4 digit is parsed as isoDate
1215 match
= s
.match( ts
.rgx
.isoDate
[ 1 ] );
1221 for ( i
= 2; i
<= 4; i
+= 2 ) {
1222 if ( !match
[ i
] || match
[ i
].length
=== 0 ) {
1227 for ( i
= 6; i
<= 15; i
++ ) {
1228 if ( !match
[ i
] || match
[ i
].length
=== 0 ) {
1232 ms
= parseFloat( match
[ 11 ].replace( /,/, '.' ) ) * 1000;
1233 hOffset
= $.tablesorter
.formatInt( match
[ 13 ] + match
[ 14 ] );
1234 mOffset
= $.tablesorter
.formatInt( match
[ 13 ] + match
[ 15 ] );
1236 isodate
= new Date( 0 );
1237 // Because Date constructor changes year 0-99 to 1900-1999, use setUTCFullYear()
1238 isodate
.setUTCFullYear( match
[ 1 ], match
[ 2 ] - 1, match
[ 4 ] );
1239 isodate
.setUTCHours( match
[ 6 ] - hOffset
, match
[ 8 ] - mOffset
, match
[ 10 ], ms
);
1240 return isodate
.getTime();
1247 is: function ( s
) {
1248 return ts
.rgx
.usLongDate
[ 0 ].test( s
);
1250 format: function ( s
) {
1251 return $.tablesorter
.formatFloat( new Date( s
).getTime() );
1258 is: function ( s
) {
1259 return ( ts
.dateRegex
[ 0 ].test( s
) || ts
.dateRegex
[ 1 ].test( s
) || ts
.dateRegex
[ 2 ].test( s
) );
1261 format: function ( s
) {
1263 s
= s
.toLowerCase().trim();
1265 if ( ( match
= s
.match( ts
.dateRegex
[ 0 ] ) ) !== null ) {
1266 if ( mw
.config
.get( 'wgDefaultDateFormat' ) === 'mdy' || mw
.config
.get( 'wgPageContentLanguage' ) === 'en' ) {
1267 s
= [ match
[ 3 ], match
[ 1 ], match
[ 2 ] ];
1268 } else if ( mw
.config
.get( 'wgDefaultDateFormat' ) === 'dmy' ) {
1269 s
= [ match
[ 3 ], match
[ 2 ], match
[ 1 ] ];
1271 // If we get here, we don't know which order the dd-dd-dddd
1272 // date is in. So return something not entirely invalid.
1275 } else if ( ( match
= s
.match( ts
.dateRegex
[ 1 ] ) ) !== null ) {
1276 s
= [ match
[ 3 ], String( ts
.monthNames
[ match
[ 2 ] ] ), match
[ 1 ] ];
1277 } else if ( ( match
= s
.match( ts
.dateRegex
[ 2 ] ) ) !== null ) {
1278 s
= [ match
[ 3 ], String( ts
.monthNames
[ match
[ 1 ] ] ), match
[ 2 ] ];
1280 // Should never get here
1284 // Pad Month and Day
1285 if ( s
[ 1 ].length
=== 1 ) {
1286 s
[ 1 ] = '0' + s
[ 1 ];
1288 if ( s
[ 2 ].length
=== 1 ) {
1289 s
[ 2 ] = '0' + s
[ 2 ];
1292 if ( ( y
= parseInt( s
[ 0 ], 10 ) ) < 100 ) {
1293 // Guestimate years without centuries
1300 while ( s
[ 0 ].length
< 4 ) {
1301 s
[ 0 ] = '0' + s
[ 0 ];
1303 return parseInt( s
.join( '' ), 10 );
1310 is: function ( s
) {
1311 return ts
.rgx
.time
[ 0 ].test( s
);
1313 format: function ( s
) {
1314 return $.tablesorter
.formatFloat( new Date( '2000/01/01 ' + s
).getTime() );
1321 is: function ( s
) {
1322 return $.tablesorter
.numberRegex
.test( s
.trim() );
1324 format: function ( s
) {
1325 return $.tablesorter
.formatDigit( s
);