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
) {
71 /*jshint onevar:false */
78 /* Parser utility functions */
80 function getParserById( name
) {
81 var len
= parsers
.length
;
82 for ( var i
= 0; i
< len
; i
++ ) {
83 if ( parsers
[i
].id
.toLowerCase() === name
.toLowerCase() ) {
90 function getElementSortKey( node
) {
91 var $node
= $( node
),
92 // Use data-sort-value attribute.
93 // Use data() instead of attr() so that live value changes
94 // are processed as well (bug 38152).
95 data
= $node
.data( 'sortValue' );
97 if ( data
!== null && data
!== undefined ) {
98 // Cast any numbers or other stuff to a string, methods
99 // like charAt, toLowerCase and split are expected.
100 return String( data
);
104 } else if ( node
.tagName
.toLowerCase() === 'img' ) {
105 return $node
.attr( 'alt' ) || ''; // handle undefined alt
107 return $.map( $.makeArray( node
.childNodes
), function( elem
) {
108 // 1 is for document.ELEMENT_NODE (the constant is undefined on old browsers)
109 if ( elem
.nodeType
=== 1 ) {
110 return getElementSortKey( elem
);
112 return $.text( elem
);
119 function detectParserForColumn( table
, rows
, cellIndex
) {
120 var l
= parsers
.length
,
122 // Start with 1 because 0 is the fallback parser
126 needed
= ( rows
.length
> 4 ) ? 5 : rows
.length
;
129 if ( rows
[rowIndex
] && rows
[rowIndex
].cells
[cellIndex
] ) {
130 nodeValue
= $.trim( getElementSortKey( rows
[rowIndex
].cells
[cellIndex
] ) );
135 if ( nodeValue
!== '') {
136 if ( parsers
[i
].is( nodeValue
, table
) ) {
139 if ( concurrent
>= needed
) {
140 // Confirmed the parser for multiple cells, let's return it
144 // Check next parser, reset rows
152 if ( rowIndex
> rows
.length
) {
159 // 0 is always the generic parser (text)
163 function buildParserCache( table
, $headers
) {
164 var rows
= table
.tBodies
[0].rows
,
170 var cells
= rows
[0].cells
,
174 for ( i
= 0; i
< len
; i
++ ) {
176 sortType
= $headers
.eq( i
).data( 'sortType' );
177 if ( sortType
!== undefined ) {
178 parser
= getParserById( sortType
);
181 if ( parser
=== false ) {
182 parser
= detectParserForColumn( table
, rows
, i
);
185 parsers
.push( parser
);
191 /* Other utility functions */
193 function buildCache( table
) {
194 var totalRows
= ( table
.tBodies
[0] && table
.tBodies
[0].rows
.length
) || 0,
195 totalCells
= ( table
.tBodies
[0].rows
[0] && table
.tBodies
[0].rows
[0].cells
.length
) || 0,
196 parsers
= table
.config
.parsers
,
202 for ( var i
= 0; i
< totalRows
; ++i
) {
204 // Add the table data to main data array
205 var $row
= $( table
.tBodies
[0].rows
[i
] ),
208 // if this is a child row, add it to the last row's children and
209 // continue to the next row
210 if ( $row
.hasClass( table
.config
.cssChildRow
) ) {
211 cache
.row
[cache
.row
.length
- 1] = cache
.row
[cache
.row
.length
- 1].add( $row
);
212 // go to the next for loop
216 cache
.row
.push( $row
);
218 for ( var j
= 0; j
< totalCells
; ++j
) {
219 cols
.push( parsers
[j
].format( getElementSortKey( $row
[0].cells
[j
] ), table
, $row
[0].cells
[j
] ) );
222 cols
.push( cache
.normalized
.length
); // add position for rowCache
223 cache
.normalized
.push( cols
);
230 function appendToTable( table
, cache
) {
232 normalized
= cache
.normalized
,
233 totalRows
= normalized
.length
,
234 checkCell
= ( normalized
[0].length
- 1 ),
235 fragment
= document
.createDocumentFragment();
237 for ( var i
= 0; i
< totalRows
; i
++ ) {
238 var pos
= normalized
[i
][checkCell
];
240 var l
= row
[pos
].length
;
242 for ( var 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 $rows
= $table
.find( '> tbody > tr' );
264 if( !$table
.get(0).tHead
) {
265 var $thead
= $( '<thead>' );
266 $rows
.each( function () {
267 if ( $(this).children( 'td' ).length
> 0 ) {
268 // This row contains a <td>, so it's not a header row
272 $thead
.append( this );
274 $table
.find(' > tbody:first').before( $thead
);
276 if( !$table
.get(0).tFoot
) {
277 var $tfoot
= $( '<tfoot>' );
278 var len
= $rows
.length
;
279 for ( var i
= len
-1; i
>= 0; i
-- ) {
280 if( $( $rows
[i
] ).children( 'td' ).length
> 0 ){
283 $tfoot
.prepend( $( $rows
[i
] ));
285 $table
.append( $tfoot
);
289 function buildHeaders( table
, msg
) {
295 $tableHeaders
= $( [] ),
296 $tableRows
= $( 'thead:eq(0) > tr', table
);
297 if ( $tableRows
.length
<= 1 ) {
298 $tableHeaders
= $tableRows
.children( 'th' );
300 // We need to find the cells of the row containing the most columns
303 $tableRows
.each( function ( rowIndex
) {
304 $.each( this.cells
, function( index2
, cell
) {
305 rowspan
= Number( cell
.rowSpan
);
306 for ( i
= 0; i
< rowspan
; i
++ ) {
307 if ( headersIndex
[rowIndex
+i
] === undefined ) {
308 headersIndex
[rowIndex
+i
] = $( [] );
310 headersIndex
[rowIndex
+i
].push( cell
);
314 $.each( headersIndex
, function ( index
, cellArray
) {
315 if ( cellArray
.length
>= maxSeen
) {
316 maxSeen
= cellArray
.length
;
320 $tableHeaders
= headersIndex
[longest
];
323 // as each header can span over multiple columns (using colspan=N),
324 // we have to bidirectionally map headers to their columns and columns to their headers
325 table
.headerToColumns
= [];
326 table
.columnToHeader
= [];
328 $tableHeaders
.each( function ( headerIndex
) {
330 for ( i
= 0; i
< this.colSpan
; i
++ ) {
331 table
.columnToHeader
[ colspanOffset
+ i
] = headerIndex
;
332 columns
.push( colspanOffset
+ i
);
335 table
.headerToColumns
[ headerIndex
] = columns
;
336 colspanOffset
+= this.colSpan
;
338 this.headerIndex
= headerIndex
;
342 if ( $( this ).hasClass( table
.config
.unsortableClass
) ) {
343 this.sortDisabled
= true;
346 if ( !this.sortDisabled
) {
348 .addClass( table
.config
.cssHeader
)
349 .prop( 'tabIndex', 0 )
351 role
: 'columnheader button',
356 // add cell to headerList
357 table
.config
.headerList
[headerIndex
] = this;
360 return $tableHeaders
;
365 * Sets the sort count of the columns that are not affected by the sorting to have them sorted
366 * in default (ascending) order when their header cell is clicked the next time.
368 * @param {jQuery} $headers
369 * @param {Number[][]} sortList
370 * @param {Number[][]} headerToColumns
372 function setHeadersOrder( $headers
, sortList
, headerToColumns
) {
373 // Loop through all headers to retrieve the indices of the columns the header spans across:
374 $.each( headerToColumns
, function( headerIndex
, columns
) {
376 $.each( columns
, function( i
, columnIndex
) {
377 var header
= $headers
[headerIndex
];
379 if ( !isValueInArray( columnIndex
, sortList
) ) {
380 // Column shall not be sorted: Reset header count and order.
384 // Column shall be sorted: Apply designated count and order.
385 $.each( sortList
, function( j
, sortColumn
) {
386 if ( sortColumn
[0] === i
) {
387 header
.order
= sortColumn
[1];
388 header
.count
= sortColumn
[1] + 1;
398 function isValueInArray( v
, a
) {
400 for ( var i
= 0; i
< l
; i
++ ) {
401 if ( a
[i
][0] === v
) {
408 function setHeadersCss( table
, $headers
, list
, css
, msg
, columnToHeader
) {
409 // Remove all header information and reset titles to default message
410 $headers
.removeClass( css
[0] ).removeClass( css
[1] ).attr( 'title', msg
[1] );
412 for ( var i
= 0; i
< list
.length
; i
++ ) {
413 $headers
.eq( columnToHeader
[ list
[i
][0] ] )
414 .addClass( css
[ list
[i
][1] ] )
415 .attr( 'title', msg
[ list
[i
][1] ] );
419 function sortText( a
, b
) {
420 return ( (a
< b
) ? -1 : ((a
> b
) ? 1 : 0) );
423 function sortTextDesc( a
, b
) {
424 return ( (b
< a
) ? -1 : ((b
> a
) ? 1 : 0) );
427 function multisort( table
, sortList
, cache
) {
429 var len
= sortList
.length
;
430 for ( var i
= 0; i
< len
; i
++ ) {
431 sortFn
[i
] = ( sortList
[i
][1] ) ? sortTextDesc
: sortText
;
433 cache
.normalized
.sort( function ( array1
, array2
) {
435 for ( var i
= 0; i
< len
; i
++ ) {
436 col
= sortList
[i
][0];
437 ret
= sortFn
[i
].call( this, array1
[col
], array2
[col
] );
442 // Fall back to index number column to ensure stable sort
443 return sortText
.call( this, array1
[array1
.length
- 1], array2
[array2
.length
- 1] );
448 function buildTransformTable() {
449 var digits
= '0123456789,.'.split( '' );
450 var separatorTransformTable
= mw
.config
.get( 'wgSeparatorTransformTable' );
451 var digitTransformTable
= mw
.config
.get( 'wgDigitTransformTable' );
452 if ( separatorTransformTable
=== null || ( separatorTransformTable
[0] === '' && digitTransformTable
[2] === '' ) ) {
453 ts
.transformTable
= false;
455 ts
.transformTable
= {};
457 // Unpack the transform table
458 var ascii
= separatorTransformTable
[0].split( '\t' ).concat( digitTransformTable
[0].split( '\t' ) );
459 var localised
= separatorTransformTable
[1].split( '\t' ).concat( digitTransformTable
[1].split( '\t' ) );
461 // Construct regex for number identification
462 for ( var i
= 0; i
< ascii
.length
; i
++ ) {
463 ts
.transformTable
[localised
[i
]] = ascii
[i
];
464 digits
.push( $.escapeRE( localised
[i
] ) );
467 var digitClass
= '[' + digits
.join( '', digits
) + ']';
469 // We allow a trailing percent sign, which we just strip. This works fine
470 // if percents and regular numbers aren't being mixed.
471 ts
.numberRegex
= new RegExp('^(' + '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
472 '|' + '[-+\u2212]?' + digitClass
+ '+[\\s\\xa0]*%?' + // Generic localised
476 function buildDateTable() {
480 for ( var i
= 0; i
< 12; i
++ ) {
481 var name
= mw
.language
.months
.names
[i
].toLowerCase();
482 ts
.monthNames
[name
] = i
+ 1;
483 regex
.push( $.escapeRE( name
) );
484 name
= mw
.language
.months
.genitive
[i
].toLowerCase();
485 ts
.monthNames
[name
] = i
+ 1;
486 regex
.push( $.escapeRE( name
) );
487 name
= mw
.language
.months
.abbrev
[i
].toLowerCase().replace( '.', '' );
488 ts
.monthNames
[name
] = i
+ 1;
489 regex
.push( $.escapeRE( name
) );
492 // Build piped string
493 regex
= regex
.join( '|' );
496 // Any date formated with . , ' - or /
497 ts
.dateRegex
[0] = new RegExp( /^\s*(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{2,4})\s*?/i);
499 // Written Month name, dmy
500 ts
.dateRegex
[1] = new RegExp( '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
502 // Written Month name, mdy
503 ts
.dateRegex
[2] = new RegExp( '^\\s*(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
508 * Replace all rowspanned cells in the body with clones in each row, so sorting
509 * need not worry about them.
511 * @param $table jQuery object for a <table>
513 function explodeRowspans( $table
) {
514 var rowspanCells
= $table
.find( '> tbody > tr > [rowspan]' ).get();
517 if ( !rowspanCells
.length
) {
521 // First, we need to make a property like cellIndex but taking into
522 // account colspans. We also cache the rowIndex to avoid having to take
523 // cell.parentNode.rowIndex in the sorting function below.
524 $table
.find( '> tbody > tr' ).each( function () {
526 var l
= this.cells
.length
;
527 for ( var i
= 0; i
< l
; i
++ ) {
528 this.cells
[i
].realCellIndex
= col
;
529 this.cells
[i
].realRowIndex
= this.rowIndex
;
530 col
+= this.cells
[i
].colSpan
;
534 // Split multi row cells into multiple cells with the same content.
535 // Sort by column then row index to avoid problems with odd table structures.
536 // Re-sort whenever a rowspanned cell's realCellIndex is changed, because it
537 // might change the sort order.
538 function resortCells() {
539 rowspanCells
= rowspanCells
.sort( function ( a
, b
) {
540 var ret
= a
.realCellIndex
- b
.realCellIndex
;
542 ret
= a
.realRowIndex
- b
.realRowIndex
;
546 $.each( rowspanCells
, function () {
547 this.needResort
= false;
552 var spanningRealCellIndex
, rowSpan
, colSpan
;
553 function filterfunc() {
554 return this.realCellIndex
>= spanningRealCellIndex
;
557 function fixTdCellIndex() {
558 this.realCellIndex
+= colSpan
;
559 if ( this.rowSpan
> 1 ) {
560 this.needResort
= true;
564 while ( rowspanCells
.length
) {
565 if ( rowspanCells
[0].needResort
) {
569 var cell
= rowspanCells
.shift();
570 rowSpan
= cell
.rowSpan
;
571 colSpan
= cell
.colSpan
;
572 spanningRealCellIndex
= cell
.realCellIndex
;
574 var $nextRows
= $( cell
).parent().nextAll();
575 for ( var i
= 0; i
< rowSpan
- 1; i
++ ) {
576 var $tds
= $( $nextRows
[i
].cells
).filter( filterfunc
);
577 var $clone
= $( cell
).clone();
578 $clone
[0].realCellIndex
= spanningRealCellIndex
;
580 $tds
.each( fixTdCellIndex
);
581 $tds
.first().before( $clone
);
583 $nextRows
.eq( i
).append( $clone
);
589 function buildCollationTable() {
590 ts
.collationTable
= mw
.config
.get( 'tableSorterCollation' );
591 ts
.collationRegex
= null;
592 if ( ts
.collationTable
) {
595 // Build array of key names
596 for ( var key
in ts
.collationTable
) {
597 if ( ts
.collationTable
.hasOwnProperty(key
) ) { //to be safe
602 ts
.collationRegex
= new RegExp( '[' + keys
.join( '' ) + ']', 'ig' );
607 function cacheRegexs() {
613 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/)
616 new RegExp( /(^[£$€¥]|[£$€¥]$)/),
617 new RegExp( /[£$€¥]/g)
620 new RegExp( /^(https?|ftp|file):\/\/$/),
621 new RegExp( /(https?|ftp|file):\/\//)
624 new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/)
627 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)))$/)
630 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/)
636 * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
637 * structure [ [ Integer , Integer ], ... ]
639 * @param sortObjects {Array} List of sort objects.
640 * @return {Array} List of internal sort definitions.
643 function convertSortList( sortObjects
) {
645 $.each( sortObjects
, function( i
, sortObject
) {
646 $.each ( sortObject
, function( columnIndex
, order
) {
647 var orderIndex
= ( order
=== 'desc' ) ? 1 : 0;
648 sortList
.push( [parseInt( columnIndex
, 10 ), orderIndex
] );
659 cssHeader
: 'headerSort',
660 cssAsc
: 'headerSortUp',
661 cssDesc
: 'headerSortDown',
662 cssChildRow
: 'expand-child',
663 sortInitialOrder
: 'asc',
664 sortMultiSortKey
: 'shiftKey',
665 sortLocaleCompare
: false,
666 unsortableClass
: 'unsortable',
670 cancelSelection
: true,
673 selectorHeaders
: 'thead tr:eq(0) th',
681 * @param $tables {jQuery}
682 * @param settings {Object} (optional)
684 construct: function ( $tables
, settings
) {
685 return $tables
.each( function ( i
, table
) {
686 // Declare and cache.
687 var $headers
, cache
, config
,
692 if ( !table
.tBodies
) {
695 if ( !table
.tHead
) {
696 // No thead found. Look for rows with <th>s and
697 // move them into a <thead> tag or a <tfoot> tag
698 emulateTHeadAndFoot( $table
);
700 // Still no thead? Then quit
701 if ( !table
.tHead
) {
705 $table
.addClass( 'jquery-tablesorter' );
707 // FIXME config should probably not be stored in the plain table node
708 // New config object.
712 config
= $.extend( table
.config
, $.tablesorter
.defaultOptions
, settings
);
714 // Save the settings where they read
715 $.data( table
, 'tablesorter', { config
: config
} );
717 // Get the CSS class names, could be done else where.
718 var sortCSS
= [ config
.cssDesc
, config
.cssAsc
];
719 var sortMsg
= [ mw
.msg( 'sort-descending' ), mw
.msg( 'sort-ascending' ) ];
722 $headers
= buildHeaders( table
, sortMsg
);
724 // Grab and process locale settings.
725 buildTransformTable();
728 // Precaching regexps can bring 10 fold
729 // performance improvements in some browsers.
732 function setupForFirstSort() {
735 // Defer buildCollationTable to first sort. As user and site scripts
736 // may customize tableSorterCollation but load after $.ready(), other
737 // scripts may call .tablesorter() before they have done the
738 // tableSorterCollation customizations.
739 buildCollationTable();
741 // Legacy fix of .sortbottoms
742 // Wrap them inside inside a tfoot (because that's what they actually want to be) &
743 // and put the <tfoot> at the end of the <table>
744 var $sortbottoms
= $table
.find( '> tbody > tr.sortbottom' );
745 if ( $sortbottoms
.length
) {
746 var $tfoot
= $table
.children( 'tfoot' );
747 if ( $tfoot
.length
) {
748 $tfoot
.eq(0).prepend( $sortbottoms
);
750 $table
.append( $( '<tfoot>' ).append( $sortbottoms
) );
754 explodeRowspans( $table
);
756 // try to auto detect column type, and store in tables config
757 table
.config
.parsers
= buildParserCache( table
, $headers
);
760 // Apply event handling to headers
761 // this is too big, perhaps break it out?
762 $headers
.not( '.' + table
.config
.unsortableClass
).on( 'keypress click', function ( e
) {
763 if ( e
.type
=== 'click' && e
.target
.nodeName
.toLowerCase() === 'a' ) {
764 // The user clicked on a link inside a table header.
765 // Do nothing and let the default link click action continue.
769 if ( e
.type
=== 'keypress' && e
.which
!== 13 ) {
770 // Only handle keypresses on the "Enter" key.
778 // Build the cache for the tbody cells
779 // to share between calculations for this sort action.
780 // Re-calculated each time a sort action is performed due to possiblity
781 // that sort values change. Shouldn't be too expensive, but if it becomes
782 // too slow an event based system should be implemented somehow where
783 // cells get event .change() and bubbles up to the <table> here
784 cache
= buildCache( table
);
786 var totalRows
= ( $table
[0].tBodies
[0] && $table
[0].tBodies
[0].rows
.length
) || 0;
787 if ( !table
.sortDisabled
&& totalRows
> 0 ) {
788 // Get current column sort order
789 this.order
= this.count
% 2;
793 // Get current column index
794 var columns
= table
.headerToColumns
[ this.headerIndex
];
795 var newSortList
= $.map( columns
, function (c
) {
796 // jQuery "helpfully" flattens the arrays...
797 return [[c
, cell
.order
]];
799 // Index of first column belonging to this header
802 if ( !e
[config
.sortMultiSortKey
] ) {
803 // User only wants to sort on one column set
804 // Flush the sort list and add new columns
805 config
.sortList
= newSortList
;
807 // Multi column sorting
808 // It is not possible for one column to belong to multiple headers,
809 // so this is okay - we don't need to check for every value in the columns array
810 if ( isValueInArray( i
, config
.sortList
) ) {
811 // The user has clicked on an already sorted column.
812 // Reverse the sorting direction for all tables.
813 for ( var j
= 0; j
< config
.sortList
.length
; j
++ ) {
814 var s
= config
.sortList
[j
],
815 o
= config
.headerList
[s
[0]];
816 if ( isValueInArray( s
[0], newSortList
) ) {
823 // Add columns to sort list array
824 config
.sortList
= config
.sortList
.concat( newSortList
);
828 // Reset order/counts of cells not affected by sorting
829 setHeadersOrder( $headers
, config
.sortList
, table
.headerToColumns
);
831 // Set CSS for headers
832 setHeadersCss( $table
[0], $headers
, config
.sortList
, sortCSS
, sortMsg
, table
.columnToHeader
);
834 $table
[0], multisort( $table
[0], config
.sortList
, cache
)
837 // Stop normal event by returning false
842 } ).mousedown( function () {
843 if ( config
.cancelSelection
) {
844 this.onselectstart = function () {
852 * Sorts the table. If no sorting is specified by passing a list of sort
853 * objects, the table is sorted according to the initial sorting order.
854 * Passing an empty array will reset sorting (basically just reset the headers
855 * making the table appear unsorted).
857 * @param sortList {Array} (optional) List of sort objects.
859 $table
.data( 'tablesorter' ).sort = function( sortList
) {
865 if ( sortList
=== undefined ) {
866 sortList
= config
.sortList
;
867 } else if ( sortList
.length
> 0 ) {
868 sortList
= convertSortList( sortList
);
871 // Set each column's sort count to be able to determine the correct sort
872 // order when clicking on a header cell the next time
873 setHeadersOrder( $headers
, sortList
, table
.headerToColumns
);
875 // re-build the cache for the tbody cells
876 cache
= buildCache( table
);
878 // set css for headers
879 setHeadersCss( table
, $headers
, sortList
, sortCSS
, sortMsg
, table
.columnToHeader
);
881 // sort the table and append it to the dom
882 appendToTable( table
, multisort( table
, sortList
, cache
) );
886 if ( config
.sortList
.length
> 0 ) {
888 config
.sortList
= convertSortList( config
.sortList
);
889 $table
.data( 'tablesorter' ).sort();
895 addParser: function ( parser
) {
896 var l
= parsers
.length
,
898 for ( var i
= 0; i
< l
; i
++ ) {
899 if ( parsers
[i
].id
.toLowerCase() === parser
.id
.toLowerCase() ) {
904 parsers
.push( parser
);
908 formatDigit: function ( s
) {
910 if ( ts
.transformTable
!== false ) {
912 for ( p
= 0; p
< s
.length
; p
++ ) {
914 if ( c
in ts
.transformTable
) {
915 out
+= ts
.transformTable
[c
];
922 i
= parseFloat( s
.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
923 return isNaN( i
) ? 0 : i
;
926 formatFloat: function ( s
) {
927 var i
= parseFloat(s
);
928 return isNaN( i
) ? 0 : i
;
931 formatInt: function ( s
) {
932 var i
= parseInt( s
, 10 );
933 return isNaN( i
) ? 0 : i
;
936 clearTableBody: function ( table
) {
937 $( table
.tBodies
[0] ).empty();
944 // Register as jQuery prototype method
945 $.fn
.tablesorter = function ( settings
) {
946 return ts
.construct( this, settings
);
949 // Add default parsers
955 format: function ( s
) {
956 s
= $.trim( s
.toLowerCase() );
957 if ( ts
.collationRegex
) {
958 var tsc
= ts
.collationTable
;
959 s
= s
.replace( ts
.collationRegex
, function ( match
) {
960 var r
= tsc
[match
] ? tsc
[match
] : tsc
[match
.toUpperCase()];
961 return r
.toLowerCase();
972 return ts
.rgx
.IPAddress
[0].test(s
);
974 format: function ( s
) {
975 var a
= s
.split( '.' ),
978 for ( var i
= 0; i
< l
; i
++ ) {
980 if ( item
.length
=== 1 ) {
982 } else if ( item
.length
=== 2 ) {
988 return $.tablesorter
.formatFloat(r
);
996 return ts
.rgx
.currency
[0].test(s
);
998 format: function ( s
) {
999 return $.tablesorter
.formatDigit( s
.replace( ts
.rgx
.currency
[1], '' ) );
1006 is: function ( s
) {
1007 return ts
.rgx
.url
[0].test(s
);
1009 format: function ( s
) {
1010 return $.trim( s
.replace( ts
.rgx
.url
[1], '' ) );
1017 is: function ( s
) {
1018 return ts
.rgx
.isoDate
[0].test(s
);
1020 format: function ( s
) {
1021 return $.tablesorter
.formatFloat((s
!== '') ? new Date(s
.replace(
1022 new RegExp( /-/g), '/')).getTime() : '0' );
1029 is: function ( s ) {
1030 return ts.rgx.usLongDate[0].test(s);
1032 format: function ( s ) {
1033 return $.tablesorter.formatFloat( new Date(s).getTime() );
1040 is: function ( s ) {
1041 return ( ts.dateRegex[0].test(s) || ts.dateRegex[1].test(s) || ts.dateRegex[2].test(s ));
1043 format: function ( s ) {
1045 s = $.trim( s.toLowerCase() );
1047 if ( ( match = s.match( ts.dateRegex[0] ) ) !== null ) {
1048 if ( mw.config.get( 'wgDefaultDateFormat
' ) === 'mdy
' || mw.config.get( 'wgContentLanguage
' ) === 'en
' ) {
1049 s = [ match[3], match[1], match[2] ];
1050 } else if ( mw.config.get( 'wgDefaultDateFormat
' ) === 'dmy
' ) {
1051 s = [ match[3], match[2], match[1] ];
1053 // If we get here, we don't know which order the dd
-dd
-dddd
1054 // date is in. So return something not entirely invalid.
1057 } else if ( ( match
= s
.match( ts
.dateRegex
[1] ) ) !== null ) {
1058 s
= [ match
[3], '' + ts
.monthNames
[match
[2]], match
[1] ];
1059 } else if ( ( match
= s
.match( ts
.dateRegex
[2] ) ) !== null ) {
1060 s
= [ match
[3], '' + ts
.monthNames
[match
[1]], match
[2] ];
1062 // Should never get here
1066 // Pad Month and Day
1067 if ( s
[1].length
=== 1 ) {
1070 if ( s
[2].length
=== 1 ) {
1075 if ( ( y
= parseInt( s
[0], 10) ) < 100 ) {
1076 // Guestimate years without centuries
1083 while ( s
[0].length
< 4 ) {
1086 return parseInt( s
.join( '' ), 10 );
1093 is: function ( s
) {
1094 return ts
.rgx
.time
[0].test(s
);
1096 format: function ( s
) {
1097 return $.tablesorter
.formatFloat( new Date( '2000/01/01 ' + s
).getTime() );
1104 is: function ( s
) {
1105 return $.tablesorter
.numberRegex
.test( $.trim( s
));
1107 format: function ( s
) {
1108 return $.tablesorter
.formatDigit(s
);
1113 }( jQuery
, mediaWiki
) );