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, wgContentLanguage)
12 * and mw.language.months.
14 * Uses 'tableSorterCollation' in mw.config (if available)
18 * @description Create a sortable table with multi-column sorting capabilitys
20 * @example $( 'table' ).tablesorter();
21 * @desc Create a simple tablesorter interface.
23 * @example $( 'table' ).tablesorter( { sortList: [ { 0: 'desc' }, { 1: 'asc' } ] } );
24 * @desc Create a tablesorter interface initially sorting on the first and second column.
26 * @option String cssHeader ( optional ) A string of the class name to be appended
27 * to sortable tr elements in the thead of the table. Default value:
30 * @option String cssAsc ( optional ) A string of the class name to be appended to
31 * sortable tr elements in the thead on a ascending sort. Default value:
34 * @option String cssDesc ( optional ) A string of the class name to be appended
35 * to sortable tr elements in the thead on a descending sort. Default
36 * value: "headerSortDown"
38 * @option String sortInitialOrder ( optional ) A string of the inital sorting
39 * order can be asc or desc. Default value: "asc"
41 * @option String sortMultisortKey ( optional ) A string of the multi-column sort
42 * key. Default value: "shiftKey"
44 * @option Boolean sortLocaleCompare ( optional ) Boolean flag indicating whatever
45 * to use String.localeCampare method or not. Set to false.
47 * @option Boolean cancelSelection ( optional ) Boolean flag indicating if
48 * tablesorter should cancel selection of the table headers text.
51 * @option Array sortList ( optional ) An array containing objects specifying sorting.
52 * By passing more than one object, multi-sorting will be applied. Object structure:
53 * { <Integer column index>: <String 'asc' or 'desc'> }
56 * @option Boolean debug ( optional ) Boolean flag indicating if tablesorter
57 * should display debuging information usefull for development.
59 * @event sortEnd.tablesorter: Triggered as soon as any sorting has been applied.
65 * @cat Plugins/Tablesorter
67 * @author Christian Bach/christian.bach@polyester.se
70 ( function ( $, mw ) {
76 /* Parser utility functions */
78 function getParserById( name ) {
81 for ( i = 0; i < len; i++ ) {
82 if ( parsers[i].id.toLowerCase() === name.toLowerCase() ) {
89 function getElementSortKey( node ) {
90 var $node = $( node ),
91 // Use data-sort-value attribute.
92 // Use data() instead of attr() so that live value changes
93 // are processed as well (bug 38152).
94 data = $node.data( 'sortValue' );
96 if ( data !== null && data !== undefined ) {
97 // Cast any numbers or other stuff to a string, methods
98 // like charAt, toLowerCase and split are expected.
99 return String( data );
103 } else if ( node.tagName.toLowerCase() === 'img' ) {
104 return $node.attr( 'alt' ) || ''; // handle undefined alt
106 return $.map( $.makeArray( node.childNodes ), function ( elem ) {
107 // 1 is for document.ELEMENT_NODE (the constant is undefined on old browsers)
108 if ( elem.nodeType === 1 ) {
109 return getElementSortKey( elem );
111 return $.text( elem );
118 function detectParserForColumn( table, rows, cellIndex ) {
119 var l = parsers.length,
121 // Start with 1 because 0 is the fallback parser
125 needed = ( rows.length > 4 ) ? 5 : rows.length;
128 if ( rows[rowIndex] && rows[rowIndex].cells[cellIndex] ) {
129 nodeValue = $.trim( getElementSortKey( rows[rowIndex].cells[cellIndex] ) );
134 if ( nodeValue !== '' ) {
135 if ( parsers[i].is( nodeValue, table ) ) {
138 if ( concurrent >= needed ) {
139 // Confirmed the parser for multiple cells, let's return it
143 // Check next parser, reset rows
151 if ( rowIndex > rows.length ) {
158 // 0 is always the generic parser (text)
162 function buildParserCache( table, $headers ) {
163 var rows = table.tBodies[0].rows,
169 var cells = rows[0].cells,
173 for ( i = 0; i < len; i++ ) {
175 sortType = $headers.eq( i ).data( 'sortType' );
176 if ( sortType !== undefined ) {
177 parser = getParserById( sortType );
180 if ( parser === false ) {
181 parser = detectParserForColumn( table, rows, i );
184 parsers.push( parser );
190 /* Other utility functions */
192 function buildCache( table ) {
193 var totalRows = ( table.tBodies[0] && table.tBodies[0].rows.length ) || 0,
194 totalCells = ( table.tBodies[0].rows[0] && table.tBodies[0].rows[0].cells.length ) || 0,
195 parsers = table.config.parsers,
201 for ( var i = 0; i < totalRows; ++i ) {
203 // Add the table data to main data array
204 var $row = $( table.tBodies[0].rows[i] ),
207 // if this is a child row, add it to the last row's children and
208 // continue to the next row
209 if ( $row.hasClass( table.config.cssChildRow ) ) {
210 cache.row[cache.row.length - 1] = cache.row[cache.row.length - 1].add( $row );
211 // go to the next for loop
215 cache.row.push( $row );
217 for ( var j = 0; j < totalCells; ++j ) {
218 cols.push( parsers[j].format( getElementSortKey( $row[0].cells[j] ), table, $row[0].cells[j] ) );
221 cols.push( cache.normalized.length ); // add position for rowCache
222 cache.normalized.push( cols );
229 function appendToTable( table, cache ) {
232 normalized = cache.normalized,
233 totalRows = normalized.length,
234 checkCell = ( normalized[0].length - 1 ),
235 fragment = document.createDocumentFragment();
237 for ( i = 0; i < totalRows; i++ ) {
238 pos = normalized[i][checkCell];
242 for ( j = 0; j < l; j++ ) {
243 fragment.appendChild( row[pos][j] );
247 table.tBodies[0].appendChild( fragment );
249 $( table ).trigger( 'sortEnd.tablesorter' );
253 * Find all header rows in a thead-less table and put them in a <thead> tag.
254 * This only treats a row as a header row if it contains only <th>s (no <td>s)
255 * and if it is preceded entirely by header rows. The algorithm stops when
256 * it encounters the first non-header row.
258 * After this, it will look at all rows at the bottom for footer rows
259 * And place these in a tfoot using similar rules.
260 * @param $table jQuery object for a <table>
262 function emulateTHeadAndFoot( $table ) {
263 var $thead, $tfoot, i, len,
264 $rows = $table.find( '> tbody > tr' );
265 if ( !$table.get( 0 ).tHead ) {
266 $thead = $( '<thead>' );
267 $rows.each( function () {
268 if ( $( this ).children( 'td' ).length ) {
269 // This row contains a <td>, so it's not a header row
273 $thead.append( this );
275 $table.find( ' > tbody:first' ).before( $thead );
277 if ( !$table.get( 0 ).tFoot ) {
278 $tfoot = $( '<tfoot>' );
280 for ( i = len - 1; i >= 0; i-- ) {
281 if ( $( $rows[i] ).children( 'td' ).length ) {
284 $tfoot.prepend( $( $rows[i] ) );
286 $table.append( $tfoot );
290 function buildHeaders( table, msg ) {
295 $tableHeaders = $( [] ),
296 $tableRows = $( 'thead:eq(0) > tr', table );
297 if ( $tableRows.length <= 1 ) {
298 $tableHeaders = $tableRows.children( 'th' );
308 // Loop through all the dom cells of the thead
309 $tableRows.each( function ( rowIndex, row ) {
310 $.each( row.cells, function ( columnIndex, cell ) {
311 rowspan = Number( cell.rowSpan );
312 colspan = Number( cell.colSpan );
314 // Skip the spots in the exploded matrix that are already filled
315 while ( exploded[rowIndex] && exploded[rowIndex][columnIndex] !== undefined ) {
319 // Find the actual dimensions of the thead, by placing each cell
320 // in the exploded matrix rowspan times colspan times, with the proper offsets
321 for ( matrixColumnIndex = columnIndex; matrixColumnIndex < columnIndex + colspan; ++matrixColumnIndex ) {
322 for ( matrixRowIndex = rowIndex; matrixRowIndex < rowIndex + rowspan; ++matrixRowIndex ) {
323 if ( !exploded[matrixRowIndex] ) {
324 exploded[matrixRowIndex] = [];
326 exploded[matrixRowIndex][matrixColumnIndex] = cell;
331 // We want to find the row that has the most columns (ignoring colspan)
332 $.each( exploded, function ( index, cellArray ) {
333 headerCount = $.unique( $( cellArray ) ).length;
334 if ( headerCount >= maxSeen ) {
335 maxSeen = headerCount;
339 // We cannot use $.unique() here because it sorts into dom order, which is undesirable
340 $tableHeaders = $( uniqueElements( exploded[longestTR] ) );
343 // as each header can span over multiple columns (using colspan=N),
344 // we have to bidirectionally map headers to their columns and columns to their headers
345 table.headerToColumns = [];
346 table.columnToHeader = [];
348 $tableHeaders.each( function ( headerIndex ) {
350 for ( i = 0; i < this.colSpan; i++ ) {
351 table.columnToHeader[ colspanOffset + i ] = headerIndex;
352 columns.push( colspanOffset + i );
355 table.headerToColumns[ headerIndex ] = columns;
356 colspanOffset += this.colSpan;
358 this.headerIndex = headerIndex;
362 if ( $( this ).hasClass( table.config.unsortableClass ) ) {
363 this.sortDisabled = true;
366 if ( !this.sortDisabled ) {
368 .addClass( table.config.cssHeader )
369 .prop( 'tabIndex', 0 )
371 role: 'columnheader button',
376 // add cell to headerList
377 table.config.headerList[headerIndex] = this;
380 return $tableHeaders;
385 * Sets the sort count of the columns that are not affected by the sorting to have them sorted
386 * in default (ascending) order when their header cell is clicked the next time.
388 * @param {jQuery} $headers
389 * @param {Number[][]} sortList
390 * @param {Number[][]} headerToColumns
392 function setHeadersOrder( $headers, sortList, headerToColumns ) {
393 // Loop through all headers to retrieve the indices of the columns the header spans across:
394 $.each( headerToColumns, function ( headerIndex, columns ) {
396 $.each( columns, function ( i, columnIndex ) {
397 var header = $headers[headerIndex];
399 if ( !isValueInArray( columnIndex, sortList ) ) {
400 // Column shall not be sorted: Reset header count and order.
404 // Column shall be sorted: Apply designated count and order.
405 $.each( sortList, function ( j, sortColumn ) {
406 if ( sortColumn[0] === i ) {
407 header.order = sortColumn[1];
408 header.count = sortColumn[1] + 1;
418 function isValueInArray( v, a ) {
420 for ( var i = 0; i < l; i++ ) {
421 if ( a[i][0] === v ) {
428 function uniqueElements( array ) {
430 $.each( array, function ( index, elem ) {
431 if ( elem !== undefined && $.inArray( elem, uniques ) === -1 ) {
432 uniques.push( elem );
438 function setHeadersCss( table, $headers, list, css, msg, columnToHeader ) {
439 // Remove all header information and reset titles to default message
440 $headers.removeClass( css[0] ).removeClass( css[1] ).attr( 'title', msg[1] );
442 for ( var i = 0; i < list.length; i++ ) {
443 $headers.eq( columnToHeader[ list[i][0] ] )
444 .addClass( css[ list[i][1] ] )
445 .attr( 'title', msg[ list[i][1] ] );
449 function sortText( a, b ) {
450 return ( ( a < b ) ? -1 : ( ( a > b ) ? 1 : 0 ) );
453 function sortTextDesc( a, b ) {
454 return ( ( b < a ) ? -1 : ( ( b > a ) ? 1 : 0 ) );
457 function multisort( table, sortList, cache ) {
460 len = sortList.length;
461 for ( i = 0; i < len; i++ ) {
462 sortFn[i] = ( sortList[i][1] ) ? sortTextDesc : sortText;
464 cache.normalized.sort( function ( array1, array2 ) {
466 for ( i = 0; i < len; i++ ) {
467 col = sortList[i][0];
468 ret = sortFn[i].call( this, array1[col], array2[col] );
473 // Fall back to index number column to ensure stable sort
474 return sortText.call( this, array1[array1.length - 1], array2[array2.length - 1] );
479 function buildTransformTable() {
480 var ascii, localised, i, digitClass,
481 digits = '0123456789,.'.split( '' ),
482 separatorTransformTable = mw.config.get( 'wgSeparatorTransformTable' ),
483 digitTransformTable = mw.config.get( 'wgDigitTransformTable' );
485 if ( separatorTransformTable === null || ( separatorTransformTable[0] === '' && digitTransformTable[2] === '' ) ) {
486 ts.transformTable = false;
488 ts.transformTable = {};
490 // Unpack the transform table
491 ascii = separatorTransformTable[0].split( '\t' ).concat( digitTransformTable[0].split( '\t' ) );
492 localised = separatorTransformTable[1].split( '\t' ).concat( digitTransformTable[1].split( '\t' ) );
494 // Construct regex for number identification
495 for ( i = 0; i < ascii.length; i++ ) {
496 ts.transformTable[localised[i]] = ascii[i];
497 digits.push( $.escapeRE( localised[i] ) );
500 digitClass = '[' + digits.join( '', digits ) + ']';
502 // We allow a trailing percent sign, which we just strip. This works fine
503 // if percents and regular numbers aren't being mixed.
504 ts.numberRegex = new RegExp( '^(' + '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
505 '|' + '[-+\u2212]?' + digitClass + '+[\\s\\xa0]*%?' + // Generic localised
509 function buildDateTable() {
515 for ( i = 0; i < 12; i++ ) {
516 name = mw.language.months.names[i].toLowerCase();
517 ts.monthNames[name] = i + 1;
518 regex.push( $.escapeRE( name ) );
519 name = mw.language.months.genitive[i].toLowerCase();
520 ts.monthNames[name] = i + 1;
521 regex.push( $.escapeRE( name ) );
522 name = mw.language.months.abbrev[i].toLowerCase().replace( '.', '' );
523 ts.monthNames[name] = i + 1;
524 regex.push( $.escapeRE( name ) );
527 // Build piped string
528 regex = regex.join( '|' );
531 // Any date formated with . , ' - or /
532 ts.dateRegex[0] = new RegExp( /^\s*(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{2,4})\s*?/i );
534 // Written Month name, dmy
535 ts.dateRegex[1] = new RegExp( '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
537 // Written Month name, mdy
538 ts.dateRegex[2] = new RegExp( '^\\s*(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
543 * Replace all rowspanned cells in the body with clones in each row, so sorting
544 * need not worry about them.
546 * @param $table jQuery object for a <table>
548 function explodeRowspans( $table ) {
549 var spanningRealCellIndex, rowSpan, colSpan,
550 cell, i, $tds, $clone, $nextRows,
551 rowspanCells = $table.find( '> tbody > tr > [rowspan]' ).get();
554 if ( !rowspanCells.length ) {
558 // First, we need to make a property like cellIndex but taking into
559 // account colspans. We also cache the rowIndex to avoid having to take
560 // cell.parentNode.rowIndex in the sorting function below.
561 $table.find( '> tbody > tr' ).each( function () {
564 l = this.cells.length;
565 for ( i = 0; i < l; i++ ) {
566 this.cells[i].realCellIndex = col;
567 this.cells[i].realRowIndex = this.rowIndex;
568 col += this.cells[i].colSpan;
572 // Split multi row cells into multiple cells with the same content.
573 // Sort by column then row index to avoid problems with odd table structures.
574 // Re-sort whenever a rowspanned cell's realCellIndex is changed, because it
575 // might change the sort order.
576 function resortCells() {
577 rowspanCells = rowspanCells.sort( function ( a, b ) {
578 var ret = a.realCellIndex - b.realCellIndex;
580 ret = a.realRowIndex - b.realRowIndex;
584 $.each( rowspanCells, function () {
585 this.needResort = false;
590 function filterfunc() {
591 return this.realCellIndex >= spanningRealCellIndex;
594 function fixTdCellIndex() {
595 this.realCellIndex += colSpan;
596 if ( this.rowSpan > 1 ) {
597 this.needResort = true;
601 while ( rowspanCells.length ) {
602 if ( rowspanCells[0].needResort ) {
606 cell = rowspanCells.shift();
607 rowSpan = cell.rowSpan;
608 colSpan = cell.colSpan;
609 spanningRealCellIndex = cell.realCellIndex;
611 $nextRows = $( cell ).parent().nextAll();
612 for ( i = 0; i < rowSpan - 1; i++ ) {
613 $tds = $( $nextRows[i].cells ).filter( filterfunc );
614 $clone = $( cell ).clone();
615 $clone[0].realCellIndex = spanningRealCellIndex;
617 $tds.each( fixTdCellIndex );
618 $tds.first().before( $clone );
620 $nextRows.eq( i ).append( $clone );
626 function buildCollationTable() {
627 ts.collationTable = mw.config.get( 'tableSorterCollation' );
628 ts.collationRegex = null;
629 if ( ts.collationTable ) {
633 // Build array of key names
634 for ( key in ts.collationTable ) {
635 // Check hasOwn to be safe
636 if ( ts.collationTable.hasOwnProperty( key ) ) {
641 ts.collationRegex = new RegExp( '[' + keys.join( '' ) + ']', 'ig' );
646 function cacheRegexs() {
652 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/ )
655 new RegExp( /(^[£$€¥]|[£$€¥]$)/ ),
656 new RegExp( /[£$€¥]/g )
659 new RegExp( /^(https?|ftp|file):\/\/$/ ),
660 new RegExp( /(https?|ftp|file):\/\// )
663 new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/ )
666 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)))$/ )
669 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/ )
675 * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
676 * structure [ [ Integer , Integer ], ... ]
678 * @param sortObjects {Array} List of sort objects.
679 * @return {Array} List of internal sort definitions.
682 function convertSortList( sortObjects ) {
684 $.each( sortObjects, function ( i, sortObject ) {
685 $.each( sortObject, function ( columnIndex, order ) {
686 var orderIndex = ( order === 'desc' ) ? 1 : 0;
687 sortList.push( [parseInt( columnIndex, 10 ), orderIndex] );
698 cssHeader: 'headerSort',
699 cssAsc: 'headerSortUp',
700 cssDesc: 'headerSortDown',
701 cssChildRow: 'expand-child',
702 sortInitialOrder: 'asc',
703 sortMultiSortKey: 'shiftKey',
704 sortLocaleCompare: false,
705 unsortableClass: 'unsortable',
709 cancelSelection: true,
712 selectorHeaders: 'thead tr:eq(0) th',
720 * @param $tables {jQuery}
721 * @param settings {Object} (optional)
723 construct: function ( $tables, settings ) {
724 return $tables.each( function ( i, table ) {
725 // Declare and cache.
726 var $headers, cache, config, sortCSS, sortMsg,
731 if ( !table.tBodies ) {
734 if ( !table.tHead ) {
735 // No thead found. Look for rows with <th>s and
736 // move them into a <thead> tag or a <tfoot> tag
737 emulateTHeadAndFoot( $table );
739 // Still no thead? Then quit
740 if ( !table.tHead ) {
744 $table.addClass( 'jquery-tablesorter' );
746 // FIXME config should probably not be stored in the plain table node
747 // New config object.
751 config = $.extend( table.config, $.tablesorter.defaultOptions, settings );
753 // Save the settings where they read
754 $.data( table, 'tablesorter', { config: config } );
756 // Get the CSS class names, could be done else where.
757 sortCSS = [ config.cssDesc, config.cssAsc ];
758 sortMsg = [ mw.msg( 'sort-descending' ), mw.msg( 'sort-ascending' ) ];
761 $headers = buildHeaders( table, sortMsg );
763 // Grab and process locale settings.
764 buildTransformTable();
767 // Precaching regexps can bring 10 fold
768 // performance improvements in some browsers.
771 function setupForFirstSort() {
774 // Defer buildCollationTable to first sort. As user and site scripts
775 // may customize tableSorterCollation but load after $.ready(), other
776 // scripts may call .tablesorter() before they have done the
777 // tableSorterCollation customizations.
778 buildCollationTable();
780 // Legacy fix of .sortbottoms
781 // Wrap them inside inside a tfoot (because that's what they actually want to be) &
782 // and put the <tfoot> at the end of the <table>
783 var $sortbottoms = $table.find( '> tbody > tr.sortbottom' );
784 if ( $sortbottoms.length ) {
785 var $tfoot = $table.children( 'tfoot' );
786 if ( $tfoot.length ) {
787 $tfoot.eq( 0 ).prepend( $sortbottoms );
789 $table.append( $( '<tfoot>' ).append( $sortbottoms ) );
793 explodeRowspans( $table );
795 // try to auto detect column type, and store in tables config
796 table.config.parsers = buildParserCache( table, $headers );
799 // Apply event handling to headers
800 // this is too big, perhaps break it out?
801 $headers.not( '.' + table.config.unsortableClass ).on( 'keypress click', function ( e ) {
802 if ( e.type === 'click' && e.target.nodeName.toLowerCase() === 'a' ) {
803 // The user clicked on a link inside a table header.
804 // Do nothing and let the default link click action continue.
808 if ( e.type === 'keypress' && e.which !== 13 ) {
809 // Only handle keypresses on the "Enter" key.
817 // Build the cache for the tbody cells
818 // to share between calculations for this sort action.
819 // Re-calculated each time a sort action is performed due to possiblity
820 // that sort values change. Shouldn't be too expensive, but if it becomes
821 // too slow an event based system should be implemented somehow where
822 // cells get event .change() and bubbles up to the <table> here
823 cache = buildCache( table );
825 var totalRows = ( $table[0].tBodies[0] && $table[0].tBodies[0].rows.length ) || 0;
826 if ( !table.sortDisabled && totalRows > 0 ) {
827 // Get current column sort order
828 this.order = this.count % 2;
831 var cell, columns, newSortList, i;
834 // Get current column index
835 columns = table.headerToColumns[ this.headerIndex ];
836 newSortList = $.map( columns, function ( c ) {
837 // jQuery "helpfully" flattens the arrays...
838 return [[c, cell.order]];
840 // Index of first column belonging to this header
843 if ( !e[config.sortMultiSortKey] ) {
844 // User only wants to sort on one column set
845 // Flush the sort list and add new columns
846 config.sortList = newSortList;
848 // Multi column sorting
849 // It is not possible for one column to belong to multiple headers,
850 // so this is okay - we don't need to check for every value in the columns array
851 if ( isValueInArray( i, config.sortList ) ) {
852 // The user has clicked on an already sorted column.
853 // Reverse the sorting direction for all tables.
854 for ( var j = 0; j < config.sortList.length; j++ ) {
855 var s = config.sortList[j],
856 o = config.headerList[s[0]];
857 if ( isValueInArray( s[0], newSortList ) ) {
864 // Add columns to sort list array
865 config.sortList = config.sortList.concat( newSortList );
869 // Reset order/counts of cells not affected by sorting
870 setHeadersOrder( $headers, config.sortList, table.headerToColumns );
872 // Set CSS for headers
873 setHeadersCss( $table[0], $headers, config.sortList, sortCSS, sortMsg, table.columnToHeader );
875 $table[0], multisort( $table[0], config.sortList, cache )
878 // Stop normal event by returning false
883 } ).mousedown( function () {
884 if ( config.cancelSelection ) {
885 this.onselectstart = function () {
893 * Sorts the table. If no sorting is specified by passing a list of sort
894 * objects, the table is sorted according to the initial sorting order.
895 * Passing an empty array will reset sorting (basically just reset the headers
896 * making the table appear unsorted).
898 * @param sortList {Array} (optional) List of sort objects.
900 $table.data( 'tablesorter' ).sort = function ( sortList ) {
906 if ( sortList === undefined ) {
907 sortList = config.sortList;
908 } else if ( sortList.length > 0 ) {
909 sortList = convertSortList( sortList );
912 // Set each column's sort count to be able to determine the correct sort
913 // order when clicking on a header cell the next time
914 setHeadersOrder( $headers, sortList, table.headerToColumns );
916 // re-build the cache for the tbody cells
917 cache = buildCache( table );
919 // set css for headers
920 setHeadersCss( table, $headers, sortList, sortCSS, sortMsg, table.columnToHeader );
922 // sort the table and append it to the dom
923 appendToTable( table, multisort( table, sortList, cache ) );
927 if ( config.sortList.length > 0 ) {
929 config.sortList = convertSortList( config.sortList );
930 $table.data( 'tablesorter' ).sort();
936 addParser: function ( parser ) {
937 var l = parsers.length,
939 for ( var i = 0; i < l; i++ ) {
940 if ( parsers[i].id.toLowerCase() === parser.id.toLowerCase() ) {
945 parsers.push( parser );
949 formatDigit: function ( s ) {
951 if ( ts.transformTable !== false ) {
953 for ( p = 0; p < s.length; p++ ) {
955 if ( c in ts.transformTable ) {
956 out += ts.transformTable[c];
963 i = parseFloat( s.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
964 return isNaN( i ) ? 0 : i;
967 formatFloat: function ( s ) {
968 var i = parseFloat( s );
969 return isNaN( i ) ? 0 : i;
972 formatInt: function ( s ) {
973 var i = parseInt( s, 10 );
974 return isNaN( i ) ? 0 : i;
977 clearTableBody: function ( table ) {
978 $( table.tBodies[0] ).empty();
985 // Register as jQuery prototype method
986 $.fn.tablesorter = function ( settings ) {
987 return ts.construct( this, settings );
990 // Add default parsers
996 format: function ( s ) {
997 s = $.trim( s.toLowerCase() );
998 if ( ts.collationRegex ) {
999 var tsc = ts.collationTable;
1000 s = s.replace( ts.collationRegex, function ( match ) {
1001 var r = tsc[match] ? tsc[match] : tsc[match.toUpperCase()];
1002 return r.toLowerCase();
1012 is: function ( s ) {
1013 return ts.rgx.IPAddress[0].test( s );
1015 format: function ( s ) {
1016 var a = s.split( '.' ),
1019 for ( var i = 0; i < l; i++ ) {
1021 if ( item.length === 1 ) {
1023 } else if ( item.length === 2 ) {
1029 return $.tablesorter.formatFloat( r );
1036 is: function ( s ) {
1037 return ts.rgx.currency[0].test( s );
1039 format: function ( s ) {
1040 return $.tablesorter.formatDigit( s.replace( ts.rgx.currency[1], '' ) );
1047 is: function ( s ) {
1048 return ts.rgx.url[0].test( s );
1050 format: function ( s ) {
1051 return $.trim( s.replace( ts.rgx.url[1], '' ) );
1058 is: function ( s ) {
1059 return ts.rgx.isoDate[0].test( s );
1061 format: function ( s ) {
1062 return $.tablesorter.formatFloat( ( s !== '' ) ? new Date( s.replace(
1063 new RegExp( /-/g ), '/' ) ).getTime() : '0' );
1070 is: function ( s ) {
1071 return ts.rgx.usLongDate[0].test( s );
1073 format: function ( s ) {
1074 return $.tablesorter.formatFloat( new Date( s ).getTime() );
1081 is: function ( s ) {
1082 return ( ts.dateRegex[0].test( s ) || ts.dateRegex[1].test( s ) || ts.dateRegex[2].test( s ) );
1084 format: function ( s ) {
1086 s = $.trim( s.toLowerCase() );
1088 if ( ( match = s.match( ts.dateRegex[0] ) ) !== null ) {
1089 if ( mw.config.get( 'wgDefaultDateFormat' ) === 'mdy' || mw.config.get( 'wgContentLanguage' ) === 'en' ) {
1090 s = [ match[3], match[1], match[2] ];
1091 } else if ( mw.config.get( 'wgDefaultDateFormat' ) === 'dmy' ) {
1092 s = [ match[3], match[2], match[1] ];
1094 // If we get here, we don't know which order the dd-dd-dddd
1095 // date is in. So return something not entirely invalid.
1098 } else if ( ( match = s.match( ts.dateRegex[1] ) ) !== null ) {
1099 s = [ match[3], '' + ts.monthNames[match[2]], match[1] ];
1100 } else if ( ( match = s.match( ts.dateRegex[2] ) ) !== null ) {
1101 s = [ match[3], '' + ts.monthNames[match[1]], match[2] ];
1103 // Should never get here
1107 // Pad Month and Day
1108 if ( s[1].length === 1 ) {
1111 if ( s[2].length === 1 ) {
1116 if ( ( y = parseInt( s[0], 10 ) ) < 100 ) {
1117 // Guestimate years without centuries
1124 while ( s[0].length < 4 ) {
1127 return parseInt( s.join( '' ), 10 );
1134 is: function ( s ) {
1135 return ts.rgx.time[0].test( s );
1137 format: function ( s ) {
1138 return $.tablesorter.formatFloat( new Date( '2000/01/01 ' + s ).getTime() );
1145 is: function ( s ) {
1146 return $.tablesorter.numberRegex.test( $.trim( s ) );
1148 format: function ( s ) {
1149 return $.tablesorter.formatDigit( s );
1154 }( jQuery, mediaWiki ) );