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 ts
.collator
.compare( a
, b
);
486 function sortNumeric( a
, b
) {
487 return ( ( a
< b
) ? -1 : ( ( a
> b
) ? 1 : 0 ) );
490 function multisort( table
, sortList
, cache
) {
493 parsers
= $( table
).data( 'tablesorter' ).config
.parsers
;
495 for ( i
= 0; i
< sortList
.length
; i
++ ) {
496 // Android doesn't support Intl.Collator
497 if ( window
.Intl
&& Intl
.Collator
&& parsers
[ sortList
[ i
][ 0 ] ].type
=== 'text' ) {
498 sortFn
[ i
] = sortText
;
500 sortFn
[ i
] = sortNumeric
;
503 cache
.normalized
.sort( function ( array1
, array2
) {
505 for ( i
= 0; i
< sortList
.length
; i
++ ) {
506 col
= sortList
[ i
][ 0 ];
507 if ( sortList
[ i
][ 1 ] ) {
509 ret
= sortFn
[ i
].call( this, array2
[ col
], array1
[ col
] );
512 ret
= sortFn
[ i
].call( this, array1
[ col
], array2
[ col
] );
518 // Fall back to index number column to ensure stable sort
519 return sortText
.call( this, array1
[ array1
.length
- 1 ], array2
[ array2
.length
- 1 ] );
524 function buildTransformTable() {
525 var ascii
, localised
, i
, digitClass
,
526 digits
= '0123456789,.'.split( '' ),
527 separatorTransformTable
= mw
.config
.get( 'wgSeparatorTransformTable' ),
528 digitTransformTable
= mw
.config
.get( 'wgDigitTransformTable' );
530 if ( separatorTransformTable
=== null || ( separatorTransformTable
[ 0 ] === '' && digitTransformTable
[ 2 ] === '' ) ) {
531 ts
.transformTable
= false;
533 ts
.transformTable
= {};
535 // Unpack the transform table
536 ascii
= separatorTransformTable
[ 0 ].split( '\t' ).concat( digitTransformTable
[ 0 ].split( '\t' ) );
537 localised
= separatorTransformTable
[ 1 ].split( '\t' ).concat( digitTransformTable
[ 1 ].split( '\t' ) );
539 // Construct regexes for number identification
540 for ( i
= 0; i
< ascii
.length
; i
++ ) {
541 ts
.transformTable
[ localised
[ i
] ] = ascii
[ i
];
542 digits
.push( mw
.RegExp
.escape( localised
[ i
] ) );
545 digitClass
= '[' + digits
.join( '', digits
) + ']';
547 // We allow a trailing percent sign, which we just strip. This works fine
548 // if percents and regular numbers aren't being mixed.
549 ts
.numberRegex
= new RegExp(
551 '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
553 '[-+\u2212]?' + digitClass
+ '+[\\s\\xa0]*%?' + // Generic localised
559 function buildDateTable() {
565 for ( i
= 0; i
< 12; i
++ ) {
566 name
= mw
.language
.months
.names
[ i
].toLowerCase();
567 ts
.monthNames
[ name
] = i
+ 1;
568 regex
.push( mw
.RegExp
.escape( name
) );
569 name
= mw
.language
.months
.genitive
[ i
].toLowerCase();
570 ts
.monthNames
[ name
] = i
+ 1;
571 regex
.push( mw
.RegExp
.escape( name
) );
572 name
= mw
.language
.months
.abbrev
[ i
].toLowerCase().replace( '.', '' );
573 ts
.monthNames
[ name
] = i
+ 1;
574 regex
.push( mw
.RegExp
.escape( name
) );
577 // Build piped string
578 regex
= regex
.join( '|' );
581 // Any date formated with . , ' - or /
582 ts
.dateRegex
[ 0 ] = new RegExp( /^\s*(\d{1,2})[,.\-/'\s]{1,2}(\d{1,2})[,.\-/'\s
]{1,2}(\d
{2,4})\s
*?/i
);
584 // Written Month name, dmy
585 ts
.dateRegex
[ 1 ] = new RegExp(
586 '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(' +
589 '[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$',
593 // Written Month name, mdy
594 ts
.dateRegex
[ 2 ] = new RegExp(
595 '^\\s*(' + regex
+ ')' +
596 '[\\,\\.\\-\\/\'\\s]+(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$',
603 * Replace all rowspanned cells in the body with clones in each row, so sorting
604 * need not worry about them.
606 * @param {jQuery} $table jQuery object for a <table>
608 function explodeRowspans( $table
) {
609 var spanningRealCellIndex
, rowSpan
, colSpan
,
610 cell
, cellData
, i
, $tds
, $clone
, $nextRows
,
611 rowspanCells
= $table
.find( '> tbody > tr > [rowspan]' ).get();
614 if ( !rowspanCells
.length
) {
618 // First, we need to make a property like cellIndex but taking into
619 // account colspans. We also cache the rowIndex to avoid having to take
620 // cell.parentNode.rowIndex in the sorting function below.
621 $table
.find( '> tbody > tr' ).each( function () {
624 len
= this.cells
.length
;
625 for ( i
= 0; i
< len
; i
++ ) {
626 $( this.cells
[ i
] ).data( 'tablesorter', {
628 realRowIndex
: this.rowIndex
630 col
+= this.cells
[ i
].colSpan
;
634 // Split multi row cells into multiple cells with the same content.
635 // Sort by column then row index to avoid problems with odd table structures.
636 // Re-sort whenever a rowspanned cell's realCellIndex is changed, because it
637 // might change the sort order.
638 function resortCells() {
642 rowspanCells
= rowspanCells
.sort( function ( a
, b
) {
643 cellAData
= $.data( a
, 'tablesorter' );
644 cellBData
= $.data( b
, 'tablesorter' );
645 ret
= cellAData
.realCellIndex
- cellBData
.realCellIndex
;
647 ret
= cellAData
.realRowIndex
- cellBData
.realRowIndex
;
651 rowspanCells
.forEach( function ( cell
) {
652 $.data( cell
, 'tablesorter' ).needResort
= false;
657 function filterfunc() {
658 return $.data( this, 'tablesorter' ).realCellIndex
>= spanningRealCellIndex
;
661 function fixTdCellIndex() {
662 $.data( this, 'tablesorter' ).realCellIndex
+= colSpan
;
663 if ( this.rowSpan
> 1 ) {
664 $.data( this, 'tablesorter' ).needResort
= true;
668 while ( rowspanCells
.length
) {
669 if ( $.data( rowspanCells
[ 0 ], 'tablesorter' ).needResort
) {
673 cell
= rowspanCells
.shift();
674 cellData
= $.data( cell
, 'tablesorter' );
675 rowSpan
= cell
.rowSpan
;
676 colSpan
= cell
.colSpan
;
677 spanningRealCellIndex
= cellData
.realCellIndex
;
679 $nextRows
= $( cell
).parent().nextAll();
680 for ( i
= 0; i
< rowSpan
- 1; i
++ ) {
681 $tds
= $( $nextRows
[ i
].cells
).filter( filterfunc
);
682 $clone
= $( cell
).clone();
683 $clone
.data( 'tablesorter', {
684 realCellIndex
: spanningRealCellIndex
,
685 realRowIndex
: cellData
.realRowIndex
+ i
,
689 $tds
.each( fixTdCellIndex
);
690 $tds
.first().before( $clone
);
692 $nextRows
.eq( i
).append( $clone
);
699 * Build index to handle colspanned cells in the body.
700 * Set the cell index for each column in an array,
701 * so that colspaned cells set multiple in this array.
702 * columnToCell[collumnIndex] point at the real cell in this row.
704 * @param {jQuery} $table object for a <table>
706 function manageColspans( $table
) {
708 $rows
= $table
.find( '> tbody > tr' ),
709 totalRows
= $rows
.length
|| 0,
710 config
= $table
.data( 'tablesorter' ).config
,
711 columns
= config
.columns
,
712 columnToCell
, cellsInRow
, index
;
714 for ( i
= 0; i
< totalRows
; i
++ ) {
716 $row
= $rows
.eq( i
);
717 // if this is a child row, continue to the next row (as buildCache())
718 if ( $row
.hasClass( config
.cssChildRow
) ) {
719 // go to the next for loop
724 cellsInRow
= ( $row
[ 0 ].cells
.length
) || 0; // all cells in this row
725 index
= 0; // real cell index in this row
726 for ( j
= 0; j
< columns
; index
++ ) {
727 if ( index
=== cellsInRow
) {
728 // Row with cells less than columns: add empty cell
729 $row
.append( '<td>' );
732 for ( k
= 0; k
< $row
[ 0 ].cells
[ index
].colSpan
; k
++ ) {
733 columnToCell
[ j
++ ] = index
;
737 $row
.data( 'columnToCell', columnToCell
);
741 function buildCollation() {
743 ts
.collationTable
= mw
.config
.get( 'tableSorterCollation' );
744 ts
.collationRegex
= null;
745 if ( ts
.collationTable
) {
746 // Build array of key names
747 for ( key
in ts
.collationTable
) {
748 keys
.push( mw
.RegExp
.escape( key
) );
751 ts
.collationRegex
= new RegExp( keys
.join( '|' ), 'ig' );
754 if ( window
.Intl
&& Intl
.Collator
) {
755 ts
.collator
= new Intl
.Collator( [
756 mw
.config
.get( 'wgPageContentLanguage' ),
757 mw
.config
.get( 'wgUserLanguage' )
764 function cacheRegexs() {
770 new RegExp( /^\d{1,3}[.]\d{1,3}[.]\d{1,3}[.]\d{1,3}$/ )
773 new RegExp( /(^[£$€¥]|[£$€¥]$)/ ),
774 new RegExp( /[£$€¥]/g )
777 new RegExp( /^(https?|ftp|file):\/\/$/ ),
778 new RegExp( /(https?|ftp|file):\/\// )
781 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)?)?)?/ ),
782 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)?)?)?/ )
785 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)))$/ )
788 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/ )
794 * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
795 * structure [ [ Integer, Integer ], ... ]
797 * @param {Array} sortObjects List of sort objects.
798 * @return {Array} List of internal sort definitions.
800 function convertSortList( sortObjects
) {
802 sortObjects
.forEach( function ( sortObject
) {
803 // eslint-disable-next-line no-jquery/no-each-util
804 $.each( sortObject
, function ( columnIndex
, order
) {
805 var orderIndex
= ( order
=== 'desc' ) ? 1 : 0;
806 sortList
.push( [ parseInt( columnIndex
, 10 ), orderIndex
] );
816 cssHeader
: 'headerSort',
817 cssAsc
: 'headerSortUp',
818 cssDesc
: 'headerSortDown',
819 cssChildRow
: 'expand-child',
820 sortMultiSortKey
: 'shiftKey',
821 unsortableClass
: 'unsortable',
823 cancelSelection
: true,
835 * @param {jQuery} $tables
836 * @param {Object} [settings]
839 construct: function ( $tables
, settings
) {
840 return $tables
.each( function ( i
, table
) {
841 // Declare and cache.
842 var $headers
, cache
, config
, sortCSS
, sortMsg
,
846 // Don't construct twice on the same table
847 if ( $.data( table
, 'tablesorter' ) ) {
851 if ( !table
.tBodies
) {
854 if ( !table
.tHead
) {
855 // No thead found. Look for rows with <th>s and
856 // move them into a <thead> tag or a <tfoot> tag
857 emulateTHeadAndFoot( $table
);
859 // Still no thead? Then quit
860 if ( !table
.tHead
) {
864 // The `sortable` class is used to identify tables which will become sortable
865 // If not used it will create a FOUC but it should be added since the sortable class
866 // is responsible for certain crucial style elements. If the class is already present
867 // this action will be harmless.
868 $table
.addClass( 'jquery-tablesorter sortable' );
871 config
= $.extend( {}, $.tablesorter
.defaultOptions
, settings
);
873 // Save the settings where they read
874 $.data( table
, 'tablesorter', { config
: config
} );
876 // Get the CSS class names, could be done elsewhere
877 sortCSS
= [ config
.cssAsc
, config
.cssDesc
];
878 // Messages tell the user what the *next* state will be
879 // so are in reverse order to the CSS classes.
880 sortMsg
= [ mw
.msg( 'sort-descending' ), mw
.msg( 'sort-ascending' ) ];
883 $headers
= buildHeaders( table
, sortMsg
);
885 // Grab and process locale settings.
886 buildTransformTable();
889 // Precaching regexps can bring 10 fold
890 // performance improvements in some browsers.
893 function setupForFirstSort() {
894 var $tfoot
, $sortbottoms
;
898 // Defer buildCollationTable to first sort. As user and site scripts
899 // may customize tableSorterCollation but load after $.ready(), other
900 // scripts may call .tablesorter() before they have done the
901 // tableSorterCollation customizations.
904 // Legacy fix of .sortbottoms
905 // Wrap them inside a tfoot (because that's what they actually want to be)
906 // and put the <tfoot> at the end of the <table>
907 $sortbottoms
= $table
.find( '> tbody > tr.sortbottom' );
908 if ( $sortbottoms
.length
) {
909 $tfoot
= $table
.children( 'tfoot' );
910 if ( $tfoot
.length
) {
911 $tfoot
.eq( 0 ).prepend( $sortbottoms
);
913 $table
.append( $( '<tfoot>' ).append( $sortbottoms
) );
917 explodeRowspans( $table
);
918 manageColspans( $table
);
920 // Try to auto detect column type, and store in tables config
921 config
.parsers
= buildParserCache( table
, $headers
);
924 // Apply event handling to headers
925 // this is too big, perhaps break it out?
926 $headers
.on( 'keypress click', function ( e
) {
927 var cell
, $cell
, columns
, newSortList
, i
,
931 if ( e
.type
=== 'click' && e
.target
.nodeName
.toLowerCase() === 'a' ) {
932 // The user clicked on a link inside a table header.
933 // Do nothing and let the default link click action continue.
937 if ( e
.type
=== 'keypress' && e
.which
!== 13 ) {
938 // Only handle keypresses on the "Enter" key.
946 // Build the cache for the tbody cells
947 // to share between calculations for this sort action.
948 // Re-calculated each time a sort action is performed due to possibility
949 // that sort values change. Shouldn't be too expensive, but if it becomes
950 // too slow an event based system should be implemented somehow where
951 // cells get event .change() and bubbles up to the <table> here
952 cache
= buildCache( table
);
954 totalRows
= ( $table
[ 0 ].tBodies
[ 0 ] && $table
[ 0 ].tBodies
[ 0 ].rows
.length
) || 0;
955 if ( totalRows
> 0 ) {
959 // Get current column sort order
961 order
: $cell
.data( 'count' ) % 2,
962 count
: $cell
.data( 'count' ) + 1
966 // Get current column index
967 columns
= config
.headerToColumns
[ $cell
.data( 'headerIndex' ) ];
968 newSortList
= columns
.map( function ( c
) {
969 return [ c
, $cell
.data( 'order' ) ];
971 // Index of first column belonging to this header
974 if ( !e
[ config
.sortMultiSortKey
] ) {
975 // User only wants to sort on one column set
976 // Flush the sort list and add new columns
977 config
.sortList
= newSortList
;
979 // Multi column sorting
980 // It is not possible for one column to belong to multiple headers,
981 // so this is okay - we don't need to check for every value in the columns array
982 if ( isValueInArray( i
, config
.sortList
) ) {
983 // The user has clicked on an already sorted column.
984 // Reverse the sorting direction for all tables.
985 for ( j
= 0; j
< config
.sortList
.length
; j
++ ) {
986 s
= config
.sortList
[ j
];
987 o
= config
.headerList
[ config
.columnToHeader
[ s
[ 0 ] ] ];
988 if ( isValueInArray( s
[ 0 ], newSortList
) ) {
989 $( o
).data( 'count', s
[ 1 ] + 1 );
990 s
[ 1 ] = $( o
).data( 'count' ) % 2;
994 // Add columns to sort list array
995 config
.sortList
= config
.sortList
.concat( newSortList
);
999 // Reset order/counts of cells not affected by sorting
1000 setHeadersOrder( $headers
, config
.sortList
, config
.headerToColumns
);
1002 // Set CSS for headers
1003 setHeadersCss( $table
[ 0 ], $headers
, config
.sortList
, sortCSS
, sortMsg
, config
.columnToHeader
);
1005 $table
[ 0 ], multisort( $table
[ 0 ], config
.sortList
, cache
)
1008 // Stop normal event by returning false
1013 } ).on( 'mousedown', function () {
1014 if ( config
.cancelSelection
) {
1015 this.onselectstart = function () {
1023 * Sorts the table. If no sorting is specified by passing a list of sort
1024 * objects, the table is sorted according to the initial sorting order.
1025 * Passing an empty array will reset sorting (basically just reset the headers
1026 * making the table appear unsorted).
1028 * @param {Array} [sortList] List of sort objects.
1030 $table
.data( 'tablesorter' ).sort = function ( sortList
) {
1033 setupForFirstSort();
1036 if ( sortList
=== undefined ) {
1037 sortList
= config
.sortList
;
1038 } else if ( sortList
.length
> 0 ) {
1039 sortList
= convertSortList( sortList
);
1042 // Set each column's sort count to be able to determine the correct sort
1043 // order when clicking on a header cell the next time
1044 setHeadersOrder( $headers
, sortList
, config
.headerToColumns
);
1046 // re-build the cache for the tbody cells
1047 cache
= buildCache( table
);
1049 // set css for headers
1050 setHeadersCss( table
, $headers
, sortList
, sortCSS
, sortMsg
, config
.columnToHeader
);
1052 // sort the table and append it to the dom
1053 appendToTable( table
, multisort( table
, sortList
, cache
) );
1057 if ( config
.sortList
.length
> 0 ) {
1058 config
.sortList
= convertSortList( config
.sortList
);
1059 $table
.data( 'tablesorter' ).sort();
1065 addParser: function ( parser
) {
1066 if ( !getParserById( parser
.id
) ) {
1067 parsers
.push( parser
);
1071 formatDigit: function ( s
) {
1073 if ( ts
.transformTable
!== false ) {
1075 for ( p
= 0; p
< s
.length
; p
++ ) {
1077 if ( c
in ts
.transformTable
) {
1078 out
+= ts
.transformTable
[ c
];
1085 i
= parseFloat( s
.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
1086 return isNaN( i
) ? -Infinity
: i
;
1089 formatFloat: function ( s
) {
1090 var i
= parseFloat( s
);
1091 return isNaN( i
) ? -Infinity
: i
;
1094 formatInt: function ( s
) {
1095 var i
= parseInt( s
, 10 );
1096 return isNaN( i
) ? -Infinity
: i
;
1099 clearTableBody: function ( table
) {
1100 $( table
.tBodies
[ 0 ] ).empty();
1103 getParser: function ( id
) {
1104 buildTransformTable();
1109 return getParserById( id
);
1112 getParsers: function () { // for table diagnosis
1120 // Register as jQuery prototype method
1121 $.fn
.tablesorter = function ( settings
) {
1122 return ts
.construct( this, settings
);
1125 // Add default parsers
1131 format: function ( s
) {
1134 if ( ts
.collationRegex
) {
1135 tsc
= ts
.collationTable
;
1136 s
= s
.replace( ts
.collationRegex
, function ( match
) {
1138 upper
= match
.toUpperCase(),
1139 lower
= match
.toLowerCase();
1140 if ( upper
=== match
&& !lower
=== match
) {
1141 r
= tsc
[ lower
] ? tsc
[ lower
] : tsc
[ upper
];
1142 r
= r
.toUpperCase();
1144 r
= tsc
[ match
.toLowerCase() ];
1156 is: function ( s
) {
1157 return ts
.rgx
.IPAddress
[ 0 ].test( s
);
1159 format: function ( s
) {
1163 for ( i
= 0; i
< a
.length
; i
++ ) {
1165 if ( item
.length
=== 1 ) {
1167 } else if ( item
.length
=== 2 ) {
1173 return $.tablesorter
.formatFloat( r
);
1180 is: function ( s
) {
1181 return ts
.rgx
.currency
[ 0 ].test( s
);
1183 format: function ( s
) {
1184 return $.tablesorter
.formatDigit( s
.replace( ts
.rgx
.currency
[ 1 ], '' ) );
1191 is: function ( s
) {
1192 return ts
.rgx
.url
[ 0 ].test( s
);
1194 format: function ( s
) {
1195 return s
.replace( ts
.rgx
.url
[ 1 ], '' ).trim();
1202 is: function ( s
) {
1203 return ts
.rgx
.isoDate
[ 0 ].test( s
);
1205 format: function ( s
) {
1206 var match
, i
, isodate
, ms
, hOffset
, mOffset
;
1207 match
= s
.match( ts
.rgx
.isoDate
[ 0 ] );
1208 if ( match
=== null ) {
1209 // Otherwise a signed number with 1-4 digit is parsed as isoDate
1210 match
= s
.match( ts
.rgx
.isoDate
[ 1 ] );
1216 for ( i
= 2; i
<= 4; i
+= 2 ) {
1217 if ( !match
[ i
] || match
[ i
].length
=== 0 ) {
1222 for ( i
= 6; i
<= 15; i
++ ) {
1223 if ( !match
[ i
] || match
[ i
].length
=== 0 ) {
1227 ms
= parseFloat( match
[ 11 ].replace( /,/, '.' ) ) * 1000;
1228 hOffset
= $.tablesorter
.formatInt( match
[ 13 ] + match
[ 14 ] );
1229 mOffset
= $.tablesorter
.formatInt( match
[ 13 ] + match
[ 15 ] );
1231 isodate
= new Date( 0 );
1232 // Because Date constructor changes year 0-99 to 1900-1999, use setUTCFullYear()
1233 isodate
.setUTCFullYear( match
[ 1 ], match
[ 2 ] - 1, match
[ 4 ] );
1234 isodate
.setUTCHours( match
[ 6 ] - hOffset
, match
[ 8 ] - mOffset
, match
[ 10 ], ms
);
1235 return isodate
.getTime();
1242 is: function ( s
) {
1243 return ts
.rgx
.usLongDate
[ 0 ].test( s
);
1245 format: function ( s
) {
1246 return $.tablesorter
.formatFloat( new Date( s
).getTime() );
1253 is: function ( s
) {
1254 return ( ts
.dateRegex
[ 0 ].test( s
) || ts
.dateRegex
[ 1 ].test( s
) || ts
.dateRegex
[ 2 ].test( s
) );
1256 format: function ( s
) {
1258 s
= s
.toLowerCase().trim();
1260 if ( ( match
= s
.match( ts
.dateRegex
[ 0 ] ) ) !== null ) {
1261 if ( mw
.config
.get( 'wgDefaultDateFormat' ) === 'mdy' || mw
.config
.get( 'wgPageContentLanguage' ) === 'en' ) {
1262 s
= [ match
[ 3 ], match
[ 1 ], match
[ 2 ] ];
1263 } else if ( mw
.config
.get( 'wgDefaultDateFormat' ) === 'dmy' ) {
1264 s
= [ match
[ 3 ], match
[ 2 ], match
[ 1 ] ];
1266 // If we get here, we don't know which order the dd-dd-dddd
1267 // date is in. So return something not entirely invalid.
1270 } else if ( ( match
= s
.match( ts
.dateRegex
[ 1 ] ) ) !== null ) {
1271 s
= [ match
[ 3 ], String( ts
.monthNames
[ match
[ 2 ] ] ), match
[ 1 ] ];
1272 } else if ( ( match
= s
.match( ts
.dateRegex
[ 2 ] ) ) !== null ) {
1273 s
= [ match
[ 3 ], String( ts
.monthNames
[ match
[ 1 ] ] ), match
[ 2 ] ];
1275 // Should never get here
1279 // Pad Month and Day
1280 if ( s
[ 1 ].length
=== 1 ) {
1281 s
[ 1 ] = '0' + s
[ 1 ];
1283 if ( s
[ 2 ].length
=== 1 ) {
1284 s
[ 2 ] = '0' + s
[ 2 ];
1287 if ( ( y
= parseInt( s
[ 0 ], 10 ) ) < 100 ) {
1288 // Guestimate years without centuries
1295 while ( s
[ 0 ].length
< 4 ) {
1296 s
[ 0 ] = '0' + s
[ 0 ];
1298 return parseInt( s
.join( '' ), 10 );
1305 is: function ( s
) {
1306 return ts
.rgx
.time
[ 0 ].test( s
);
1308 format: function ( s
) {
1309 return $.tablesorter
.formatFloat( new Date( '2000/01/01 ' + s
).getTime() );
1316 is: function ( s
) {
1317 return $.tablesorter
.numberRegex
.test( s
.trim() );
1319 format: function ( s
) {
1320 return $.tablesorter
.formatDigit( s
);