2 * Provides a {@link jQuery} plugin that creates a sortable table.
4 * Depends on mw.config (wgDigitTransformTable, wgDefaultDateFormat, wgPageViewLanguage)
5 * and {@link mw.language.months}.
7 * Uses 'tableSorterCollation' in {@link mw.config} (if available).
9 * @module jquery.tablesorter
10 * @author Written 2011 Leo Koppelkamm. Based on tablesorter.com plugin, written (c) 2007 Christian Bach/christian.bach@polyester.se
11 * @license Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL (http://www.gnu.org/licenses/gpl.html) licenses
14 * @typedef {Object} module:jquery.tablesorter~TableSorterOptions
15 * @property {string} [cssHeader="headerSort"] A string of the class name to be appended to sortable
16 * tr elements in the thead of the table.
17 * @property {string} [cssAsc="headerSortUp"] A string of the class name to be appended to
18 * sortable tr elements in the thead on a ascending sort.
19 * @property {string} [cssDesc="headerSortDown"] A string of the class name to be appended to
20 * sortable tr elements in the thead on a descending sort.
21 * @property {string} [sortMultisortKey="shiftKey"] A string of the multi-column sort key.
22 * @property {boolean} [cancelSelection=true] Boolean flag indicating iftablesorter should cancel
23 * selection of the table headers text.
24 * @property {Array} [sortList] An array containing objects specifying sorting. By passing more
25 * than one object, multi-sorting will be applied. Object structure:
26 * { <Integer column index>: <String 'asc' or 'desc'> }
32 /* Parser utility functions */
34 function getParserById( name ) {
35 for ( let i = 0; i < parsers.length; i++ ) {
36 if ( parsers[ i ].id.toLowerCase() === name.toLowerCase() ) {
44 * @param {HTMLElement} node
47 function getElementSortKey( node ) {
48 // Browse the node to build the raw sort key, which will then be normalized.
49 function buildRawSortKey( currentNode ) {
50 // Get data-sort-value attribute. Uses jQuery to allow live value
51 // changes from other code paths via data(), which reside only in jQuery.
52 // Must use $().data() instead of $.data(), as the latter *only*
53 // accesses the live values, without reading HTML5 attribs first (T40152).
54 const data = $( currentNode ).data( 'sortValue' );
56 if ( data !== null && data !== undefined ) {
57 // Cast any numbers or other stuff to a string. Methods
58 // like charAt, toLowerCase and split are expected in callers.
59 return String( data );
62 // Iterate the NodeList (not an array).
63 // Also uses null-return as filter in the same pass.
64 // eslint-disable-next-line no-jquery/no-map-util
65 return $.map( currentNode.childNodes, ( elem ) => {
66 if ( elem.nodeType === Node.ELEMENT_NODE ) {
67 const nodeName = elem.nodeName.toLowerCase();
68 if ( nodeName === 'img' ) {
71 if ( nodeName === 'br' ) {
74 if ( nodeName === 'style' ) {
77 if ( elem.classList.contains( 'reference' ) ) {
80 return buildRawSortKey( elem );
82 if ( elem.nodeType === Node.TEXT_NODE ) {
83 return elem.textContent;
85 // Ignore other node types, such as HTML comments.
90 return buildRawSortKey( node ).replace( / +/g, ' ' ).trim();
93 function detectParserForColumn( table, rows, column ) {
94 const l = parsers.length,
95 config = $( table ).data( 'tablesorter' ).config,
96 needed = ( rows.length > 4 ) ? 5 : rows.length;
97 // Start with 1 because 0 is the fallback parser
107 // if this is a child row, continue to the next row (as buildCache())
108 // eslint-disable-next-line no-jquery/no-class-state
109 if ( rows[ rowIndex ] && !$( rows[ rowIndex ] ).hasClass( config.cssChildRow ) ) {
110 if ( rowIndex !== lastRowIndex ) {
111 lastRowIndex = rowIndex;
112 const cellIndex = $( rows[ rowIndex ] ).data( 'columnToCell' )[ column ];
113 nodeValue = getElementSortKey( rows[ rowIndex ].cells[ cellIndex ] );
119 if ( nodeValue !== '' ) {
120 if ( parsers[ i ].is( nodeValue, table ) ) {
123 if ( concurrent >= needed ) {
124 // Confirmed the parser for multiple cells, let's return it
128 // Check next parser, reset rows
144 if ( rowIndex >= rows.length ) {
145 if ( concurrent > 0 && concurrent >= rows.length - empty ) {
146 // Confirmed the parser for all filled cells
149 // Check next parser, reset rows
158 // 0 is always the generic parser (text)
162 function buildParserCache( table, $headers ) {
163 const rows = table.tBodies[ 0 ].rows,
164 config = $( table ).data( 'tablesorter' ).config,
168 for ( let j = 0; j < config.columns; j++ ) {
170 const sortType = $headers.eq( config.columnToHeader[ j ] ).data( 'sortType' );
171 if ( sortType !== undefined ) {
172 // Cast any numbers or other stuff to a string. Methods
173 // like charAt, toLowerCase and split are expected in callers.
174 parser = getParserById( String( sortType ) );
177 if ( parser === false ) {
178 parser = detectParserForColumn( table, rows, j );
181 cachedParsers.push( parser );
184 return cachedParsers;
187 /* Other utility functions */
189 function buildCache( table ) {
190 const totalRows = ( table.tBodies[ 0 ] && table.tBodies[ 0 ].rows.length ) || 0,
191 config = $( table ).data( 'tablesorter' ).config,
192 cachedParsers = config.parsers,
198 for ( let i = 0; i < totalRows; i++ ) {
200 // Add the table data to main data array
201 const $row = $( table.tBodies[ 0 ].rows[ i ] );
204 // if this is a child row, add it to the last row's children and
205 // continue to the next row
206 // eslint-disable-next-line no-jquery/no-class-state
207 if ( $row.hasClass( config.cssChildRow ) ) {
208 cache.row[ cache.row.length - 1 ] = cache.row[ cache.row.length - 1 ].add( $row );
209 // go to the next for loop
213 cache.row.push( $row );
215 if ( $row.data( 'initialOrder' ) === undefined ) {
216 $row.data( 'initialOrder', i );
219 for ( let j = 0; j < cachedParsers.length; j++ ) {
220 const cellIndex = $row.data( 'columnToCell' )[ j ];
221 cols.push( cachedParsers[ j ].format( getElementSortKey( $row[ 0 ].cells[ cellIndex ] ) ) );
224 // Store the initial sort order, from when the page was loaded
225 cols.push( $row.data( 'initialOrder' ) );
227 // Store the current sort order, before rows are re-sorted
228 cols.push( cache.normalized.length );
230 cache.normalized.push( cols );
237 function appendToTable( table, cache ) {
238 const row = cache.row,
239 normalized = cache.normalized,
240 totalRows = normalized.length,
241 checkCell = ( normalized[ 0 ].length - 1 ),
242 fragment = document.createDocumentFragment();
244 for ( let i = 0; i < totalRows; i++ ) {
245 const pos = normalized[ i ][ checkCell ];
247 const l = row[ pos ].length;
248 for ( let j = 0; j < l; j++ ) {
249 fragment.appendChild( row[ pos ][ j ] );
253 table.tBodies[ 0 ].appendChild( fragment );
255 $( table ).trigger( 'sortEnd.tablesorter' );
259 * Find all header rows in a thead-less table and put them in a <thead> tag.
260 * This only treats a row as a header row if it contains only <th>s (no <td>s)
261 * and if it is preceded entirely by header rows. The algorithm stops when
262 * it encounters the first non-header row.
264 * After this, it will look at all rows at the bottom for footer rows
265 * And place these in a tfoot using similar rules.
267 * @param {jQuery} $table object for a <table>
269 function emulateTHeadAndFoot( $table ) {
270 const $rows = $table.find( '> tbody > tr' );
272 if ( !$table.get( 0 ).tHead ) {
273 const $thead = $( '<thead>' );
274 $rows.each( function () {
275 if ( $( this ).children( 'td' ).length ) {
276 // This row contains a <td>, so it's not a header row
280 $thead.append( this );
282 $table.find( '> tbody' ).first().before( $thead );
284 if ( !$table.get( 0 ).tFoot ) {
285 const $tfoot = $( '<tfoot>' );
287 remainingCellRowSpan = 0;
289 $rows.each( function () {
290 $( this ).children( 'td' ).each( function () {
291 remainingCellRowSpan = Math.max( this.rowSpan, remainingCellRowSpan );
294 if ( remainingCellRowSpan > 0 ) {
296 remainingCellRowSpan--;
298 tfootRows.push( this );
302 $tfoot.append( tfootRows );
303 $table.append( $tfoot );
307 function uniqueElements( array ) {
309 array.forEach( ( elem ) => {
310 if ( elem !== undefined && uniques.indexOf( elem ) === -1 ) {
311 uniques.push( elem );
317 function buildHeaders( table, msg ) {
318 const config = $( table ).data( 'tablesorter' ).config,
319 $tableRows = $( table ).find( 'thead' ).eq( 0 ).find( '> tr:not(.sorttop)' );
320 let $tableHeaders = $( [] );
325 if ( $tableRows.length <= 1 ) {
326 $tableHeaders = $tableRows.children( 'th' );
330 // Loop through all the dom cells of the thead
331 $tableRows.each( ( rowIndex, row ) => {
332 // eslint-disable-next-line no-jquery/no-each-util
333 $.each( row.cells, ( columnIndex, cell ) => {
334 const rowspan = Number( cell.rowSpan );
335 const colspan = Number( cell.colSpan );
337 // Skip the spots in the exploded matrix that are already filled
338 while ( exploded[ rowIndex ] && exploded[ rowIndex ][ columnIndex ] !== undefined ) {
344 // Find the actual dimensions of the thead, by placing each cell
345 // in the exploded matrix rowspan times colspan times, with the proper offsets
346 for ( matrixColumnIndex = columnIndex; matrixColumnIndex < columnIndex + colspan; ++matrixColumnIndex ) {
347 for ( matrixRowIndex = rowIndex; matrixRowIndex < rowIndex + rowspan; ++matrixRowIndex ) {
348 if ( !exploded[ matrixRowIndex ] ) {
349 exploded[ matrixRowIndex ] = [];
351 exploded[ matrixRowIndex ][ matrixColumnIndex ] = cell;
357 // We want to find the row that has the most columns (ignoring colspan)
358 exploded.forEach( ( cellArray, index ) => {
359 const headerCount = $( uniqueElements( cellArray ) ).filter( 'th' ).length;
360 if ( headerCount >= maxSeen ) {
361 maxSeen = headerCount;
365 // We cannot use $.unique() here because it sorts into dom order, which is undesirable
366 $tableHeaders = $( uniqueElements( exploded[ longestTR ] ) ).filter( 'th' );
369 // as each header can span over multiple columns (using colspan=N),
370 // we have to bidirectionally map headers to their columns and columns to their headers
371 config.columnToHeader = [];
372 config.headerToColumns = [];
373 config.headerList = [];
375 $tableHeaders.each( function () {
376 const $cell = $( this );
379 // eslint-disable-next-line no-jquery/no-class-state
380 if ( !$cell.hasClass( config.unsortableClass ) ) {
382 // The following classes are used here:
384 // * other passed by config
385 .addClass( config.cssHeader )
386 .prop( 'tabIndex', 0 )
388 role: 'columnheader button',
392 for ( let k = 0; k < this.colSpan; k++ ) {
393 config.columnToHeader[ colspanOffset + k ] = headerIndex;
394 columns.push( colspanOffset + k );
397 config.headerToColumns[ headerIndex ] = columns;
400 headerIndex: headerIndex,
405 // add only sortable cells to headerList
406 config.headerList[ headerIndex ] = this;
410 colspanOffset += this.colSpan;
413 // number of columns with extended colspan, inclusive unsortable
414 // parsers[j], cache[][j], columnToHeader[j], columnToCell[j] have so many elements
415 config.columns = colspanOffset;
417 return $tableHeaders.not( '.' + config.unsortableClass );
420 function isValueInArray( v, a ) {
421 for ( let i = 0; i < a.length; i++ ) {
422 if ( a[ i ][ 0 ] === v ) {
430 * Sets the sort count of the columns that are not affected by the sorting to have them sorted
431 * in default (ascending) order when their header cell is clicked the next time.
433 * @param {jQuery} $headers
434 * @param {Array} sortList 2D number array
435 * @param {Array} headerToColumns 2D number array
437 function setHeadersOrder( $headers, sortList, headerToColumns ) {
438 // Loop through all headers to retrieve the indices of the columns the header spans across:
439 headerToColumns.forEach( ( columns, headerIndex ) => {
441 columns.forEach( ( columnIndex, i ) => {
442 const 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 ( let j = 0; j < sortList.length; j++ ) {
454 const 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 ) {
470 // Remove all header information and reset titles to default message
471 // The following classes are used here:
474 $headers.removeClass( css ).attr( 'title', msg[ 2 ] );
476 for ( let i = 0; i < list.length; i++ ) {
477 // The following classes are used here:
481 .eq( columnToHeader[ list[ i ][ 0 ] ] )
482 .addClass( css[ list[ i ][ 1 ] ] )
483 .attr( 'title', msg[ list[ i ][ 1 ] ] );
487 function sortText( a, b ) {
488 return ts.collator.compare( a, b );
491 function sortNumeric( a, b ) {
492 return ( ( a < b ) ? -1 : ( ( a > b ) ? 1 : 0 ) );
495 function multisort( table, sortList, cache ) {
497 cachedParsers = $( table ).data( 'tablesorter' ).config.parsers;
499 for ( let i = 0; i < sortList.length; i++ ) {
500 // Android doesn't support Intl.Collator
501 if ( window.Intl && Intl.Collator && cachedParsers[ sortList[ i ][ 0 ] ].type === 'text' ) {
502 sortFn[ i ] = sortText;
504 sortFn[ i ] = sortNumeric;
507 cache.normalized.sort( function ( array1, array2 ) {
508 for ( let n = 0; n < sortList.length; n++ ) {
509 const col = sortList[ n ][ 0 ];
511 if ( sortList[ n ][ 1 ] === 2 ) {
513 const orderIndex = array1.length - 2;
514 ret = sortNumeric.call( this, array1[ orderIndex ], array2[ orderIndex ] );
515 } else if ( sortList[ n ][ 1 ] === 1 ) {
517 ret = sortFn[ n ].call( this, array2[ col ], array1[ col ] );
520 ret = sortFn[ n ].call( this, array1[ col ], array2[ col ] );
526 // Fall back to index number column to ensure stable sort
527 return sortText.call( this, array1[ array1.length - 1 ], array2[ array2.length - 1 ] );
532 function buildTransformTable() {
533 const digits = '0123456789,.'.split( '' ),
534 separatorTransformTable = mw.config.get( 'wgSeparatorTransformTable' ),
535 digitTransformTable = mw.config.get( 'wgDigitTransformTable' );
537 if ( separatorTransformTable === null || ( separatorTransformTable[ 0 ] === '' && digitTransformTable[ 2 ] === '' ) ) {
538 ts.transformTable = false;
540 ts.transformTable = {};
542 // Unpack the transform table
543 const ascii = separatorTransformTable[ 0 ].split( '\t' ).concat( digitTransformTable[ 0 ].split( '\t' ) );
544 const localised = separatorTransformTable[ 1 ].split( '\t' ).concat( digitTransformTable[ 1 ].split( '\t' ) );
546 // Construct regexes for number identification
547 for ( let i = 0; i < ascii.length; i++ ) {
548 ts.transformTable[ localised[ i ] ] = ascii[ i ];
549 digits.push( mw.util.escapeRegExp( localised[ i ] ) );
552 const digitClass = '[' + digits.join( '', digits ) + ']';
554 // We allow a trailing percent sign, which we just strip. This works fine
555 // if percents and regular numbers aren't being mixed.
557 ts.numberRegex = new RegExp(
559 '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
561 '[-+\u2212]?' + digitClass + '+[\\s\\xa0]*%?' + // Generic localised
567 function buildDateTable() {
572 for ( let i = 0; i < 12; i++ ) {
573 let name = mw.language.months.names[ i ].toLowerCase();
574 ts.monthNames[ name ] = i + 1;
575 regex.push( mw.util.escapeRegExp( name ) );
576 name = mw.language.months.genitive[ i ].toLowerCase();
577 ts.monthNames[ name ] = i + 1;
578 regex.push( mw.util.escapeRegExp( name ) );
579 name = mw.language.months.abbrev[ i ].toLowerCase().replace( '.', '' );
580 ts.monthNames[ name ] = i + 1;
581 regex.push( mw.util.escapeRegExp( name ) );
584 // Build piped string
585 regex = regex.join( '|' );
588 // Any date formated with . , ' - or /
589 ts.dateRegex[ 0 ] = new RegExp( /^\s*(\d{1,2})[,.\-/'\s]{1,2}(\d{1,2})[,.\-/'\s]{1,2}(\d{2,4})\s*?/i );
591 // Written Month name, dmy
593 ts.dateRegex[ 1 ] = new RegExp(
594 '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'º\\s]+(' +
597 '[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$',
601 // Written Month name, mdy
603 ts.dateRegex[ 2 ] = new RegExp(
604 '^\\s*(' + regex + ')' +
605 '[\\,\\.\\-\\/\'\\s]+(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$',
612 * Replace all rowspanned cells in the body with clones in each row, so sorting
613 * need not worry about them.
615 * @param {jQuery} $table jQuery object for a <table>
617 function explodeRowspans( $table ) {
618 let spanningRealCellIndex, colSpan,
619 rowspanCells = $table.find( '> tbody > tr > [rowspan]' ).get();
622 if ( !rowspanCells.length ) {
626 // First, we need to make a property like cellIndex but taking into
627 // account colspans. We also cache the rowIndex to avoid having to take
628 // cell.parentNode.rowIndex in the sorting function below.
629 $table.find( '> tbody > tr' ).each( function () {
631 for ( let c = 0; c < this.cells.length; c++ ) {
632 $( this.cells[ c ] ).data( 'tablesorter', {
634 realRowIndex: this.rowIndex
636 col += this.cells[ c ].colSpan;
640 // Split multi row cells into multiple cells with the same content.
641 // Sort by column then row index to avoid problems with odd table structures.
642 // Re-sort whenever a rowspanned cell's realCellIndex is changed, because it
643 // might change the sort order.
644 function resortCells() {
645 rowspanCells = rowspanCells.sort( ( a, b ) => {
646 const cellAData = $.data( a, 'tablesorter' );
647 const cellBData = $.data( b, 'tablesorter' );
648 let ret = cellAData.realCellIndex - cellBData.realCellIndex;
650 ret = cellAData.realRowIndex - cellBData.realRowIndex;
654 rowspanCells.forEach( ( cellNode ) => {
655 $.data( cellNode, 'tablesorter' ).needResort = false;
660 function filterfunc() {
661 return $.data( this, 'tablesorter' ).realCellIndex >= spanningRealCellIndex;
664 function fixTdCellIndex() {
665 $.data( this, 'tablesorter' ).realCellIndex += colSpan;
666 if ( this.rowSpan > 1 ) {
667 $.data( this, 'tablesorter' ).needResort = true;
671 while ( rowspanCells.length ) {
672 if ( $.data( rowspanCells[ 0 ], 'tablesorter' ).needResort ) {
676 const cell = rowspanCells.shift();
677 const cellData = $.data( cell, 'tablesorter' );
678 const rowSpan = cell.rowSpan;
679 colSpan = cell.colSpan;
680 spanningRealCellIndex = cellData.realCellIndex;
682 const $nextRows = $( cell ).parent().nextAll();
684 for ( let i = 0; i < rowSpan - 1; i++ ) {
685 const row = $nextRows[ i ];
687 // Badly formatted HTML for table.
688 // Ignore this row, but leave a warning for someone to be able to find this.
689 // Perhaps in future this could be a wikitext linter rule, or preview warning
691 mw.log.warn( mw.message( 'sort-rowspan-error' ).plain() );
694 const $tds = $( row.cells ).filter( filterfunc );
695 const $clone = $( cell ).clone();
696 $clone.data( 'tablesorter', {
697 realCellIndex: spanningRealCellIndex,
698 realRowIndex: cellData.realRowIndex + i,
702 $tds.each( fixTdCellIndex );
703 $tds.first().before( $clone );
705 $nextRows.eq( i ).append( $clone );
712 * Build index to handle colspanned cells in the body.
713 * Set the cell index for each column in an array,
714 * so that colspaned cells set multiple in this array.
715 * columnToCell[collumnIndex] point at the real cell in this row.
717 * @param {jQuery} $table object for a <table>
719 function manageColspans( $table ) {
720 const $rows = $table.find( '> tbody > tr' ),
721 totalRows = $rows.length || 0,
722 config = $table.data( 'tablesorter' ).config,
723 columns = config.columns;
725 for ( let i = 0; i < totalRows; i++ ) {
727 const $row = $rows.eq( i );
728 // if this is a child row, continue to the next row (as buildCache())
729 // eslint-disable-next-line no-jquery/no-class-state
730 if ( $row.hasClass( config.cssChildRow ) ) {
731 // go to the next for loop
735 const columnToCell = [];
736 let cellsInRow = ( $row[ 0 ].cells.length ) || 0; // all cells in this row
737 let index = 0; // real cell index in this row
738 for ( let j = 0; j < columns; index++ ) {
739 if ( index === cellsInRow ) {
740 // Row with cells less than columns: add empty cell
741 $row.append( '<td>' );
744 for ( let k = 0; k < $row[ 0 ].cells[ index ].colSpan; k++ ) {
745 columnToCell[ j++ ] = index;
749 $row.data( 'columnToCell', columnToCell );
753 function buildCollation() {
755 ts.collationTable = mw.config.get( 'tableSorterCollation' );
756 ts.collationRegex = null;
757 if ( ts.collationTable ) {
758 // Build array of key names
759 for ( const key in ts.collationTable ) {
760 keys.push( mw.util.escapeRegExp( key ) );
764 ts.collationRegex = new RegExp( keys.join( '|' ), 'ig' );
767 if ( window.Intl && Intl.Collator ) {
768 ts.collator = new Intl.Collator( [
769 mw.config.get( 'wgPageViewLanguage' ),
770 mw.config.get( 'wgUserLanguage' )
777 function cacheRegexs() {
783 new RegExp( /^\d{1,3}[.]\d{1,3}[.]\d{1,3}[.]\d{1,3}$/ )
786 new RegExp( /(^[£$€¥]|[£$€¥]$)/ ),
787 new RegExp( /[£$€¥]/g )
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( ( sortObject ) => {
808 // eslint-disable-next-line no-jquery/no-each-util
809 $.each( sortObject, ( columnIndex, order ) => {
810 const orderIndex = ( order === 'desc' ) ? 1 : 0;
811 sortList.push( [ parseInt( columnIndex, 10 ), orderIndex ] );
821 cssHeader: 'headerSort',
822 cssAsc: 'headerSortUp',
823 cssDesc: 'headerSortDown',
825 cssChildRow: 'expand-child',
826 sortMultiSortKey: 'shiftKey',
827 unsortableClass: 'unsortable',
829 cancelSelection: true,
841 * @param {jQuery} $tables
842 * @param {Object} [settings]
845 construct: function ( $tables, settings ) {
846 return $tables.each( ( i, table ) => {
847 // Declare and cache.
850 const $table = $( table );
852 // Don't construct twice on the same table
853 if ( $.data( table, 'tablesorter' ) ) {
857 if ( !table.tBodies ) {
860 if ( !table.tHead ) {
861 // No thead found. Look for rows with <th>s and
862 // move them into a <thead> tag or a <tfoot> tag
863 emulateTHeadAndFoot( $table );
865 // Still no thead? Then quit
866 if ( !table.tHead ) {
870 // The `sortable` class is used to identify tables which will become sortable
871 // If not used it will create a FOUC but it should be added since the sortable class
872 // is responsible for certain crucial style elements. If the class is already present
873 // this action will be harmless.
874 $table.addClass( 'jquery-tablesorter sortable' );
877 const config = Object.assign( {}, $.tablesorter.defaultOptions, settings );
879 // Save the settings where they read
880 $.data( table, 'tablesorter', { config: config } );
882 // Get the CSS class names, could be done elsewhere
883 const sortCSS = [ config.cssAsc, config.cssDesc, config.cssInitial ];
884 // Messages tell the user what the *next* state will be
885 // so are shifted by one relative to the CSS classes.
886 const sortMsg = [ mw.msg( 'sort-descending' ), mw.msg( 'sort-initial' ), mw.msg( 'sort-ascending' ) ];
889 const $headers = buildHeaders( table, sortMsg );
891 // Grab and process locale settings.
892 buildTransformTable();
895 // Precaching regexps can bring 10 fold
896 // performance improvements in some browsers.
899 function setupForFirstSort() {
902 // Defer buildCollationTable to first sort. As user and site scripts
903 // may customize tableSorterCollation but load after $.ready(), other
904 // scripts may call .tablesorter() before they have done the
905 // tableSorterCollation customizations.
908 // Move .sortbottom rows to the <tfoot> at the bottom of the <table>
909 const $sortbottoms = $table.find( '> tbody > tr.sortbottom' );
910 if ( $sortbottoms.length ) {
911 const $tfoot = $table.children( 'tfoot' );
912 if ( $tfoot.length ) {
913 $tfoot.eq( 0 ).prepend( $sortbottoms );
915 $table.append( $( '<tfoot>' ).append( $sortbottoms ) );
919 // Move .sorttop rows to the <thead> at the top of the <table>
920 // <thead> should exist if we got this far
921 const $sorttops = $table.find( '> tbody > tr.sorttop' );
922 if ( $sorttops.length ) {
923 $table.children( 'thead' ).append( $sorttops );
926 explodeRowspans( $table );
927 manageColspans( $table );
929 // Try to auto detect column type, and store in tables config
930 config.parsers = buildParserCache( table, $headers );
933 // Apply event handling to headers
934 // this is too big, perhaps break it out?
935 $headers.on( 'keypress click', function ( e ) {
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 const totalRows = ( $table[ 0 ].tBodies[ 0 ] && $table[ 0 ].tBodies[ 0 ].rows.length ) || 0;
960 if ( totalRows > 0 ) {
962 const $cell = $( cell );
963 const numSortOrders = 3;
965 // Get current column sort order
967 order: $cell.data( 'count' ) % numSortOrders,
968 count: $cell.data( 'count' ) + 1
971 // Get current column index
972 const columns = config.headerToColumns[ $cell.data( 'headerIndex' ) ];
973 const newSortList = columns.map( ( c ) => [ c, $cell.data( 'order' ) ] );
974 // Index of first column belonging to this header
975 const col = columns[ 0 ];
977 if ( !e[ config.sortMultiSortKey ] ) {
978 // User only wants to sort on one column set
979 // Flush the sort list and add new columns
980 config.sortList = newSortList;
982 // Multi column sorting
983 // It is not possible for one column to belong to multiple headers,
984 // so this is okay - we don't need to check for every value in the columns array
985 if ( isValueInArray( col, config.sortList ) ) {
986 // The user has clicked on an already sorted column.
987 // Reverse the sorting direction for all tables.
988 for ( let j = 0; j < config.sortList.length; j++ ) {
989 const s = config.sortList[ j ];
990 const o = config.headerList[ config.columnToHeader[ s[ 0 ] ] ];
991 if ( isValueInArray( s[ 0 ], newSortList ) ) {
992 $( o ).data( 'count', s[ 1 ] + 1 );
993 s[ 1 ] = $( o ).data( 'count' ) % numSortOrders;
997 // Add columns to sort list array
998 config.sortList = config.sortList.concat( newSortList );
1002 // Reset order/counts of cells not affected by sorting
1003 setHeadersOrder( $headers, config.sortList, config.headerToColumns );
1005 // Set CSS for headers
1006 setHeadersCss( $table[ 0 ], $headers, config.sortList, sortCSS, sortMsg, config.columnToHeader );
1008 $table[ 0 ], multisort( $table[ 0 ], config.sortList, cache )
1011 // Stop normal event by returning false
1016 } ).on( 'mousedown', function () {
1017 if ( config.cancelSelection ) {
1018 this.onselectstart = function () {
1026 * Sorts the table. If no sorting is specified by passing a list of sort
1027 * objects, the table is sorted according to the initial sorting order.
1028 * Passing an empty array will reset sorting (basically just reset the headers
1029 * making the table appear unsorted).
1031 * @param {Array} [sortList] List of sort objects.
1034 $table.data( 'tablesorter' ).sort = function ( sortList ) {
1037 setupForFirstSort();
1040 if ( sortList === undefined ) {
1041 sortList = config.sortList;
1042 } else if ( sortList.length > 0 ) {
1043 sortList = convertSortList( sortList );
1046 // Set each column's sort count to be able to determine the correct sort
1047 // order when clicking on a header cell the next time
1048 setHeadersOrder( $headers, sortList, config.headerToColumns );
1050 // re-build the cache for the tbody cells
1051 cache = buildCache( table );
1053 // set css for headers
1054 setHeadersCss( table, $headers, sortList, sortCSS, sortMsg, config.columnToHeader );
1056 // sort the table and append it to the dom
1057 appendToTable( table, multisort( table, sortList, cache ) );
1061 if ( config.sortList.length > 0 ) {
1062 config.sortList = convertSortList( config.sortList );
1063 $table.data( 'tablesorter' ).sort();
1069 addParser: function ( parser ) {
1070 if ( !getParserById( parser.id ) ) {
1071 parsers.push( parser );
1075 formatDigit: function ( s ) {
1076 if ( ts.transformTable !== false ) {
1078 for ( let p = 0; p < s.length; p++ ) {
1079 const c = s.charAt( p );
1080 if ( c in ts.transformTable ) {
1081 out += ts.transformTable[ c ];
1088 const i = parseFloat( s.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
1089 return isNaN( i ) ? -Infinity : i;
1092 formatFloat: function ( s ) {
1093 const i = parseFloat( s );
1094 return isNaN( i ) ? -Infinity : i;
1097 formatInt: function ( s ) {
1098 const i = parseInt( s, 10 );
1099 return isNaN( i ) ? -Infinity : i;
1102 clearTableBody: function ( table ) {
1103 $( table.tBodies[ 0 ] ).empty();
1106 getParser: function ( id ) {
1107 buildTransformTable();
1112 return getParserById( id );
1115 getParsers: function () { // for table diagnosis
1123 // Register as jQuery prototype method
1125 * Create a sortable table with multi-column sorting capabilities.
1127 * To use this {@link jQuery} plugin, load the `jquery.tablesorter` module with {@link mw.loader}.
1129 * @memberof module:jquery.tablesorter
1131 * mw.loader.using( 'jquery.tablesorter' ).then( () => {
1132 * // Create a simple tablesorter interface
1133 * $( 'table' ).tablesorter();
1135 * // Create a tablesorter interface, initially sorting on the first and second column
1136 * $( 'table' ).tablesorter( { sortList: [ { 0: 'desc' }, { 1: 'asc' } ] } )
1137 * .on( 'sortEnd.tablesorter', () => console.log( 'Triggered as soon as any sorting has been applied.' ) );
1139 * @param {module:jquery.tablesorter~TableSorterOptions} settings
1142 $.fn.tablesorter = function ( settings ) {
1143 return ts.construct( this, settings );
1146 // Add default parsers
1152 format: function ( s ) {
1153 if ( ts.collationRegex ) {
1154 const tsc = ts.collationTable;
1155 s = s.replace( ts.collationRegex, ( match ) => {
1156 const upper = match.toUpperCase(),
1157 lower = match.toLowerCase();
1159 if ( upper === match && !lower === match ) {
1160 r = tsc[ lower ] ? tsc[ lower ] : tsc[ upper ];
1161 r = r.toUpperCase();
1175 is: function ( s ) {
1176 return ts.rgx.IPAddress[ 0 ].test( s );
1178 format: function ( s ) {
1179 const a = s.split( '.' );
1181 for ( let i = 0; i < a.length; i++ ) {
1182 const item = a[ i ];
1183 if ( item.length === 1 ) {
1185 } else if ( item.length === 2 ) {
1191 return $.tablesorter.formatFloat( r );
1198 is: function ( s ) {
1199 return ts.rgx.currency[ 0 ].test( s );
1201 format: function ( s ) {
1202 return $.tablesorter.formatDigit( s.replace( ts.rgx.currency[ 1 ], '' ) );
1209 is: function ( s ) {
1210 return ts.rgx.usLongDate[ 0 ].test( s );
1212 format: function ( s ) {
1213 return $.tablesorter.formatFloat( new Date( s ).getTime() );
1220 is: function ( s ) {
1221 return ( ts.dateRegex[ 0 ].test( s ) || ts.dateRegex[ 1 ].test( s ) || ts.dateRegex[ 2 ].test( s ) );
1223 format: function ( s ) {
1224 s = s.toLowerCase();
1227 if ( ( match = s.match( ts.dateRegex[ 0 ] ) ) !== null ) {
1228 if ( mw.config.get( 'wgDefaultDateFormat' ) === 'mdy' || mw.config.get( 'wgPageViewLanguage' ) === 'en' ) {
1229 s = [ match[ 3 ], match[ 1 ], match[ 2 ] ];
1230 } else if ( mw.config.get( 'wgDefaultDateFormat' ) === 'dmy' ) {
1231 s = [ match[ 3 ], match[ 2 ], match[ 1 ] ];
1233 // If we get here, we don't know which order the dd-dd-dddd
1234 // date is in. So return something not entirely invalid.
1237 } else if ( ( match = s.match( ts.dateRegex[ 1 ] ) ) !== null ) {
1238 s = [ match[ 3 ], String( ts.monthNames[ match[ 2 ] ] ), match[ 1 ] ];
1239 } else if ( ( match = s.match( ts.dateRegex[ 2 ] ) ) !== null ) {
1240 s = [ match[ 3 ], String( ts.monthNames[ match[ 1 ] ] ), match[ 2 ] ];
1242 // Should never get here
1246 // Pad Month and Day
1247 if ( s[ 1 ].length === 1 ) {
1248 s[ 1 ] = '0' + s[ 1 ];
1250 if ( s[ 2 ].length === 1 ) {
1251 s[ 2 ] = '0' + s[ 2 ];
1255 if ( ( y = parseInt( s[ 0 ], 10 ) ) < 100 ) {
1256 // Guestimate years without centuries
1263 while ( s[ 0 ].length < 4 ) {
1264 s[ 0 ] = '0' + s[ 0 ];
1266 return parseInt( s.join( '' ), 10 );
1273 is: function ( s ) {
1274 return ts.rgx.time[ 0 ].test( s );
1276 format: function ( s ) {
1277 return $.tablesorter.formatFloat( new Date( '2000/01/01 ' + s ).getTime() );
1284 is: function ( s ) {
1285 return $.tablesorter.numberRegex.test( s );
1287 format: function ( s ) {
1288 return $.tablesorter.formatDigit( s );