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 sortType
, cells
, len
, i
, parser
,
164 rows
= table
.tBodies
[0].rows
,
169 cells
= rows
[0].cells
;
172 for ( i
= 0; i
< len
; i
++ ) {
174 sortType
= $headers
.eq( i
).data( 'sortType' );
175 if ( sortType
!== undefined ) {
176 parser
= getParserById( sortType
);
179 if ( parser
=== false ) {
180 parser
= detectParserForColumn( table
, rows
, i
);
183 parsers
.push( parser
);
189 /* Other utility functions */
191 function buildCache( table
) {
192 var i
, j
, $row
, cols
,
193 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 ( i
= 0; i
< totalRows
; ++i
) {
203 // Add the table data to main data array
204 $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 ( 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
) {
302 $tableHeaders
= $( [] ),
303 $tableRows
= $( 'thead:eq(0) > tr', table
);
304 if ( $tableRows
.length
<= 1 ) {
305 $tableHeaders
= $tableRows
.children( 'th' );
309 // Loop through all the dom cells of the thead
310 $tableRows
.each( function ( rowIndex
, row
) {
311 $.each( row
.cells
, function ( columnIndex
, cell
) {
312 rowspan
= Number( cell
.rowSpan
);
313 colspan
= Number( cell
.colSpan
);
315 // Skip the spots in the exploded matrix that are already filled
316 while ( exploded
[rowIndex
] && exploded
[rowIndex
][columnIndex
] !== undefined ) {
320 // Find the actual dimensions of the thead, by placing each cell
321 // in the exploded matrix rowspan times colspan times, with the proper offsets
322 for ( matrixColumnIndex
= columnIndex
; matrixColumnIndex
< columnIndex
+ colspan
; ++matrixColumnIndex
) {
323 for ( matrixRowIndex
= rowIndex
; matrixRowIndex
< rowIndex
+ rowspan
; ++matrixRowIndex
) {
324 if ( !exploded
[matrixRowIndex
] ) {
325 exploded
[matrixRowIndex
] = [];
327 exploded
[matrixRowIndex
][matrixColumnIndex
] = cell
;
332 // We want to find the row that has the most columns (ignoring colspan)
333 $.each( exploded
, function ( index
, cellArray
) {
334 headerCount
= $.unique( $( cellArray
) ).length
;
335 if ( headerCount
>= maxSeen
) {
336 maxSeen
= headerCount
;
340 // We cannot use $.unique() here because it sorts into dom order, which is undesirable
341 $tableHeaders
= $( uniqueElements( exploded
[longestTR
] ) );
344 // as each header can span over multiple columns (using colspan=N),
345 // we have to bidirectionally map headers to their columns and columns to their headers
346 table
.headerToColumns
= [];
347 table
.columnToHeader
= [];
349 $tableHeaders
.each( function ( headerIndex
) {
351 for ( i
= 0; i
< this.colSpan
; i
++ ) {
352 table
.columnToHeader
[ colspanOffset
+ i
] = headerIndex
;
353 columns
.push( colspanOffset
+ i
);
356 table
.headerToColumns
[ headerIndex
] = columns
;
357 colspanOffset
+= this.colSpan
;
359 this.headerIndex
= headerIndex
;
363 if ( $( this ).hasClass( table
.config
.unsortableClass
) ) {
364 this.sortDisabled
= true;
367 if ( !this.sortDisabled
) {
369 .addClass( table
.config
.cssHeader
)
370 .prop( 'tabIndex', 0 )
372 role
: 'columnheader button',
377 // add cell to headerList
378 table
.config
.headerList
[headerIndex
] = this;
381 return $tableHeaders
;
386 * Sets the sort count of the columns that are not affected by the sorting to have them sorted
387 * in default (ascending) order when their header cell is clicked the next time.
389 * @param {jQuery} $headers
390 * @param {Number[][]} sortList
391 * @param {Number[][]} headerToColumns
393 function setHeadersOrder( $headers
, sortList
, headerToColumns
) {
394 // Loop through all headers to retrieve the indices of the columns the header spans across:
395 $.each( headerToColumns
, function ( headerIndex
, columns
) {
397 $.each( columns
, function ( i
, columnIndex
) {
398 var header
= $headers
[headerIndex
];
400 if ( !isValueInArray( columnIndex
, sortList
) ) {
401 // Column shall not be sorted: Reset header count and order.
405 // Column shall be sorted: Apply designated count and order.
406 $.each( sortList
, function ( j
, sortColumn
) {
407 if ( sortColumn
[0] === i
) {
408 header
.order
= sortColumn
[1];
409 header
.count
= sortColumn
[1] + 1;
419 function isValueInArray( v
, a
) {
422 for ( i
= 0; i
< len
; i
++ ) {
423 if ( a
[i
][0] === v
) {
430 function uniqueElements( array
) {
432 $.each( array
, function ( index
, elem
) {
433 if ( elem
!== undefined && $.inArray( elem
, uniques
) === -1 ) {
434 uniques
.push( elem
);
440 function setHeadersCss( table
, $headers
, list
, css
, msg
, columnToHeader
) {
441 // Remove all header information and reset titles to default message
442 $headers
.removeClass( css
[0] ).removeClass( css
[1] ).attr( 'title', msg
[1] );
444 for ( var i
= 0; i
< list
.length
; i
++ ) {
445 $headers
.eq( columnToHeader
[ list
[i
][0] ] )
446 .addClass( css
[ list
[i
][1] ] )
447 .attr( 'title', msg
[ list
[i
][1] ] );
451 function sortText( a
, b
) {
452 return ( ( a
< b
) ? -1 : ( ( a
> b
) ? 1 : 0 ) );
455 function sortTextDesc( a
, b
) {
456 return ( ( b
< a
) ? -1 : ( ( b
> a
) ? 1 : 0 ) );
459 function multisort( table
, sortList
, cache
) {
462 len
= sortList
.length
;
463 for ( i
= 0; i
< len
; i
++ ) {
464 sortFn
[i
] = ( sortList
[i
][1] ) ? sortTextDesc
: sortText
;
466 cache
.normalized
.sort( function ( array1
, array2
) {
468 for ( i
= 0; i
< len
; i
++ ) {
469 col
= sortList
[i
][0];
470 ret
= sortFn
[i
].call( this, array1
[col
], array2
[col
] );
475 // Fall back to index number column to ensure stable sort
476 return sortText
.call( this, array1
[array1
.length
- 1], array2
[array2
.length
- 1] );
481 function buildTransformTable() {
482 var ascii
, localised
, i
, digitClass
,
483 digits
= '0123456789,.'.split( '' ),
484 separatorTransformTable
= mw
.config
.get( 'wgSeparatorTransformTable' ),
485 digitTransformTable
= mw
.config
.get( 'wgDigitTransformTable' );
487 if ( separatorTransformTable
=== null || ( separatorTransformTable
[0] === '' && digitTransformTable
[2] === '' ) ) {
488 ts
.transformTable
= false;
490 ts
.transformTable
= {};
492 // Unpack the transform table
493 ascii
= separatorTransformTable
[0].split( '\t' ).concat( digitTransformTable
[0].split( '\t' ) );
494 localised
= separatorTransformTable
[1].split( '\t' ).concat( digitTransformTable
[1].split( '\t' ) );
496 // Construct regex for number identification
497 for ( i
= 0; i
< ascii
.length
; i
++ ) {
498 ts
.transformTable
[localised
[i
]] = ascii
[i
];
499 digits
.push( $.escapeRE( localised
[i
] ) );
502 digitClass
= '[' + digits
.join( '', digits
) + ']';
504 // We allow a trailing percent sign, which we just strip. This works fine
505 // if percents and regular numbers aren't being mixed.
506 ts
.numberRegex
= new RegExp( '^(' + '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
507 '|' + '[-+\u2212]?' + digitClass
+ '+[\\s\\xa0]*%?' + // Generic localised
511 function buildDateTable() {
517 for ( i
= 0; i
< 12; i
++ ) {
518 name
= mw
.language
.months
.names
[i
].toLowerCase();
519 ts
.monthNames
[name
] = i
+ 1;
520 regex
.push( $.escapeRE( name
) );
521 name
= mw
.language
.months
.genitive
[i
].toLowerCase();
522 ts
.monthNames
[name
] = i
+ 1;
523 regex
.push( $.escapeRE( name
) );
524 name
= mw
.language
.months
.abbrev
[i
].toLowerCase().replace( '.', '' );
525 ts
.monthNames
[name
] = i
+ 1;
526 regex
.push( $.escapeRE( name
) );
529 // Build piped string
530 regex
= regex
.join( '|' );
533 // Any date formated with . , ' - or /
534 ts
.dateRegex
[0] = new RegExp( /^\s*(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{2,4})\s*?/i );
536 // Written Month name, dmy
537 ts
.dateRegex
[1] = new RegExp( '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
539 // Written Month name, mdy
540 ts
.dateRegex
[2] = new RegExp( '^\\s*(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
545 * Replace all rowspanned cells in the body with clones in each row, so sorting
546 * need not worry about them.
548 * @param $table jQuery object for a <table>
550 function explodeRowspans( $table
) {
551 var spanningRealCellIndex
, rowSpan
, colSpan
,
552 cell
, i
, $tds
, $clone
, $nextRows
,
553 rowspanCells
= $table
.find( '> tbody > tr > [rowspan]' ).get();
556 if ( !rowspanCells
.length
) {
560 // First, we need to make a property like cellIndex but taking into
561 // account colspans. We also cache the rowIndex to avoid having to take
562 // cell.parentNode.rowIndex in the sorting function below.
563 $table
.find( '> tbody > tr' ).each( function () {
566 l
= this.cells
.length
;
567 for ( i
= 0; i
< l
; i
++ ) {
568 this.cells
[i
].realCellIndex
= col
;
569 this.cells
[i
].realRowIndex
= this.rowIndex
;
570 col
+= this.cells
[i
].colSpan
;
574 // Split multi row cells into multiple cells with the same content.
575 // Sort by column then row index to avoid problems with odd table structures.
576 // Re-sort whenever a rowspanned cell's realCellIndex is changed, because it
577 // might change the sort order.
578 function resortCells() {
579 rowspanCells
= rowspanCells
.sort( function ( a
, b
) {
580 var ret
= a
.realCellIndex
- b
.realCellIndex
;
582 ret
= a
.realRowIndex
- b
.realRowIndex
;
586 $.each( rowspanCells
, function () {
587 this.needResort
= false;
592 function filterfunc() {
593 return this.realCellIndex
>= spanningRealCellIndex
;
596 function fixTdCellIndex() {
597 this.realCellIndex
+= colSpan
;
598 if ( this.rowSpan
> 1 ) {
599 this.needResort
= true;
603 while ( rowspanCells
.length
) {
604 if ( rowspanCells
[0].needResort
) {
608 cell
= rowspanCells
.shift();
609 rowSpan
= cell
.rowSpan
;
610 colSpan
= cell
.colSpan
;
611 spanningRealCellIndex
= cell
.realCellIndex
;
613 $nextRows
= $( cell
).parent().nextAll();
614 for ( i
= 0; i
< rowSpan
- 1; i
++ ) {
615 $tds
= $( $nextRows
[i
].cells
).filter( filterfunc
);
616 $clone
= $( cell
).clone();
617 $clone
[0].realCellIndex
= spanningRealCellIndex
;
619 $tds
.each( fixTdCellIndex
);
620 $tds
.first().before( $clone
);
622 $nextRows
.eq( i
).append( $clone
);
628 function buildCollationTable() {
629 ts
.collationTable
= mw
.config
.get( 'tableSorterCollation' );
630 ts
.collationRegex
= null;
631 if ( ts
.collationTable
) {
635 // Build array of key names
636 for ( key
in ts
.collationTable
) {
637 // Check hasOwn to be safe
638 if ( ts
.collationTable
.hasOwnProperty( key
) ) {
643 ts
.collationRegex
= new RegExp( '[' + keys
.join( '' ) + ']', 'ig' );
648 function cacheRegexs() {
654 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/ )
657 new RegExp( /(^[£$€¥]|[£$€¥]$)/ ),
658 new RegExp( /[£$€¥]/g )
661 new RegExp( /^(https?|ftp|file):\/\/$/ ),
662 new RegExp( /(https?|ftp|file):\/\// )
665 new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/ )
668 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)))$/ )
671 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/ )
677 * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
678 * structure [ [ Integer , Integer ], ... ]
680 * @param sortObjects {Array} List of sort objects.
681 * @return {Array} List of internal sort definitions.
684 function convertSortList( sortObjects
) {
686 $.each( sortObjects
, function ( i
, sortObject
) {
687 $.each( sortObject
, function ( columnIndex
, order
) {
688 var orderIndex
= ( order
=== 'desc' ) ? 1 : 0;
689 sortList
.push( [parseInt( columnIndex
, 10 ), orderIndex
] );
700 cssHeader
: 'headerSort',
701 cssAsc
: 'headerSortUp',
702 cssDesc
: 'headerSortDown',
703 cssChildRow
: 'expand-child',
704 sortInitialOrder
: 'asc',
705 sortMultiSortKey
: 'shiftKey',
706 sortLocaleCompare
: false,
707 unsortableClass
: 'unsortable',
711 cancelSelection
: true,
714 selectorHeaders
: 'thead tr:eq(0) th',
722 * @param $tables {jQuery}
723 * @param settings {Object} (optional)
725 construct: function ( $tables
, settings
) {
726 return $tables
.each( function ( i
, table
) {
727 // Declare and cache.
728 var $headers
, cache
, config
, sortCSS
, sortMsg
,
733 if ( !table
.tBodies
) {
736 if ( !table
.tHead
) {
737 // No thead found. Look for rows with <th>s and
738 // move them into a <thead> tag or a <tfoot> tag
739 emulateTHeadAndFoot( $table
);
741 // Still no thead? Then quit
742 if ( !table
.tHead
) {
746 $table
.addClass( 'jquery-tablesorter' );
748 // FIXME config should probably not be stored in the plain table node
749 // New config object.
753 config
= $.extend( table
.config
, $.tablesorter
.defaultOptions
, settings
);
755 // Save the settings where they read
756 $.data( table
, 'tablesorter', { config
: config
} );
758 // Get the CSS class names, could be done else where.
759 sortCSS
= [ config
.cssDesc
, config
.cssAsc
];
760 sortMsg
= [ mw
.msg( 'sort-descending' ), mw
.msg( 'sort-ascending' ) ];
763 $headers
= buildHeaders( table
, sortMsg
);
765 // Grab and process locale settings.
766 buildTransformTable();
769 // Precaching regexps can bring 10 fold
770 // performance improvements in some browsers.
773 function setupForFirstSort() {
776 // Defer buildCollationTable to first sort. As user and site scripts
777 // may customize tableSorterCollation but load after $.ready(), other
778 // scripts may call .tablesorter() before they have done the
779 // tableSorterCollation customizations.
780 buildCollationTable();
782 // Legacy fix of .sortbottoms
783 // Wrap them inside inside a tfoot (because that's what they actually want to be) &
784 // and put the <tfoot> at the end of the <table>
786 $sortbottoms
= $table
.find( '> tbody > tr.sortbottom' );
787 if ( $sortbottoms
.length
) {
788 $tfoot
= $table
.children( 'tfoot' );
789 if ( $tfoot
.length
) {
790 $tfoot
.eq( 0 ).prepend( $sortbottoms
);
792 $table
.append( $( '<tfoot>' ).append( $sortbottoms
) );
796 explodeRowspans( $table
);
798 // try to auto detect column type, and store in tables config
799 table
.config
.parsers
= buildParserCache( table
, $headers
);
802 // Apply event handling to headers
803 // this is too big, perhaps break it out?
804 $headers
.not( '.' + table
.config
.unsortableClass
).on( 'keypress click', function ( e
) {
805 var cell
, columns
, newSortList
, i
,
809 if ( e
.type
=== 'click' && e
.target
.nodeName
.toLowerCase() === 'a' ) {
810 // The user clicked on a link inside a table header.
811 // Do nothing and let the default link click action continue.
815 if ( e
.type
=== 'keypress' && e
.which
!== 13 ) {
816 // Only handle keypresses on the "Enter" key.
824 // Build the cache for the tbody cells
825 // to share between calculations for this sort action.
826 // Re-calculated each time a sort action is performed due to possiblity
827 // that sort values change. Shouldn't be too expensive, but if it becomes
828 // too slow an event based system should be implemented somehow where
829 // cells get event .change() and bubbles up to the <table> here
830 cache
= buildCache( table
);
832 totalRows
= ( $table
[0].tBodies
[0] && $table
[0].tBodies
[0].rows
.length
) || 0;
833 if ( !table
.sortDisabled
&& totalRows
> 0 ) {
834 // Get current column sort order
835 this.order
= this.count
% 2;
839 // Get current column index
840 columns
= table
.headerToColumns
[ this.headerIndex
];
841 newSortList
= $.map( columns
, function ( c
) {
842 // jQuery "helpfully" flattens the arrays...
843 return [[c
, cell
.order
]];
845 // Index of first column belonging to this header
848 if ( !e
[config
.sortMultiSortKey
] ) {
849 // User only wants to sort on one column set
850 // Flush the sort list and add new columns
851 config
.sortList
= newSortList
;
853 // Multi column sorting
854 // It is not possible for one column to belong to multiple headers,
855 // so this is okay - we don't need to check for every value in the columns array
856 if ( isValueInArray( i
, config
.sortList
) ) {
857 // The user has clicked on an already sorted column.
858 // Reverse the sorting direction for all tables.
859 for ( j
= 0; j
< config
.sortList
.length
; j
++ ) {
860 s
= config
.sortList
[j
];
861 o
= config
.headerList
[s
[0]];
862 if ( isValueInArray( s
[0], newSortList
) ) {
869 // Add columns to sort list array
870 config
.sortList
= config
.sortList
.concat( newSortList
);
874 // Reset order/counts of cells not affected by sorting
875 setHeadersOrder( $headers
, config
.sortList
, table
.headerToColumns
);
877 // Set CSS for headers
878 setHeadersCss( $table
[0], $headers
, config
.sortList
, sortCSS
, sortMsg
, table
.columnToHeader
);
880 $table
[0], multisort( $table
[0], config
.sortList
, cache
)
883 // Stop normal event by returning false
888 } ).mousedown( function () {
889 if ( config
.cancelSelection
) {
890 this.onselectstart = function () {
898 * Sorts the table. If no sorting is specified by passing a list of sort
899 * objects, the table is sorted according to the initial sorting order.
900 * Passing an empty array will reset sorting (basically just reset the headers
901 * making the table appear unsorted).
903 * @param sortList {Array} (optional) List of sort objects.
905 $table
.data( 'tablesorter' ).sort = function ( sortList
) {
911 if ( sortList
=== undefined ) {
912 sortList
= config
.sortList
;
913 } else if ( sortList
.length
> 0 ) {
914 sortList
= convertSortList( sortList
);
917 // Set each column's sort count to be able to determine the correct sort
918 // order when clicking on a header cell the next time
919 setHeadersOrder( $headers
, sortList
, table
.headerToColumns
);
921 // re-build the cache for the tbody cells
922 cache
= buildCache( table
);
924 // set css for headers
925 setHeadersCss( table
, $headers
, sortList
, sortCSS
, sortMsg
, table
.columnToHeader
);
927 // sort the table and append it to the dom
928 appendToTable( table
, multisort( table
, sortList
, cache
) );
932 if ( config
.sortList
.length
> 0 ) {
934 config
.sortList
= convertSortList( config
.sortList
);
935 $table
.data( 'tablesorter' ).sort();
941 addParser: function ( parser
) {
943 len
= parsers
.length
,
945 for ( i
= 0; i
< len
; i
++ ) {
946 if ( parsers
[i
].id
.toLowerCase() === parser
.id
.toLowerCase() ) {
951 parsers
.push( parser
);
955 formatDigit: function ( s
) {
957 if ( ts
.transformTable
!== false ) {
959 for ( p
= 0; p
< s
.length
; p
++ ) {
961 if ( c
in ts
.transformTable
) {
962 out
+= ts
.transformTable
[c
];
969 i
= parseFloat( s
.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
970 return isNaN( i
) ? 0 : i
;
973 formatFloat: function ( s
) {
974 var i
= parseFloat( s
);
975 return isNaN( i
) ? 0 : i
;
978 formatInt: function ( s
) {
979 var i
= parseInt( s
, 10 );
980 return isNaN( i
) ? 0 : i
;
983 clearTableBody: function ( table
) {
984 $( table
.tBodies
[0] ).empty();
991 // Register as jQuery prototype method
992 $.fn
.tablesorter = function ( settings
) {
993 return ts
.construct( this, settings
);
996 // Add default parsers
1002 format: function ( s
) {
1003 s
= $.trim( s
.toLowerCase() );
1004 if ( ts
.collationRegex
) {
1005 var tsc
= ts
.collationTable
;
1006 s
= s
.replace( ts
.collationRegex
, function ( match
) {
1007 var r
= tsc
[match
] ? tsc
[match
] : tsc
[match
.toUpperCase()];
1008 return r
.toLowerCase();
1018 is: function ( s
) {
1019 return ts
.rgx
.IPAddress
[0].test( s
);
1021 format: function ( s
) {
1026 for ( i
= 0; i
< len
; i
++ ) {
1028 if ( item
.length
=== 1 ) {
1030 } else if ( item
.length
=== 2 ) {
1036 return $.tablesorter
.formatFloat( r
);
1043 is: function ( s
) {
1044 return ts
.rgx
.currency
[0].test( s
);
1046 format: function ( s
) {
1047 return $.tablesorter
.formatDigit( s
.replace( ts
.rgx
.currency
[1], '' ) );
1054 is: function ( s
) {
1055 return ts
.rgx
.url
[0].test( s
);
1057 format: function ( s
) {
1058 return $.trim( s
.replace( ts
.rgx
.url
[1], '' ) );
1065 is: function ( s
) {
1066 return ts
.rgx
.isoDate
[0].test( s
);
1068 format: function ( s
) {
1069 return $.tablesorter
.formatFloat( ( s
!== '' ) ? new Date( s
.replace(
1070 new RegExp( /-/g ), '/' ) ).getTime() : '0' );
1077 is: function ( s ) {
1078 return ts.rgx.usLongDate[0].test( s );
1080 format: function ( s ) {
1081 return $.tablesorter.formatFloat( new Date( s ).getTime() );
1088 is: function ( s ) {
1089 return ( ts.dateRegex[0].test( s ) || ts.dateRegex[1].test( s ) || ts.dateRegex[2].test( s ) );
1091 format: function ( s ) {
1093 s = $.trim( s.toLowerCase() );
1095 if ( ( match = s.match( ts.dateRegex[0] ) ) !== null ) {
1096 if ( mw.config.get( 'wgDefaultDateFormat
' ) === 'mdy
' || mw.config.get( 'wgContentLanguage
' ) === 'en
' ) {
1097 s = [ match[3], match[1], match[2] ];
1098 } else if ( mw.config.get( 'wgDefaultDateFormat
' ) === 'dmy
' ) {
1099 s = [ match[3], match[2], match[1] ];
1101 // If we get here, we don't know which order the dd
-dd
-dddd
1102 // date is in. So return something not entirely invalid.
1105 } else if ( ( match
= s
.match( ts
.dateRegex
[1] ) ) !== null ) {
1106 s
= [ match
[3], '' + ts
.monthNames
[match
[2]], match
[1] ];
1107 } else if ( ( match
= s
.match( ts
.dateRegex
[2] ) ) !== null ) {
1108 s
= [ match
[3], '' + ts
.monthNames
[match
[1]], match
[2] ];
1110 // Should never get here
1114 // Pad Month and Day
1115 if ( s
[1].length
=== 1 ) {
1118 if ( s
[2].length
=== 1 ) {
1122 if ( ( y
= parseInt( s
[0], 10 ) ) < 100 ) {
1123 // Guestimate years without centuries
1130 while ( s
[0].length
< 4 ) {
1133 return parseInt( s
.join( '' ), 10 );
1140 is: function ( s
) {
1141 return ts
.rgx
.time
[0].test( s
);
1143 format: function ( s
) {
1144 return $.tablesorter
.formatFloat( new Date( '2000/01/01 ' + s
).getTime() );
1151 is: function ( s
) {
1152 return $.tablesorter
.numberRegex
.test( $.trim( s
) );
1154 format: function ( s
) {
1155 return $.tablesorter
.formatDigit( s
);
1160 }( jQuery
, mediaWiki
) );