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, wgMonthNames, wgMonthNamesShort,
12 * wgDefaultDateFormat, wgContentLanguage)
13 * Uses 'tableSorterCollation' in mw.config (if available)
17 * @description Create a sortable table with multi-column sorting capabilitys
19 * @example $( 'table' ).tablesorter();
20 * @desc Create a simple tablesorter interface.
22 * @example $( 'table' ).tablesorter( { sortList: [ { 0: 'desc' }, { 1: 'asc' } ] } );
23 * @desc Create a tablesorter interface initially sorting on the first and second column.
25 * @option String cssHeader ( optional ) A string of the class name to be appended
26 * to sortable tr elements in the thead of the table. Default value:
29 * @option String cssAsc ( optional ) A string of the class name to be appended to
30 * sortable tr elements in the thead on a ascending sort. Default value:
33 * @option String cssDesc ( optional ) A string of the class name to be appended
34 * to sortable tr elements in the thead on a descending sort. Default
35 * value: "headerSortDown"
37 * @option String sortInitialOrder ( optional ) A string of the inital sorting
38 * order can be asc or desc. Default value: "asc"
40 * @option String sortMultisortKey ( optional ) A string of the multi-column sort
41 * key. Default value: "shiftKey"
43 * @option Boolean sortLocaleCompare ( optional ) Boolean flag indicating whatever
44 * to use String.localeCampare method or not. Set to false.
46 * @option Boolean cancelSelection ( optional ) Boolean flag indicating if
47 * tablesorter should cancel selection of the table headers text.
50 * @option Array sortList ( optional ) An array containing objects specifying sorting.
51 * By passing more than one object, multi-sorting will be applied. Object structure:
52 * { <Integer column index>: <String 'asc' or 'desc'> }
55 * @option Boolean debug ( optional ) Boolean flag indicating if tablesorter
56 * should display debuging information usefull for development.
58 * @event sortEnd.tablesorter: Triggered as soon as any sorting has been applied.
64 * @cat Plugins/Tablesorter
66 * @author Christian Bach/christian.bach@polyester.se
69 ( function ( $, mw
) {
70 /*jshint onevar:false */
77 /* Parser utility functions */
79 function getParserById( name
) {
80 var len
= parsers
.length
;
81 for ( var 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
) {
231 normalized
= cache
.normalized
,
232 totalRows
= normalized
.length
,
233 checkCell
= ( normalized
[0].length
- 1 ),
234 fragment
= document
.createDocumentFragment();
236 for ( var i
= 0; i
< totalRows
; i
++ ) {
237 var pos
= normalized
[i
][checkCell
];
239 var l
= row
[pos
].length
;
241 for ( var j
= 0; j
< l
; j
++ ) {
242 fragment
.appendChild( row
[pos
][j
] );
246 table
.tBodies
[0].appendChild( fragment
);
248 $( table
).trigger( 'sortEnd.tablesorter' );
252 * Find all header rows in a thead-less table and put them in a <thead> tag.
253 * This only treats a row as a header row if it contains only <th>s (no <td>s)
254 * and if it is preceded entirely by header rows. The algorithm stops when
255 * it encounters the first non-header row.
257 * After this, it will look at all rows at the bottom for footer rows
258 * And place these in a tfoot using similar rules.
259 * @param $table jQuery object for a <table>
261 function emulateTHeadAndFoot( $table
) {
262 var $rows
= $table
.find( '> tbody > tr' );
263 if( !$table
.get(0).tHead
) {
264 var $thead
= $( '<thead>' );
265 $rows
.each( function () {
266 if ( $(this).children( 'td' ).length
> 0 ) {
267 // This row contains a <td>, so it's not a header row
271 $thead
.append( this );
273 $table
.find(' > tbody:first').before( $thead
);
275 if( !$table
.get(0).tFoot
) {
276 var $tfoot
= $( '<tfoot>' );
277 var len
= $rows
.length
;
278 for ( var i
= len
-1; i
>= 0; i
-- ) {
279 if( $( $rows
[i
] ).children( 'td' ).length
> 0 ){
282 $tfoot
.prepend( $( $rows
[i
] ));
284 $table
.append( $tfoot
);
288 function buildHeaders( table
, msg
) {
294 $tableHeaders
= $( [] ),
295 $tableRows
= $( 'thead:eq(0) > tr', table
);
296 if ( $tableRows
.length
<= 1 ) {
297 $tableHeaders
= $tableRows
.children( 'th' );
299 // We need to find the cells of the row containing the most columns
302 $tableRows
.each( function ( rowIndex
) {
303 $.each( this.cells
, function( index2
, cell
) {
304 rowspan
= Number( cell
.rowSpan
);
305 for ( i
= 0; i
< rowspan
; i
++ ) {
306 if ( headersIndex
[rowIndex
+i
] === undefined ) {
307 headersIndex
[rowIndex
+i
] = $( [] );
309 headersIndex
[rowIndex
+i
].push( cell
);
313 $.each( headersIndex
, function ( index
, cellArray
) {
314 if ( cellArray
.length
>= maxSeen
) {
315 maxSeen
= cellArray
.length
;
319 $tableHeaders
= headersIndex
[longest
];
322 // as each header can span over multiple columns (using colspan=N),
323 // we have to bidirectionally map headers to their columns and columns to their headers
324 table
.headerToColumns
= [];
325 table
.columnToHeader
= [];
327 $tableHeaders
.each( function ( headerIndex
) {
329 for ( i
= 0; i
< this.colSpan
; i
++ ) {
330 table
.columnToHeader
[ colspanOffset
+ i
] = headerIndex
;
331 columns
.push( colspanOffset
+ i
);
334 table
.headerToColumns
[ headerIndex
] = columns
;
335 colspanOffset
+= this.colSpan
;
337 this.headerIndex
= headerIndex
;
341 if ( $( this ).is( '.unsortable' ) ) {
342 this.sortDisabled
= true;
345 if ( !this.sortDisabled
) {
346 $( this ).addClass( table
.config
.cssHeader
).attr( 'title', msg
[1] );
349 // add cell to headerList
350 table
.config
.headerList
[headerIndex
] = this;
353 return $tableHeaders
;
358 * Sets the sort count of the columns that are not affected by the sorting to have them sorted
359 * in default (ascending) order when their header cell is clicked the next time.
361 * @param {jQuery} $headers
362 * @param {Number[][]} sortList
363 * @param {Number[][]} headerToColumns
365 function setHeadersOrder( $headers
, sortList
, headerToColumns
) {
366 // Loop through all headers to retrieve the indices of the columns the header spans across:
367 $.each( headerToColumns
, function( headerIndex
, columns
) {
369 $.each( columns
, function( i
, columnIndex
) {
370 var header
= $headers
[headerIndex
];
372 if ( !isValueInArray( columnIndex
, sortList
) ) {
373 // Column shall not be sorted: Reset header count and order.
377 // Column shall be sorted: Apply designated count and order.
378 $.each( sortList
, function( j
, sortColumn
) {
379 if ( sortColumn
[0] === i
) {
380 header
.order
= sortColumn
[1];
381 header
.count
= sortColumn
[1] + 1;
391 function isValueInArray( v
, a
) {
393 for ( var i
= 0; i
< l
; i
++ ) {
394 if ( a
[i
][0] === v
) {
401 function setHeadersCss( table
, $headers
, list
, css
, msg
, columnToHeader
) {
402 // Remove all header information and reset titles to default message
403 $headers
.removeClass( css
[0] ).removeClass( css
[1] ).attr( 'title', msg
[1] );
405 for ( var i
= 0; i
< list
.length
; i
++ ) {
406 $headers
.eq( columnToHeader
[ list
[i
][0] ] )
407 .addClass( css
[ list
[i
][1] ] )
408 .attr( 'title', msg
[ list
[i
][1] ] );
412 function sortText( a
, b
) {
413 return ( (a
< b
) ? -1 : ((a
> b
) ? 1 : 0) );
416 function sortTextDesc( a
, b
) {
417 return ( (b
< a
) ? -1 : ((b
> a
) ? 1 : 0) );
420 function multisort( table
, sortList
, cache
) {
422 var len
= sortList
.length
;
423 for ( var i
= 0; i
< len
; i
++ ) {
424 sortFn
[i
] = ( sortList
[i
][1] ) ? sortTextDesc
: sortText
;
426 cache
.normalized
.sort( function ( array1
, array2
) {
428 for ( var i
= 0; i
< len
; i
++ ) {
429 col
= sortList
[i
][0];
430 ret
= sortFn
[i
].call( this, array1
[col
], array2
[col
] );
435 // Fall back to index number column to ensure stable sort
436 return sortText
.call( this, array1
[array1
.length
- 1], array2
[array2
.length
- 1] );
441 function buildTransformTable() {
442 var digits
= '0123456789,.'.split( '' );
443 var separatorTransformTable
= mw
.config
.get( 'wgSeparatorTransformTable' );
444 var digitTransformTable
= mw
.config
.get( 'wgDigitTransformTable' );
445 if ( separatorTransformTable
=== null || ( separatorTransformTable
[0] === '' && digitTransformTable
[2] === '' ) ) {
446 ts
.transformTable
= false;
448 ts
.transformTable
= {};
450 // Unpack the transform table
451 var ascii
= separatorTransformTable
[0].split( '\t' ).concat( digitTransformTable
[0].split( '\t' ) );
452 var localised
= separatorTransformTable
[1].split( '\t' ).concat( digitTransformTable
[1].split( '\t' ) );
454 // Construct regex for number identification
455 for ( var i
= 0; i
< ascii
.length
; i
++ ) {
456 ts
.transformTable
[localised
[i
]] = ascii
[i
];
457 digits
.push( $.escapeRE( localised
[i
] ) );
460 var digitClass
= '[' + digits
.join( '', digits
) + ']';
462 // We allow a trailing percent sign, which we just strip. This works fine
463 // if percents and regular numbers aren't being mixed.
464 ts
.numberRegex
= new RegExp('^(' + '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
465 '|' + '[-+\u2212]?' + digitClass
+ '+[\\s\\xa0]*%?' + // Generic localised
469 function buildDateTable() {
473 for ( var i
= 1; i
< 13; i
++ ) {
474 var name
= mw
.config
.get( 'wgMonthNames' )[i
].toLowerCase();
475 ts
.monthNames
[name
] = i
;
476 regex
.push( $.escapeRE( name
) );
477 name
= mw
.config
.get( 'wgMonthNamesShort' )[i
].toLowerCase().replace( '.', '' );
478 ts
.monthNames
[name
] = i
;
479 regex
.push( $.escapeRE( name
) );
482 // Build piped string
483 regex
= regex
.join( '|' );
486 // Any date formated with . , ' - or /
487 ts
.dateRegex
[0] = new RegExp( /^\s*(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{2,4})\s*?/i);
489 // Written Month name, dmy
490 ts
.dateRegex
[1] = new RegExp( '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
492 // Written Month name, mdy
493 ts
.dateRegex
[2] = new RegExp( '^\\s*(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
498 * Replace all rowspanned cells in the body with clones in each row, so sorting
499 * need not worry about them.
501 * @param $table jQuery object for a <table>
503 function explodeRowspans( $table
) {
504 var rowspanCells
= $table
.find( '> tbody > tr > [rowspan]' ).get();
507 if ( !rowspanCells
.length
) {
511 // First, we need to make a property like cellIndex but taking into
512 // account colspans. We also cache the rowIndex to avoid having to take
513 // cell.parentNode.rowIndex in the sorting function below.
514 $table
.find( '> tbody > tr' ).each( function () {
516 var l
= this.cells
.length
;
517 for ( var i
= 0; i
< l
; i
++ ) {
518 this.cells
[i
].realCellIndex
= col
;
519 this.cells
[i
].realRowIndex
= this.rowIndex
;
520 col
+= this.cells
[i
].colSpan
;
524 // Split multi row cells into multiple cells with the same content.
525 // Sort by column then row index to avoid problems with odd table structures.
526 // Re-sort whenever a rowspanned cell's realCellIndex is changed, because it
527 // might change the sort order.
528 function resortCells() {
529 rowspanCells
= rowspanCells
.sort( function ( a
, b
) {
530 var ret
= a
.realCellIndex
- b
.realCellIndex
;
532 ret
= a
.realRowIndex
- b
.realRowIndex
;
536 $.each( rowspanCells
, function () {
537 this.needResort
= false;
542 var spanningRealCellIndex
, rowSpan
, colSpan
;
543 function filterfunc() {
544 return this.realCellIndex
>= spanningRealCellIndex
;
547 function fixTdCellIndex() {
548 this.realCellIndex
+= colSpan
;
549 if ( this.rowSpan
> 1 ) {
550 this.needResort
= true;
554 while ( rowspanCells
.length
) {
555 if ( rowspanCells
[0].needResort
) {
559 var cell
= rowspanCells
.shift();
560 rowSpan
= cell
.rowSpan
;
561 colSpan
= cell
.colSpan
;
562 spanningRealCellIndex
= cell
.realCellIndex
;
564 var $nextRows
= $( cell
).parent().nextAll();
565 for ( var i
= 0; i
< rowSpan
- 1; i
++ ) {
566 var $tds
= $( $nextRows
[i
].cells
).filter( filterfunc
);
567 var $clone
= $( cell
).clone();
568 $clone
[0].realCellIndex
= spanningRealCellIndex
;
570 $tds
.each( fixTdCellIndex
);
571 $tds
.first().before( $clone
);
573 $nextRows
.eq( i
).append( $clone
);
579 function buildCollationTable() {
580 ts
.collationTable
= mw
.config
.get( 'tableSorterCollation' );
581 ts
.collationRegex
= null;
582 if ( ts
.collationTable
) {
585 // Build array of key names
586 for ( var key
in ts
.collationTable
) {
587 if ( ts
.collationTable
.hasOwnProperty(key
) ) { //to be safe
592 ts
.collationRegex
= new RegExp( '[' + keys
.join( '' ) + ']', 'ig' );
597 function cacheRegexs() {
603 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/)
606 new RegExp( /(^[£$€¥]|[£$€¥]$)/),
607 new RegExp( /[£$€¥]/g)
610 new RegExp( /^(https?|ftp|file):\/\/$/),
611 new RegExp( /(https?|ftp|file):\/\//)
614 new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/)
617 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)))$/)
620 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/)
626 * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
627 * structure [ [ Integer , Integer ], ... ]
629 * @param sortObjects {Array} List of sort objects.
630 * @return {Array} List of internal sort definitions.
633 function convertSortList( sortObjects
) {
635 $.each( sortObjects
, function( i
, sortObject
) {
636 $.each ( sortObject
, function( columnIndex
, order
) {
637 var orderIndex
= ( order
=== 'desc' ) ? 1 : 0;
638 sortList
.push( [parseInt( columnIndex
, 10 ), orderIndex
] );
649 cssHeader
: 'headerSort',
650 cssAsc
: 'headerSortUp',
651 cssDesc
: 'headerSortDown',
652 cssChildRow
: 'expand-child',
653 sortInitialOrder
: 'asc',
654 sortMultiSortKey
: 'shiftKey',
655 sortLocaleCompare
: false,
659 cancelSelection
: true,
662 selectorHeaders
: 'thead tr:eq(0) th',
670 * @param $tables {jQuery}
671 * @param settings {Object} (optional)
673 construct: function ( $tables
, settings
) {
674 return $tables
.each( function ( i
, table
) {
675 // Declare and cache.
676 var $headers
, cache
, config
,
681 if ( !table
.tBodies
) {
684 if ( !table
.tHead
) {
685 // No thead found. Look for rows with <th>s and
686 // move them into a <thead> tag or a <tfoot> tag
687 emulateTHeadAndFoot( $table
);
689 // Still no thead? Then quit
690 if ( !table
.tHead
) {
694 $table
.addClass( 'jquery-tablesorter' );
696 // FIXME config should probably not be stored in the plain table node
697 // New config object.
701 config
= $.extend( table
.config
, $.tablesorter
.defaultOptions
, settings
);
703 // Save the settings where they read
704 $.data( table
, 'tablesorter', { config
: config
} );
706 // Get the CSS class names, could be done else where.
707 var sortCSS
= [ config
.cssDesc
, config
.cssAsc
];
708 var sortMsg
= [ mw
.msg( 'sort-descending' ), mw
.msg( 'sort-ascending' ) ];
711 $headers
= buildHeaders( table
, sortMsg
);
713 // Grab and process locale settings
714 buildTransformTable();
716 buildCollationTable();
718 // Precaching regexps can bring 10 fold
719 // performance improvements in some browsers.
722 function setupForFirstSort() {
725 // Legacy fix of .sortbottoms
726 // Wrap them inside inside a tfoot (because that's what they actually want to be) &
727 // and put the <tfoot> at the end of the <table>
728 var $sortbottoms
= $table
.find( '> tbody > tr.sortbottom' );
729 if ( $sortbottoms
.length
) {
730 var $tfoot
= $table
.children( 'tfoot' );
731 if ( $tfoot
.length
) {
732 $tfoot
.eq(0).prepend( $sortbottoms
);
734 $table
.append( $( '<tfoot>' ).append( $sortbottoms
) );
738 explodeRowspans( $table
);
740 // try to auto detect column type, and store in tables config
741 table
.config
.parsers
= buildParserCache( table
, $headers
);
744 // Apply event handling to headers
745 // this is too big, perhaps break it out?
746 $headers
.filter( ':not(.unsortable)' ).click( function ( e
) {
747 if ( e
.target
.nodeName
.toLowerCase() === 'a' ) {
748 // The user clicked on a link inside a table header
749 // Do nothing and let the default link click action continue
757 // Build the cache for the tbody cells
758 // to share between calculations for this sort action.
759 // Re-calculated each time a sort action is performed due to possiblity
760 // that sort values change. Shouldn't be too expensive, but if it becomes
761 // too slow an event based system should be implemented somehow where
762 // cells get event .change() and bubbles up to the <table> here
763 cache
= buildCache( table
);
765 var totalRows
= ( $table
[0].tBodies
[0] && $table
[0].tBodies
[0].rows
.length
) || 0;
766 if ( !table
.sortDisabled
&& totalRows
> 0 ) {
767 // Get current column sort order
768 this.order
= this.count
% 2;
772 // Get current column index
773 var columns
= table
.headerToColumns
[ this.headerIndex
];
774 var newSortList
= $.map( columns
, function (c
) {
775 // jQuery "helpfully" flattens the arrays...
776 return [[c
, cell
.order
]];
778 // Index of first column belonging to this header
781 if ( !e
[config
.sortMultiSortKey
] ) {
782 // User only wants to sort on one column set
783 // Flush the sort list and add new columns
784 config
.sortList
= newSortList
;
786 // Multi column sorting
787 // It is not possible for one column to belong to multiple headers,
788 // so this is okay - we don't need to check for every value in the columns array
789 if ( isValueInArray( i
, config
.sortList
) ) {
790 // The user has clicked on an already sorted column.
791 // Reverse the sorting direction for all tables.
792 for ( var j
= 0; j
< config
.sortList
.length
; j
++ ) {
793 var s
= config
.sortList
[j
],
794 o
= config
.headerList
[s
[0]];
795 if ( isValueInArray( s
[0], newSortList
) ) {
802 // Add columns to sort list array
803 config
.sortList
= config
.sortList
.concat( newSortList
);
807 // Reset order/counts of cells not affected by sorting
808 setHeadersOrder( $headers
, config
.sortList
, table
.headerToColumns
);
810 // Set CSS for headers
811 setHeadersCss( $table
[0], $headers
, config
.sortList
, sortCSS
, sortMsg
, table
.columnToHeader
);
813 $table
[0], multisort( $table
[0], config
.sortList
, cache
)
816 // Stop normal event by returning false
821 } ).mousedown( function () {
822 if ( config
.cancelSelection
) {
823 this.onselectstart = function () {
831 * Sorts the table. If no sorting is specified by passing a list of sort
832 * objects, the table is sorted according to the initial sorting order.
833 * Passing an empty array will reset sorting (basically just reset the headers
834 * making the table appear unsorted).
836 * @param sortList {Array} (optional) List of sort objects.
838 $table
.data( 'tablesorter' ).sort = function( sortList
) {
844 if ( sortList
=== undefined ) {
845 sortList
= config
.sortList
;
846 } else if ( sortList
.length
> 0 ) {
847 sortList
= convertSortList( sortList
);
850 // Set each column's sort count to be able to determine the correct sort
851 // order when clicking on a header cell the next time
852 setHeadersOrder( $headers
, sortList
, table
.headerToColumns
);
854 // re-build the cache for the tbody cells
855 cache
= buildCache( table
);
857 // set css for headers
858 setHeadersCss( table
, $headers
, sortList
, sortCSS
, sortMsg
, table
.columnToHeader
);
860 // sort the table and append it to the dom
861 appendToTable( table
, multisort( table
, sortList
, cache
) );
865 if ( config
.sortList
.length
> 0 ) {
867 config
.sortList
= convertSortList( config
.sortList
);
868 $table
.data( 'tablesorter' ).sort();
874 addParser: function ( parser
) {
875 var l
= parsers
.length
,
877 for ( var i
= 0; i
< l
; i
++ ) {
878 if ( parsers
[i
].id
.toLowerCase() === parser
.id
.toLowerCase() ) {
883 parsers
.push( parser
);
887 formatDigit: function ( s
) {
889 if ( ts
.transformTable
!== false ) {
891 for ( p
= 0; p
< s
.length
; p
++ ) {
893 if ( c
in ts
.transformTable
) {
894 out
+= ts
.transformTable
[c
];
901 i
= parseFloat( s
.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
902 return isNaN( i
) ? 0 : i
;
905 formatFloat: function ( s
) {
906 var i
= parseFloat(s
);
907 return isNaN( i
) ? 0 : i
;
910 formatInt: function ( s
) {
911 var i
= parseInt( s
, 10 );
912 return isNaN( i
) ? 0 : i
;
915 clearTableBody: function ( table
) {
916 $( table
.tBodies
[0] ).empty();
923 // Register as jQuery prototype method
924 $.fn
.tablesorter = function ( settings
) {
925 return ts
.construct( this, settings
);
928 // Add default parsers
934 format: function ( s
) {
935 s
= $.trim( s
.toLowerCase() );
936 if ( ts
.collationRegex
) {
937 var tsc
= ts
.collationTable
;
938 s
= s
.replace( ts
.collationRegex
, function ( match
) {
939 var r
= tsc
[match
] ? tsc
[match
] : tsc
[match
.toUpperCase()];
940 return r
.toLowerCase();
951 return ts
.rgx
.IPAddress
[0].test(s
);
953 format: function ( s
) {
954 var a
= s
.split( '.' ),
957 for ( var i
= 0; i
< l
; i
++ ) {
959 if ( item
.length
=== 1 ) {
961 } else if ( item
.length
=== 2 ) {
967 return $.tablesorter
.formatFloat(r
);
975 return ts
.rgx
.currency
[0].test(s
);
977 format: function ( s
) {
978 return $.tablesorter
.formatDigit( s
.replace( ts
.rgx
.currency
[1], '' ) );
986 return ts
.rgx
.url
[0].test(s
);
988 format: function ( s
) {
989 return $.trim( s
.replace( ts
.rgx
.url
[1], '' ) );
997 return ts
.rgx
.isoDate
[0].test(s
);
999 format: function ( s
) {
1000 return $.tablesorter
.formatFloat((s
!== '') ? new Date(s
.replace(
1001 new RegExp( /-/g), '/')).getTime() : '0' );
1008 is: function ( s ) {
1009 return ts.rgx.usLongDate[0].test(s);
1011 format: function ( s ) {
1012 return $.tablesorter.formatFloat( new Date(s).getTime() );
1019 is: function ( s ) {
1020 return ( ts.dateRegex[0].test(s) || ts.dateRegex[1].test(s) || ts.dateRegex[2].test(s ));
1022 format: function ( s ) {
1024 s = $.trim( s.toLowerCase() );
1026 if ( ( match = s.match( ts.dateRegex[0] ) ) !== null ) {
1027 if ( mw.config.get( 'wgDefaultDateFormat
' ) === 'mdy
' || mw.config.get( 'wgContentLanguage
' ) === 'en
' ) {
1028 s = [ match[3], match[1], match[2] ];
1029 } else if ( mw.config.get( 'wgDefaultDateFormat
' ) === 'dmy
' ) {
1030 s = [ match[3], match[2], match[1] ];
1032 // If we get here, we don't know which order the dd
-dd
-dddd
1033 // date is in. So return something not entirely invalid.
1036 } else if ( ( match
= s
.match( ts
.dateRegex
[1] ) ) !== null ) {
1037 s
= [ match
[3], '' + ts
.monthNames
[match
[2]], match
[1] ];
1038 } else if ( ( match
= s
.match( ts
.dateRegex
[2] ) ) !== null ) {
1039 s
= [ match
[3], '' + ts
.monthNames
[match
[1]], match
[2] ];
1041 // Should never get here
1045 // Pad Month and Day
1046 if ( s
[1].length
=== 1 ) {
1049 if ( s
[2].length
=== 1 ) {
1054 if ( ( y
= parseInt( s
[0], 10) ) < 100 ) {
1055 // Guestimate years without centuries
1062 while ( s
[0].length
< 4 ) {
1065 return parseInt( s
.join( '' ), 10 );
1072 is: function ( s
) {
1073 return ts
.rgx
.time
[0].test(s
);
1075 format: function ( s
) {
1076 return $.tablesorter
.formatFloat( new Date( '2000/01/01 ' + s
).getTime() );
1083 is: function ( s
) {
1084 return $.tablesorter
.numberRegex
.test( $.trim( s
));
1086 format: function ( s
) {
1087 return $.tablesorter
.formatDigit(s
);
1092 }( jQuery
, mediaWiki
) );