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, wgPageContentLanguage)
12 * and mw.language.months.
14 * Uses 'tableSorterCollation' in mw.config (if available)
18 * @description Create a sortable table with multi-column sorting capabilities
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 sortMultisortKey ( optional ) A string of the multi-column sort
39 * key. Default value: "shiftKey"
41 * @option Boolean cancelSelection ( optional ) Boolean flag indicating if
42 * tablesorter should cancel selection of the table headers text.
45 * @option Array sortList ( optional ) An array containing objects specifying sorting.
46 * By passing more than one object, multi-sorting will be applied. Object structure:
47 * { <Integer column index>: <String 'asc' or 'desc'> }
50 * @event sortEnd.tablesorter: Triggered as soon as any sorting has been applied.
56 * @cat Plugins/Tablesorter
58 * @author Christian Bach/christian.bach@polyester.se
61 ( function ( $, mw
) {
67 /* Parser utility functions */
69 function getParserById( name
) {
72 for ( i
= 0; i
< len
; i
++ ) {
73 if ( parsers
[ i
].id
.toLowerCase() === name
.toLowerCase() ) {
80 function getElementSortKey( node
) {
81 var $node
= $( node
),
82 // Use data-sort-value attribute.
83 // Use data() instead of attr() so that live value changes
84 // are processed as well (bug 38152).
85 data
= $node
.data( 'sortValue' );
87 if ( data
!== null && data
!== undefined ) {
88 // Cast any numbers or other stuff to a string, methods
89 // like charAt, toLowerCase and split are expected.
90 return String( data
);
94 } else if ( node
.tagName
.toLowerCase() === 'img' ) {
95 return $node
.attr( 'alt' ) || ''; // handle undefined alt
97 return $.map( $.makeArray( node
.childNodes
), function ( elem
) {
98 if ( elem
.nodeType
=== Node
.ELEMENT_NODE
) {
99 return getElementSortKey( elem
);
101 return $.text( elem
);
108 function detectParserForColumn( table
, rows
, column
) {
109 var l
= parsers
.length
,
110 config
= $( table
).data( 'tablesorter' ).config
,
113 // Start with 1 because 0 is the fallback parser
119 needed
= ( rows
.length
> 4 ) ? 5 : rows
.length
;
122 // if this is a child row, continue to the next row (as buildCache())
123 if ( rows
[ rowIndex
] && !$( rows
[ rowIndex
] ).hasClass( config
.cssChildRow
) ) {
124 if ( rowIndex
!== lastRowIndex
) {
125 lastRowIndex
= rowIndex
;
126 cellIndex
= $( rows
[ rowIndex
] ).data( 'columnToCell' )[ column
];
127 nodeValue
= $.trim( getElementSortKey( rows
[ rowIndex
].cells
[ cellIndex
] ) );
133 if ( nodeValue
!== '' ) {
134 if ( parsers
[ i
].is( nodeValue
, table
) ) {
137 if ( concurrent
>= needed
) {
138 // Confirmed the parser for multiple cells, let's return it
142 // Check next parser, reset rows
152 if ( rowIndex
>= rows
.length
) {
153 if ( concurrent
>= rows
.length
- empty
) {
154 // Confirmed the parser for all filled cells
157 // Check next parser, reset rows
166 // 0 is always the generic parser (text)
170 function buildParserCache( table
, $headers
) {
171 var sortType
, len
, j
, parser
,
172 rows
= table
.tBodies
[ 0 ].rows
,
173 config
= $( table
).data( 'tablesorter' ).config
,
177 len
= config
.columns
;
178 for ( j
= 0; j
< len
; j
++ ) {
180 sortType
= $headers
.eq( config
.columnToHeader
[ j
] ).data( 'sortType' );
181 if ( sortType
!== undefined ) {
182 parser
= getParserById( sortType
);
185 if ( parser
=== false ) {
186 parser
= detectParserForColumn( table
, rows
, j
);
189 parsers
.push( parser
);
195 /* Other utility functions */
197 function buildCache( table
) {
198 var i
, j
, $row
, cols
,
199 totalRows
= ( table
.tBodies
[ 0 ] && table
.tBodies
[ 0 ].rows
.length
) || 0,
200 config
= $( table
).data( 'tablesorter' ).config
,
201 parsers
= config
.parsers
,
202 len
= parsers
.length
,
209 for ( i
= 0; i
< totalRows
; i
++ ) {
211 // Add the table data to main data array
212 $row
= $( table
.tBodies
[ 0 ].rows
[ i
] );
215 // if this is a child row, add it to the last row's children and
216 // continue to the next row
217 if ( $row
.hasClass( config
.cssChildRow
) ) {
218 cache
.row
[ cache
.row
.length
- 1 ] = cache
.row
[ cache
.row
.length
- 1 ].add( $row
);
219 // go to the next for loop
223 cache
.row
.push( $row
);
225 for ( j
= 0; j
< len
; j
++ ) {
226 cellIndex
= $row
.data( 'columnToCell' )[ j
];
227 cols
.push( parsers
[ j
].format( getElementSortKey( $row
[ 0 ].cells
[ cellIndex
] ) ) );
230 cols
.push( cache
.normalized
.length
); // add position for rowCache
231 cache
.normalized
.push( cols
);
238 function appendToTable( table
, cache
) {
241 normalized
= cache
.normalized
,
242 totalRows
= normalized
.length
,
243 checkCell
= ( normalized
[ 0 ].length
- 1 ),
244 fragment
= document
.createDocumentFragment();
246 for ( i
= 0; i
< totalRows
; i
++ ) {
247 pos
= normalized
[ i
][ checkCell
];
249 l
= row
[ pos
].length
;
251 for ( j
= 0; j
< l
; j
++ ) {
252 fragment
.appendChild( row
[ pos
][ j
] );
256 table
.tBodies
[ 0 ].appendChild( fragment
);
258 $( table
).trigger( 'sortEnd.tablesorter' );
262 * Find all header rows in a thead-less table and put them in a <thead> tag.
263 * This only treats a row as a header row if it contains only <th>s (no <td>s)
264 * and if it is preceded entirely by header rows. The algorithm stops when
265 * it encounters the first non-header row.
267 * After this, it will look at all rows at the bottom for footer rows
268 * And place these in a tfoot using similar rules.
270 * @param {jQuery} $table object for a <table>
272 function emulateTHeadAndFoot( $table
) {
273 var $thead
, $tfoot
, i
, len
,
274 $rows
= $table
.find( '> tbody > tr' );
275 if ( !$table
.get( 0 ).tHead
) {
276 $thead
= $( '<thead>' );
277 $rows
.each( function () {
278 if ( $( this ).children( 'td' ).length
) {
279 // This row contains a <td>, so it's not a header row
283 $thead
.append( this );
285 $table
.find( ' > tbody:first' ).before( $thead
);
287 if ( !$table
.get( 0 ).tFoot
) {
288 $tfoot
= $( '<tfoot>' );
290 for ( i
= len
- 1; i
>= 0; i
-- ) {
291 if ( $( $rows
[ i
] ).children( 'td' ).length
) {
294 $tfoot
.prepend( $( $rows
[ i
] ) );
296 $table
.append( $tfoot
);
300 function uniqueElements( array
) {
302 $.each( array
, function ( index
, elem
) {
303 if ( elem
!== undefined && $.inArray( elem
, uniques
) === -1 ) {
304 uniques
.push( elem
);
310 function buildHeaders( table
, msg
) {
311 var config
= $( table
).data( 'tablesorter' ).config
,
323 $tableHeaders
= $( [] ),
324 $tableRows
= $( 'thead:eq(0) > tr', table
);
325 if ( $tableRows
.length
<= 1 ) {
326 $tableHeaders
= $tableRows
.children( 'th' );
330 // Loop through all the dom cells of the thead
331 $tableRows
.each( function ( rowIndex
, row
) {
332 $.each( row
.cells
, function ( columnIndex
, cell
) {
336 rowspan
= Number( cell
.rowSpan
);
337 colspan
= Number( cell
.colSpan
);
339 // Skip the spots in the exploded matrix that are already filled
340 while ( exploded
[ rowIndex
] && exploded
[ rowIndex
][ columnIndex
] !== undefined ) {
344 // Find the actual dimensions of the thead, by placing each cell
345 // in the exploded matrix rowspan times colspan times, with the proper offsets
346 for ( matrixColumnIndex
= columnIndex
; matrixColumnIndex
< columnIndex
+ colspan
; ++matrixColumnIndex
) {
347 for ( matrixRowIndex
= rowIndex
; matrixRowIndex
< rowIndex
+ rowspan
; ++matrixRowIndex
) {
348 if ( !exploded
[ matrixRowIndex
] ) {
349 exploded
[ matrixRowIndex
] = [];
351 exploded
[ matrixRowIndex
][ matrixColumnIndex
] = cell
;
356 // We want to find the row that has the most columns (ignoring colspan)
357 $.each( exploded
, function ( index
, cellArray
) {
358 headerCount
= $( uniqueElements( cellArray
) ).filter( 'th' ).length
;
359 if ( headerCount
>= maxSeen
) {
360 maxSeen
= headerCount
;
364 // We cannot use $.unique() here because it sorts into dom order, which is undesirable
365 $tableHeaders
= $( uniqueElements( exploded
[ longestTR
] ) ).filter( 'th' );
368 // as each header can span over multiple columns (using colspan=N),
369 // we have to bidirectionally map headers to their columns and columns to their headers
370 config
.columnToHeader
= [];
371 config
.headerToColumns
= [];
372 config
.headerList
= [];
374 $tableHeaders
.each( function () {
378 if ( !$cell
.hasClass( config
.unsortableClass
) ) {
380 .addClass( config
.cssHeader
)
381 .prop( 'tabIndex', 0 )
383 role
: 'columnheader button',
387 for ( k
= 0; k
< this.colSpan
; k
++ ) {
388 config
.columnToHeader
[ colspanOffset
+ k
] = headerIndex
;
389 columns
.push( colspanOffset
+ k
);
392 config
.headerToColumns
[ headerIndex
] = columns
;
395 headerIndex
: headerIndex
,
400 // add only sortable cells to headerList
401 config
.headerList
[ headerIndex
] = this;
405 colspanOffset
+= this.colSpan
;
408 // number of columns with extended colspan, inclusive unsortable
409 // parsers[j], cache[][j], columnToHeader[j], columnToCell[j] have so many elements
410 config
.columns
= colspanOffset
;
412 return $tableHeaders
.not( '.' + config
.unsortableClass
);
415 function isValueInArray( v
, a
) {
418 for ( i
= 0; i
< len
; i
++ ) {
419 if ( a
[ i
][ 0 ] === v
) {
427 * Sets the sort count of the columns that are not affected by the sorting to have them sorted
428 * in default (ascending) order when their header cell is clicked the next time.
430 * @param {jQuery} $headers
431 * @param {number[][]} sortList
432 * @param {number[][]} headerToColumns
434 function setHeadersOrder( $headers
, sortList
, headerToColumns
) {
435 // Loop through all headers to retrieve the indices of the columns the header spans across:
436 $.each( headerToColumns
, function ( headerIndex
, columns
) {
438 $.each( columns
, function ( i
, columnIndex
) {
439 var header
= $headers
[ headerIndex
],
440 $header
= $( header
);
442 if ( !isValueInArray( columnIndex
, sortList
) ) {
443 // Column shall not be sorted: Reset header count and order.
449 // Column shall be sorted: Apply designated count and order.
450 $.each( sortList
, function ( j
, sortColumn
) {
451 if ( sortColumn
[ 0 ] === i
) {
453 order
: sortColumn
[ 1 ],
454 count
: sortColumn
[ 1 ] + 1
465 function setHeadersCss( table
, $headers
, list
, css
, msg
, columnToHeader
) {
466 // Remove all header information and reset titles to default message
467 $headers
.removeClass( css
[ 0 ] ).removeClass( css
[ 1 ] ).attr( 'title', msg
[ 1 ] );
469 for ( var i
= 0; i
< list
.length
; i
++ ) {
470 $headers
.eq( columnToHeader
[ list
[ i
][ 0 ] ] )
471 .addClass( css
[ list
[ i
][ 1 ] ] )
472 .attr( 'title', msg
[ list
[ i
][ 1 ] ] );
476 function sortText( a
, b
) {
477 return ( ( a
< b
) ? -1 : ( ( a
> b
) ? 1 : 0 ) );
480 function sortTextDesc( a
, b
) {
481 return ( ( b
< a
) ? -1 : ( ( b
> a
) ? 1 : 0 ) );
484 function multisort( table
, sortList
, cache
) {
487 len
= sortList
.length
;
488 for ( i
= 0; i
< len
; i
++ ) {
489 sortFn
[ i
] = ( sortList
[ i
][ 1 ] ) ? sortTextDesc
: sortText
;
491 cache
.normalized
.sort( function ( array1
, array2
) {
493 for ( i
= 0; i
< len
; i
++ ) {
494 col
= sortList
[ i
][ 0 ];
495 ret
= sortFn
[ i
].call( this, array1
[ col
], array2
[ col
] );
500 // Fall back to index number column to ensure stable sort
501 return sortText
.call( this, array1
[ array1
.length
- 1 ], array2
[ array2
.length
- 1 ] );
506 function buildTransformTable() {
507 var ascii
, localised
, i
, digitClass
,
508 digits
= '0123456789,.'.split( '' ),
509 separatorTransformTable
= mw
.config
.get( 'wgSeparatorTransformTable' ),
510 digitTransformTable
= mw
.config
.get( 'wgDigitTransformTable' );
512 if ( separatorTransformTable
=== null || ( separatorTransformTable
[ 0 ] === '' && digitTransformTable
[ 2 ] === '' ) ) {
513 ts
.transformTable
= false;
515 ts
.transformTable
= {};
517 // Unpack the transform table
518 ascii
= separatorTransformTable
[ 0 ].split( '\t' ).concat( digitTransformTable
[ 0 ].split( '\t' ) );
519 localised
= separatorTransformTable
[ 1 ].split( '\t' ).concat( digitTransformTable
[ 1 ].split( '\t' ) );
521 // Construct regex for number identification
522 for ( i
= 0; i
< ascii
.length
; i
++ ) {
523 ts
.transformTable
[ localised
[ i
] ] = ascii
[ i
];
524 digits
.push( mw
.RegExp
.escape( localised
[ i
] ) );
527 digitClass
= '[' + digits
.join( '', digits
) + ']';
529 // We allow a trailing percent sign, which we just strip. This works fine
530 // if percents and regular numbers aren't being mixed.
531 ts
.numberRegex
= new RegExp( '^(' + '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
532 '|' + '[-+\u2212]?' + digitClass
+ '+[\\s\\xa0]*%?' + // Generic localised
536 function buildDateTable() {
542 for ( i
= 0; i
< 12; i
++ ) {
543 name
= mw
.language
.months
.names
[ i
].toLowerCase();
544 ts
.monthNames
[ name
] = i
+ 1;
545 regex
.push( mw
.RegExp
.escape( name
) );
546 name
= mw
.language
.months
.genitive
[ i
].toLowerCase();
547 ts
.monthNames
[ name
] = i
+ 1;
548 regex
.push( mw
.RegExp
.escape( name
) );
549 name
= mw
.language
.months
.abbrev
[ i
].toLowerCase().replace( '.', '' );
550 ts
.monthNames
[ name
] = i
+ 1;
551 regex
.push( mw
.RegExp
.escape( name
) );
554 // Build piped string
555 regex
= regex
.join( '|' );
558 // Any date formated with . , ' - or /
559 ts
.dateRegex
[ 0 ] = new RegExp( /^\s*(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{2,4})\s*?/i );
561 // Written Month name, dmy
562 ts
.dateRegex
[ 1 ] = new RegExp( '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
564 // Written Month name, mdy
565 ts
.dateRegex
[ 2 ] = new RegExp( '^\\s*(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
570 * Replace all rowspanned cells in the body with clones in each row, so sorting
571 * need not worry about them.
573 * @param {jQuery} $table jQuery object for a <table>
575 function explodeRowspans( $table
) {
576 var spanningRealCellIndex
, rowSpan
, colSpan
,
577 cell
, cellData
, i
, $tds
, $clone
, $nextRows
,
578 rowspanCells
= $table
.find( '> tbody > tr > [rowspan]' ).get();
581 if ( !rowspanCells
.length
) {
585 // First, we need to make a property like cellIndex but taking into
586 // account colspans. We also cache the rowIndex to avoid having to take
587 // cell.parentNode.rowIndex in the sorting function below.
588 $table
.find( '> tbody > tr' ).each( function () {
591 l
= this.cells
.length
;
592 for ( i
= 0; i
< l
; i
++ ) {
593 $( this.cells
[ i
] ).data( 'tablesorter', {
595 realRowIndex
: this.rowIndex
597 col
+= this.cells
[ i
].colSpan
;
601 // Split multi row cells into multiple cells with the same content.
602 // Sort by column then row index to avoid problems with odd table structures.
603 // Re-sort whenever a rowspanned cell's realCellIndex is changed, because it
604 // might change the sort order.
605 function resortCells() {
609 rowspanCells
= rowspanCells
.sort( function ( a
, b
) {
610 cellAData
= $.data( a
, 'tablesorter' );
611 cellBData
= $.data( b
, 'tablesorter' );
612 ret
= cellAData
.realCellIndex
- cellBData
.realCellIndex
;
614 ret
= cellAData
.realRowIndex
- cellBData
.realRowIndex
;
618 $.each( rowspanCells
, function () {
619 $.data( this, 'tablesorter' ).needResort
= false;
624 function filterfunc() {
625 return $.data( this, 'tablesorter' ).realCellIndex
>= spanningRealCellIndex
;
628 function fixTdCellIndex() {
629 $.data( this, 'tablesorter' ).realCellIndex
+= colSpan
;
630 if ( this.rowSpan
> 1 ) {
631 $.data( this, 'tablesorter' ).needResort
= true;
635 while ( rowspanCells
.length
) {
636 if ( $.data( rowspanCells
[ 0 ], 'tablesorter' ).needResort
) {
640 cell
= rowspanCells
.shift();
641 cellData
= $.data( cell
, 'tablesorter' );
642 rowSpan
= cell
.rowSpan
;
643 colSpan
= cell
.colSpan
;
644 spanningRealCellIndex
= cellData
.realCellIndex
;
646 $nextRows
= $( cell
).parent().nextAll();
647 for ( i
= 0; i
< rowSpan
- 1; i
++ ) {
648 $tds
= $( $nextRows
[ i
].cells
).filter( filterfunc
);
649 $clone
= $( cell
).clone();
650 $clone
.data( 'tablesorter', {
651 realCellIndex
: spanningRealCellIndex
,
652 realRowIndex
: cellData
.realRowIndex
+ i
,
656 $tds
.each( fixTdCellIndex
);
657 $tds
.first().before( $clone
);
659 $nextRows
.eq( i
).append( $clone
);
666 * Build index to handle colspanned cells in the body.
667 * Set the cell index for each column in an array,
668 * so that colspaned cells set multiple in this array.
669 * columnToCell[collumnIndex] point at the real cell in this row.
671 * @param {jQuery} $table object for a <table>
673 function manageColspans( $table
) {
675 $rows
= $table
.find( '> tbody > tr' ),
676 totalRows
= $rows
.length
|| 0,
677 config
= $table
.data( 'tablesorter' ).config
,
678 columns
= config
.columns
,
679 columnToCell
, cellsInRow
, index
;
681 for ( i
= 0; i
< totalRows
; i
++ ) {
683 $row
= $rows
.eq( i
);
684 // if this is a child row, continue to the next row (as buildCache())
685 if ( $row
.hasClass( config
.cssChildRow
) ) {
686 // go to the next for loop
691 cellsInRow
= ( $row
[ 0 ].cells
.length
) || 0; // all cells in this row
692 index
= 0; // real cell index in this row
693 for ( j
= 0; j
< columns
; index
++ ) {
694 if ( index
=== cellsInRow
) {
695 // Row with cells less than columns: add empty cell
696 $row
.append( '<td>' );
699 for ( k
= 0; k
< $row
[ 0 ].cells
[ index
].colSpan
; k
++ ) {
700 columnToCell
[ j
++ ] = index
;
704 $row
.data( 'columnToCell', columnToCell
);
708 function buildCollationTable() {
709 ts
.collationTable
= mw
.config
.get( 'tableSorterCollation' );
710 ts
.collationRegex
= null;
711 if ( ts
.collationTable
) {
715 // Build array of key names
716 for ( key
in ts
.collationTable
) {
717 // Check hasOwn to be safe
718 if ( ts
.collationTable
.hasOwnProperty( key
) ) {
723 ts
.collationRegex
= new RegExp( '[' + keys
.join( '' ) + ']', 'ig' );
728 function cacheRegexs() {
734 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/ )
737 new RegExp( /(^[£$€¥]|[£$€¥]$)/ ),
738 new RegExp( /[£$€¥]/g )
741 new RegExp( /^(https?|ftp|file):\/\/$/ ),
742 new RegExp( /(https?|ftp|file):\/\// )
745 new RegExp( /^([-+]?\d{1,4})-([01]\d)-([0-3]\d)([T\s]((([01]\d|2[0-3])(:?[0-5]\d)?|24:?00)?(:?([0-5]\d|60))?([.,]\d+)?)([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?/ ),
746 new RegExp( /^([-+]?\d{1,4})-([01]\d)-([0-3]\d)/ )
749 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)))$/ )
752 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/ )
758 * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
759 * structure [ [ Integer , Integer ], ... ]
761 * @param sortObjects {Array} List of sort objects.
762 * @return {Array} List of internal sort definitions.
765 function convertSortList( sortObjects
) {
767 $.each( sortObjects
, function ( i
, sortObject
) {
768 $.each( sortObject
, function ( columnIndex
, order
) {
769 var orderIndex
= ( order
=== 'desc' ) ? 1 : 0;
770 sortList
.push( [ parseInt( columnIndex
, 10 ), orderIndex
] );
780 cssHeader
: 'headerSort',
781 cssAsc
: 'headerSortUp',
782 cssDesc
: 'headerSortDown',
783 cssChildRow
: 'expand-child',
784 sortMultiSortKey
: 'shiftKey',
785 unsortableClass
: 'unsortable',
787 cancelSelection
: true,
799 * @param {jQuery} $tables
800 * @param {Object} [settings]
802 construct: function ( $tables
, settings
) {
803 return $tables
.each( function ( i
, table
) {
804 // Declare and cache.
805 var $headers
, cache
, config
, sortCSS
, sortMsg
,
810 if ( !table
.tBodies
) {
813 if ( !table
.tHead
) {
814 // No thead found. Look for rows with <th>s and
815 // move them into a <thead> tag or a <tfoot> tag
816 emulateTHeadAndFoot( $table
);
818 // Still no thead? Then quit
819 if ( !table
.tHead
) {
823 $table
.addClass( 'jquery-tablesorter' );
826 config
= $.extend( {}, $.tablesorter
.defaultOptions
, settings
);
828 // Save the settings where they read
829 $.data( table
, 'tablesorter', { config
: config
} );
831 // Get the CSS class names, could be done elsewhere
832 sortCSS
= [ config
.cssDesc
, config
.cssAsc
];
833 sortMsg
= [ mw
.msg( 'sort-descending' ), mw
.msg( 'sort-ascending' ) ];
836 $headers
= buildHeaders( table
, sortMsg
);
838 // Grab and process locale settings.
839 buildTransformTable();
842 // Precaching regexps can bring 10 fold
843 // performance improvements in some browsers.
846 function setupForFirstSort() {
849 // Defer buildCollationTable to first sort. As user and site scripts
850 // may customize tableSorterCollation but load after $.ready(), other
851 // scripts may call .tablesorter() before they have done the
852 // tableSorterCollation customizations.
853 buildCollationTable();
855 // Legacy fix of .sortbottoms
856 // Wrap them inside a tfoot (because that's what they actually want to be)
857 // and put the <tfoot> at the end of the <table>
859 $sortbottoms
= $table
.find( '> tbody > tr.sortbottom' );
860 if ( $sortbottoms
.length
) {
861 $tfoot
= $table
.children( 'tfoot' );
862 if ( $tfoot
.length
) {
863 $tfoot
.eq( 0 ).prepend( $sortbottoms
);
865 $table
.append( $( '<tfoot>' ).append( $sortbottoms
) );
869 explodeRowspans( $table
);
870 manageColspans( $table
);
872 // Try to auto detect column type, and store in tables config
873 config
.parsers
= buildParserCache( table
, $headers
);
876 // Apply event handling to headers
877 // this is too big, perhaps break it out?
878 $headers
.on( 'keypress click', function ( e
) {
879 var cell
, $cell
, columns
, newSortList
, i
,
883 if ( e
.type
=== 'click' && e
.target
.nodeName
.toLowerCase() === 'a' ) {
884 // The user clicked on a link inside a table header.
885 // Do nothing and let the default link click action continue.
889 if ( e
.type
=== 'keypress' && e
.which
!== 13 ) {
890 // Only handle keypresses on the "Enter" key.
898 // Build the cache for the tbody cells
899 // to share between calculations for this sort action.
900 // Re-calculated each time a sort action is performed due to possiblity
901 // that sort values change. Shouldn't be too expensive, but if it becomes
902 // too slow an event based system should be implemented somehow where
903 // cells get event .change() and bubbles up to the <table> here
904 cache
= buildCache( table
);
906 totalRows
= ( $table
[ 0 ].tBodies
[ 0 ] && $table
[ 0 ].tBodies
[ 0 ].rows
.length
) || 0;
907 if ( totalRows
> 0 ) {
911 // Get current column sort order
913 order
: $cell
.data( 'count' ) % 2,
914 count
: $cell
.data( 'count' ) + 1
918 // Get current column index
919 columns
= config
.headerToColumns
[ $cell
.data( 'headerIndex' ) ];
920 newSortList
= $.map( columns
, function ( c
) {
921 // jQuery "helpfully" flattens the arrays...
922 return [ [ c
, $cell
.data( 'order' ) ] ];
924 // Index of first column belonging to this header
927 if ( !e
[ config
.sortMultiSortKey
] ) {
928 // User only wants to sort on one column set
929 // Flush the sort list and add new columns
930 config
.sortList
= newSortList
;
932 // Multi column sorting
933 // It is not possible for one column to belong to multiple headers,
934 // so this is okay - we don't need to check for every value in the columns array
935 if ( isValueInArray( i
, config
.sortList
) ) {
936 // The user has clicked on an already sorted column.
937 // Reverse the sorting direction for all tables.
938 for ( j
= 0; j
< config
.sortList
.length
; j
++ ) {
939 s
= config
.sortList
[ j
];
940 o
= config
.headerList
[ config
.columnToHeader
[ s
[ 0 ] ] ];
941 if ( isValueInArray( s
[ 0 ], newSortList
) ) {
942 $( o
).data( 'count', s
[ 1 ] + 1 );
943 s
[ 1 ] = $( o
).data( 'count' ) % 2;
947 // Add columns to sort list array
948 config
.sortList
= config
.sortList
.concat( newSortList
);
952 // Reset order/counts of cells not affected by sorting
953 setHeadersOrder( $headers
, config
.sortList
, config
.headerToColumns
);
955 // Set CSS for headers
956 setHeadersCss( $table
[ 0 ], $headers
, config
.sortList
, sortCSS
, sortMsg
, config
.columnToHeader
);
958 $table
[ 0 ], multisort( $table
[ 0 ], config
.sortList
, cache
)
961 // Stop normal event by returning false
966 } ).mousedown( function () {
967 if ( config
.cancelSelection
) {
968 this.onselectstart = function () {
976 * Sorts the table. If no sorting is specified by passing a list of sort
977 * objects, the table is sorted according to the initial sorting order.
978 * Passing an empty array will reset sorting (basically just reset the headers
979 * making the table appear unsorted).
981 * @param {Array} [sortList] List of sort objects.
983 $table
.data( 'tablesorter' ).sort = function ( sortList
) {
989 if ( sortList
=== undefined ) {
990 sortList
= config
.sortList
;
991 } else if ( sortList
.length
> 0 ) {
992 sortList
= convertSortList( sortList
);
995 // Set each column's sort count to be able to determine the correct sort
996 // order when clicking on a header cell the next time
997 setHeadersOrder( $headers
, sortList
, config
.headerToColumns
);
999 // re-build the cache for the tbody cells
1000 cache
= buildCache( table
);
1002 // set css for headers
1003 setHeadersCss( table
, $headers
, sortList
, sortCSS
, sortMsg
, config
.columnToHeader
);
1005 // sort the table and append it to the dom
1006 appendToTable( table
, multisort( table
, sortList
, cache
) );
1010 if ( config
.sortList
.length
> 0 ) {
1011 config
.sortList
= convertSortList( config
.sortList
);
1012 $table
.data( 'tablesorter' ).sort();
1018 addParser: function ( parser
) {
1020 len
= parsers
.length
,
1022 for ( i
= 0; i
< len
; i
++ ) {
1023 if ( parsers
[ i
].id
.toLowerCase() === parser
.id
.toLowerCase() ) {
1028 parsers
.push( parser
);
1032 formatDigit: function ( s
) {
1034 if ( ts
.transformTable
!== false ) {
1036 for ( p
= 0; p
< s
.length
; p
++ ) {
1038 if ( c
in ts
.transformTable
) {
1039 out
+= ts
.transformTable
[ c
];
1046 i
= parseFloat( s
.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
1047 return isNaN( i
) ? 0 : i
;
1050 formatFloat: function ( s
) {
1051 var i
= parseFloat( s
);
1052 return isNaN( i
) ? 0 : i
;
1055 formatInt: function ( s
) {
1056 var i
= parseInt( s
, 10 );
1057 return isNaN( i
) ? 0 : i
;
1060 clearTableBody: function ( table
) {
1061 $( table
.tBodies
[ 0 ] ).empty();
1064 getParser: function ( id
) {
1065 buildTransformTable();
1068 buildCollationTable();
1070 return getParserById( id
);
1073 getParsers: function () { // for table diagnosis
1081 // Register as jQuery prototype method
1082 $.fn
.tablesorter = function ( settings
) {
1083 return ts
.construct( this, settings
);
1086 // Add default parsers
1092 format: function ( s
) {
1093 s
= $.trim( s
.toLowerCase() );
1094 if ( ts
.collationRegex
) {
1095 var tsc
= ts
.collationTable
;
1096 s
= s
.replace( ts
.collationRegex
, function ( match
) {
1097 var r
= tsc
[ match
] ? tsc
[ match
] : tsc
[ match
.toUpperCase() ];
1098 return r
.toLowerCase();
1108 is: function ( s
) {
1109 return ts
.rgx
.IPAddress
[ 0 ].test( s
);
1111 format: function ( s
) {
1116 for ( i
= 0; i
< len
; i
++ ) {
1118 if ( item
.length
=== 1 ) {
1120 } else if ( item
.length
=== 2 ) {
1126 return $.tablesorter
.formatFloat( r
);
1133 is: function ( s
) {
1134 return ts
.rgx
.currency
[ 0 ].test( s
);
1136 format: function ( s
) {
1137 return $.tablesorter
.formatDigit( s
.replace( ts
.rgx
.currency
[ 1 ], '' ) );
1144 is: function ( s
) {
1145 return ts
.rgx
.url
[ 0 ].test( s
);
1147 format: function ( s
) {
1148 return $.trim( s
.replace( ts
.rgx
.url
[ 1 ], '' ) );
1155 is: function ( s
) {
1156 return ts
.rgx
.isoDate
[ 0 ].test( s
);
1158 format: function ( s
) {
1161 if ( !Date
.prototype.toISOString
) {
1162 // Old browsers don't understand iso, Fallback to US date parsing and ignore the time part.
1163 matches
= $.trim( s
).match( ts
.rgx
.isoDate
[ 1 ] );
1165 isodate
= new Date( matches
[ 2 ] + '/' + matches
[ 3 ] + '/' + matches
[ 1 ] );
1167 return $.tablesorter
.formatFloat( 0 );
1170 matches
= s
.match( ts
.rgx
.isoDate
[ 0 ] );
1172 isodate
= new Date( $.trim( matches
[ 0 ] ) );
1174 return $.tablesorter
.formatFloat( 0 );
1177 return $.tablesorter
.formatFloat( ( isodate
!== undefined ) ? isodate
.getTime() : 0 );
1184 is: function ( s
) {
1185 return ts
.rgx
.usLongDate
[ 0 ].test( s
);
1187 format: function ( s
) {
1188 return $.tablesorter
.formatFloat( new Date( s
).getTime() );
1195 is: function ( s
) {
1196 return ( ts
.dateRegex
[ 0 ].test( s
) || ts
.dateRegex
[ 1 ].test( s
) || ts
.dateRegex
[ 2 ].test( s
) );
1198 format: function ( s
) {
1200 s
= $.trim( s
.toLowerCase() );
1202 if ( ( match
= s
.match( ts
.dateRegex
[ 0 ] ) ) !== null ) {
1203 if ( mw
.config
.get( 'wgDefaultDateFormat' ) === 'mdy' || mw
.config
.get( 'wgPageContentLanguage' ) === 'en' ) {
1204 s
= [ match
[ 3 ], match
[ 1 ], match
[ 2 ] ];
1205 } else if ( mw
.config
.get( 'wgDefaultDateFormat' ) === 'dmy' ) {
1206 s
= [ match
[ 3 ], match
[ 2 ], match
[ 1 ] ];
1208 // If we get here, we don't know which order the dd-dd-dddd
1209 // date is in. So return something not entirely invalid.
1212 } else if ( ( match
= s
.match( ts
.dateRegex
[ 1 ] ) ) !== null ) {
1213 s
= [ match
[ 3 ], String( ts
.monthNames
[ match
[ 2 ] ] ), match
[ 1 ] ];
1214 } else if ( ( match
= s
.match( ts
.dateRegex
[ 2 ] ) ) !== null ) {
1215 s
= [ match
[ 3 ], String( ts
.monthNames
[ match
[ 1 ] ] ), match
[ 2 ] ];
1217 // Should never get here
1221 // Pad Month and Day
1222 if ( s
[ 1 ].length
=== 1 ) {
1223 s
[ 1 ] = '0' + s
[ 1 ];
1225 if ( s
[ 2 ].length
=== 1 ) {
1226 s
[ 2 ] = '0' + s
[ 2 ];
1229 if ( ( y
= parseInt( s
[ 0 ], 10 ) ) < 100 ) {
1230 // Guestimate years without centuries
1237 while ( s
[ 0 ].length
< 4 ) {
1238 s
[ 0 ] = '0' + s
[ 0 ];
1240 return parseInt( s
.join( '' ), 10 );
1247 is: function ( s
) {
1248 return ts
.rgx
.time
[ 0 ].test( s
);
1250 format: function ( s
) {
1251 return $.tablesorter
.formatFloat( new Date( '2000/01/01 ' + s
).getTime() );
1258 is: function ( s
) {
1259 return $.tablesorter
.numberRegex
.test( $.trim( s
) );
1261 format: function ( s
) {
1262 return $.tablesorter
.formatDigit( s
);
1267 }( jQuery
, mediaWiki
) );