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
) {
65 /* Parser utility functions */
67 function getParserById( name
) {
69 for ( i
= 0; i
< parsers
.length
; i
++ ) {
70 if ( parsers
[ i
].id
.toLowerCase() === name
.toLowerCase() ) {
77 function getElementSortKey( node
) {
78 var $node
= $( node
),
79 // Use data-sort-value attribute.
80 // Use data() instead of attr() so that live value changes
81 // are processed as well (bug 38152).
82 data
= $node
.data( 'sortValue' );
84 if ( data
!== null && data
!== undefined ) {
85 // Cast any numbers or other stuff to a string, methods
86 // like charAt, toLowerCase and split are expected.
87 return String( data
);
92 if ( node
.tagName
.toLowerCase() === 'img' ) {
93 return $node
.attr( 'alt' ) || ''; // handle undefined alt
95 return $.map( $.makeArray( node
.childNodes
), function ( elem
) {
96 if ( elem
.nodeType
=== Node
.ELEMENT_NODE
) {
97 return getElementSortKey( elem
);
99 return $.text( elem
);
103 function detectParserForColumn( table
, rows
, column
) {
104 var l
= parsers
.length
,
105 config
= $( table
).data( 'tablesorter' ).config
,
108 // Start with 1 because 0 is the fallback parser
114 needed
= ( rows
.length
> 4 ) ? 5 : rows
.length
;
117 // if this is a child row, continue to the next row (as buildCache())
118 if ( rows
[ rowIndex
] && !$( rows
[ rowIndex
] ).hasClass( config
.cssChildRow
) ) {
119 if ( rowIndex
!== lastRowIndex
) {
120 lastRowIndex
= rowIndex
;
121 cellIndex
= $( rows
[ rowIndex
] ).data( 'columnToCell' )[ column
];
122 nodeValue
= $.trim( getElementSortKey( rows
[ rowIndex
].cells
[ cellIndex
] ) );
128 if ( nodeValue
!== '' ) {
129 if ( parsers
[ i
].is( nodeValue
, table
) ) {
132 if ( concurrent
>= needed
) {
133 // Confirmed the parser for multiple cells, let's return it
137 // Check next parser, reset rows
147 if ( rowIndex
>= rows
.length
) {
148 if ( concurrent
>= rows
.length
- empty
) {
149 // Confirmed the parser for all filled cells
152 // Check next parser, reset rows
161 // 0 is always the generic parser (text)
165 function buildParserCache( table
, $headers
) {
166 var sortType
, len
, j
, parser
,
167 rows
= table
.tBodies
[ 0 ].rows
,
168 config
= $( table
).data( 'tablesorter' ).config
,
172 len
= config
.columns
;
173 for ( j
= 0; j
< len
; j
++ ) {
175 sortType
= $headers
.eq( config
.columnToHeader
[ j
] ).data( 'sortType' );
176 if ( sortType
!== undefined ) {
177 parser
= getParserById( sortType
);
180 if ( parser
=== false ) {
181 parser
= detectParserForColumn( table
, rows
, j
);
184 parsers
.push( parser
);
190 /* Other utility functions */
192 function buildCache( table
) {
193 var i
, j
, $row
, cols
,
194 totalRows
= ( table
.tBodies
[ 0 ] && table
.tBodies
[ 0 ].rows
.length
) || 0,
195 config
= $( table
).data( 'tablesorter' ).config
,
196 parsers
= config
.parsers
,
197 len
= parsers
.length
,
204 for ( i
= 0; i
< totalRows
; i
++ ) {
206 // Add the table data to main data array
207 $row
= $( table
.tBodies
[ 0 ].rows
[ i
] );
210 // if this is a child row, add it to the last row's children and
211 // continue to the next row
212 if ( $row
.hasClass( config
.cssChildRow
) ) {
213 cache
.row
[ cache
.row
.length
- 1 ] = cache
.row
[ cache
.row
.length
- 1 ].add( $row
);
214 // go to the next for loop
218 cache
.row
.push( $row
);
220 for ( j
= 0; j
< len
; j
++ ) {
221 cellIndex
= $row
.data( 'columnToCell' )[ j
];
222 cols
.push( parsers
[ j
].format( getElementSortKey( $row
[ 0 ].cells
[ cellIndex
] ) ) );
225 cols
.push( cache
.normalized
.length
); // add position for rowCache
226 cache
.normalized
.push( cols
);
233 function appendToTable( table
, cache
) {
236 normalized
= cache
.normalized
,
237 totalRows
= normalized
.length
,
238 checkCell
= ( normalized
[ 0 ].length
- 1 ),
239 fragment
= document
.createDocumentFragment();
241 for ( i
= 0; i
< totalRows
; i
++ ) {
242 pos
= normalized
[ i
][ checkCell
];
244 l
= row
[ pos
].length
;
245 for ( j
= 0; j
< l
; j
++ ) {
246 fragment
.appendChild( row
[ pos
][ j
] );
250 table
.tBodies
[ 0 ].appendChild( fragment
);
252 $( table
).trigger( 'sortEnd.tablesorter' );
256 * Find all header rows in a thead-less table and put them in a <thead> tag.
257 * This only treats a row as a header row if it contains only <th>s (no <td>s)
258 * and if it is preceded entirely by header rows. The algorithm stops when
259 * it encounters the first non-header row.
261 * After this, it will look at all rows at the bottom for footer rows
262 * And place these in a tfoot using similar rules.
264 * @param {jQuery} $table object for a <table>
266 function emulateTHeadAndFoot( $table
) {
267 var $thead
, $tfoot
, i
, len
,
268 $rows
= $table
.find( '> tbody > tr' );
269 if ( !$table
.get( 0 ).tHead
) {
270 $thead
= $( '<thead>' );
271 $rows
.each( function () {
272 if ( $( this ).children( 'td' ).length
) {
273 // This row contains a <td>, so it's not a header row
277 $thead
.append( this );
279 $table
.find( ' > tbody:first' ).before( $thead
);
281 if ( !$table
.get( 0 ).tFoot
) {
282 $tfoot
= $( '<tfoot>' );
284 for ( i
= len
- 1; i
>= 0; i
-- ) {
285 if ( $( $rows
[ i
] ).children( 'td' ).length
) {
288 $tfoot
.prepend( $( $rows
[ i
] ) );
290 $table
.append( $tfoot
);
294 function uniqueElements( array
) {
296 $.each( array
, function ( i
, elem
) {
297 if ( elem
!== undefined && $.inArray( elem
, uniques
) === -1 ) {
298 uniques
.push( elem
);
304 function buildHeaders( table
, msg
) {
305 var config
= $( table
).data( 'tablesorter' ).config
,
317 $tableHeaders
= $( [] ),
318 $tableRows
= $( 'thead:eq(0) > tr', table
);
320 if ( $tableRows
.length
<= 1 ) {
321 $tableHeaders
= $tableRows
.children( 'th' );
325 // Loop through all the dom cells of the thead
326 $tableRows
.each( function ( rowIndex
, row
) {
327 $.each( row
.cells
, function ( columnIndex
, cell
) {
331 rowspan
= Number( cell
.rowSpan
);
332 colspan
= Number( cell
.colSpan
);
334 // Skip the spots in the exploded matrix that are already filled
335 while ( exploded
[ rowIndex
] && exploded
[ rowIndex
][ columnIndex
] !== undefined ) {
339 // Find the actual dimensions of the thead, by placing each cell
340 // in the exploded matrix rowspan times colspan times, with the proper offsets
341 for ( matrixColumnIndex
= columnIndex
; matrixColumnIndex
< columnIndex
+ colspan
; ++matrixColumnIndex
) {
342 for ( matrixRowIndex
= rowIndex
; matrixRowIndex
< rowIndex
+ rowspan
; ++matrixRowIndex
) {
343 if ( !exploded
[ matrixRowIndex
] ) {
344 exploded
[ matrixRowIndex
] = [];
346 exploded
[ matrixRowIndex
][ matrixColumnIndex
] = cell
;
351 // We want to find the row that has the most columns (ignoring colspan)
352 $.each( exploded
, function ( index
, cellArray
) {
353 headerCount
= $( uniqueElements( cellArray
) ).filter( 'th' ).length
;
354 if ( headerCount
>= maxSeen
) {
355 maxSeen
= headerCount
;
359 // We cannot use $.unique() here because it sorts into dom order, which is undesirable
360 $tableHeaders
= $( uniqueElements( exploded
[ longestTR
] ) ).filter( 'th' );
363 // as each header can span over multiple columns (using colspan=N),
364 // we have to bidirectionally map headers to their columns and columns to their headers
365 config
.columnToHeader
= [];
366 config
.headerToColumns
= [];
367 config
.headerList
= [];
369 $tableHeaders
.each( function () {
373 if ( !$cell
.hasClass( config
.unsortableClass
) ) {
375 .addClass( config
.cssHeader
)
376 .prop( 'tabIndex', 0 )
378 role
: 'columnheader button',
382 for ( k
= 0; k
< this.colSpan
; k
++ ) {
383 config
.columnToHeader
[ colspanOffset
+ k
] = headerIndex
;
384 columns
.push( colspanOffset
+ k
);
387 config
.headerToColumns
[ headerIndex
] = columns
;
390 headerIndex
: headerIndex
,
395 // add only sortable cells to headerList
396 config
.headerList
[ headerIndex
] = this;
400 colspanOffset
+= this.colSpan
;
403 // number of columns with extended colspan, inclusive unsortable
404 // parsers[j], cache[][j], columnToHeader[j], columnToCell[j] have so many elements
405 config
.columns
= colspanOffset
;
407 return $tableHeaders
.not( '.' + config
.unsortableClass
);
410 function isValueInArray( v
, a
) {
412 for ( i
= 0; i
< a
.length
; i
++ ) {
413 if ( a
[ i
][ 0 ] === v
) {
421 * Sets the sort count of the columns that are not affected by the sorting to have them sorted
422 * in default (ascending) order when their header cell is clicked the next time.
424 * @param {jQuery} $headers
425 * @param {number[][]} sortList
426 * @param {number[][]} headerToColumns
428 function setHeadersOrder( $headers
, sortList
, headerToColumns
) {
429 // Loop through all headers to retrieve the indices of the columns the header spans across:
430 $.each( headerToColumns
, function ( headerIndex
, columns
) {
432 $.each( columns
, function ( i
, columnIndex
) {
433 var header
= $headers
[ headerIndex
],
434 $header
= $( header
);
436 if ( !isValueInArray( columnIndex
, sortList
) ) {
437 // Column shall not be sorted: Reset header count and order.
443 // Column shall be sorted: Apply designated count and order.
444 $.each( sortList
, function ( j
, sortColumn
) {
445 if ( sortColumn
[ 0 ] === i
) {
447 order
: sortColumn
[ 1 ],
448 count
: sortColumn
[ 1 ] + 1
459 function setHeadersCss( table
, $headers
, list
, css
, msg
, columnToHeader
) {
460 // Remove all header information and reset titles to default message
461 $headers
.removeClass( css
[ 0 ] ).removeClass( css
[ 1 ] ).attr( 'title', msg
[ 1 ] );
463 for ( var i
= 0; i
< list
.length
; i
++ ) {
465 .eq( columnToHeader
[ list
[ i
][ 0 ] ] )
466 .addClass( css
[ list
[ i
][ 1 ] ] )
467 .attr( 'title', msg
[ list
[ i
][ 1 ] ] );
471 function sortText( a
, b
) {
472 return ( ( a
< b
) ? -1 : ( ( a
> b
) ? 1 : 0 ) );
475 function sortTextDesc( a
, b
) {
476 return ( ( b
< a
) ? -1 : ( ( b
> a
) ? 1 : 0 ) );
479 function multisort( table
, sortList
, cache
) {
483 for ( i
= 0; i
< sortList
.length
; i
++ ) {
484 sortFn
[ i
] = ( sortList
[ i
][ 1 ] ) ? sortTextDesc
: sortText
;
486 cache
.normalized
.sort( function ( array1
, array2
) {
488 for ( i
= 0; i
< sortList
.length
; i
++ ) {
489 col
= sortList
[ i
][ 0 ];
490 ret
= sortFn
[ i
].call( this, array1
[ col
], array2
[ col
] );
495 // Fall back to index number column to ensure stable sort
496 return sortText
.call( this, array1
[ array1
.length
- 1 ], array2
[ array2
.length
- 1 ] );
501 function buildTransformTable() {
502 var ascii
, localised
, i
, digitClass
,
503 digits
= '0123456789,.'.split( '' ),
504 separatorTransformTable
= mw
.config
.get( 'wgSeparatorTransformTable' ),
505 digitTransformTable
= mw
.config
.get( 'wgDigitTransformTable' );
507 if ( separatorTransformTable
=== null || ( separatorTransformTable
[ 0 ] === '' && digitTransformTable
[ 2 ] === '' ) ) {
508 ts
.transformTable
= false;
510 ts
.transformTable
= {};
512 // Unpack the transform table
513 ascii
= separatorTransformTable
[ 0 ].split( '\t' ).concat( digitTransformTable
[ 0 ].split( '\t' ) );
514 localised
= separatorTransformTable
[ 1 ].split( '\t' ).concat( digitTransformTable
[ 1 ].split( '\t' ) );
516 // Construct regexes for number identification
517 for ( i
= 0; i
< ascii
.length
; i
++ ) {
518 ts
.transformTable
[ localised
[ i
] ] = ascii
[ i
];
519 digits
.push( mw
.RegExp
.escape( localised
[ i
] ) );
522 digitClass
= '[' + digits
.join( '', digits
) + ']';
524 // We allow a trailing percent sign, which we just strip. This works fine
525 // if percents and regular numbers aren't being mixed.
526 ts
.numberRegex
= new RegExp( '^(' + '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
527 '|' + '[-+\u2212]?' + digitClass
+ '+[\\s\\xa0]*%?' + // Generic localised
531 function buildDateTable() {
537 for ( i
= 0; i
< 12; i
++ ) {
538 name
= mw
.language
.months
.names
[ i
].toLowerCase();
539 ts
.monthNames
[ name
] = i
+ 1;
540 regex
.push( mw
.RegExp
.escape( name
) );
541 name
= mw
.language
.months
.genitive
[ i
].toLowerCase();
542 ts
.monthNames
[ name
] = i
+ 1;
543 regex
.push( mw
.RegExp
.escape( name
) );
544 name
= mw
.language
.months
.abbrev
[ i
].toLowerCase().replace( '.', '' );
545 ts
.monthNames
[ name
] = i
+ 1;
546 regex
.push( mw
.RegExp
.escape( name
) );
549 // Build piped string
550 regex
= regex
.join( '|' );
553 // Any date formated with . , ' - or /
554 ts
.dateRegex
[ 0 ] = new RegExp( /^\s*(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{2,4})\s*?/i );
556 // Written Month name, dmy
557 ts
.dateRegex
[ 1 ] = new RegExp( '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
559 // Written Month name, mdy
560 ts
.dateRegex
[ 2 ] = new RegExp( '^\\s*(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
565 * Replace all rowspanned cells in the body with clones in each row, so sorting
566 * need not worry about them.
568 * @param {jQuery} $table jQuery object for a <table>
570 function explodeRowspans( $table
) {
571 var spanningRealCellIndex
, rowSpan
, colSpan
,
572 cell
, cellData
, i
, $tds
, $clone
, $nextRows
,
573 rowspanCells
= $table
.find( '> tbody > tr > [rowspan]' ).get();
576 if ( !rowspanCells
.length
) {
580 // First, we need to make a property like cellIndex but taking into
581 // account colspans. We also cache the rowIndex to avoid having to take
582 // cell.parentNode.rowIndex in the sorting function below.
583 $table
.find( '> tbody > tr' ).each( function () {
586 len
= this.cells
.length
;
587 for ( i
= 0; i
< len
; i
++ ) {
588 $( this.cells
[ i
] ).data( 'tablesorter', {
590 realRowIndex
: this.rowIndex
592 col
+= this.cells
[ i
].colSpan
;
596 // Split multi row cells into multiple cells with the same content.
597 // Sort by column then row index to avoid problems with odd table structures.
598 // Re-sort whenever a rowspanned cell's realCellIndex is changed, because it
599 // might change the sort order.
600 function resortCells() {
604 rowspanCells
= rowspanCells
.sort( function ( a
, b
) {
605 cellAData
= $.data( a
, 'tablesorter' );
606 cellBData
= $.data( b
, 'tablesorter' );
607 ret
= cellAData
.realCellIndex
- cellBData
.realCellIndex
;
609 ret
= cellAData
.realRowIndex
- cellBData
.realRowIndex
;
613 $.each( rowspanCells
, function () {
614 $.data( this, 'tablesorter' ).needResort
= false;
619 function filterfunc() {
620 return $.data( this, 'tablesorter' ).realCellIndex
>= spanningRealCellIndex
;
623 function fixTdCellIndex() {
624 $.data( this, 'tablesorter' ).realCellIndex
+= colSpan
;
625 if ( this.rowSpan
> 1 ) {
626 $.data( this, 'tablesorter' ).needResort
= true;
630 while ( rowspanCells
.length
) {
631 if ( $.data( rowspanCells
[ 0 ], 'tablesorter' ).needResort
) {
635 cell
= rowspanCells
.shift();
636 cellData
= $.data( cell
, 'tablesorter' );
637 rowSpan
= cell
.rowSpan
;
638 colSpan
= cell
.colSpan
;
639 spanningRealCellIndex
= cellData
.realCellIndex
;
641 $nextRows
= $( cell
).parent().nextAll();
642 for ( i
= 0; i
< rowSpan
- 1; i
++ ) {
643 $tds
= $( $nextRows
[ i
].cells
).filter( filterfunc
);
644 $clone
= $( cell
).clone();
645 $clone
.data( 'tablesorter', {
646 realCellIndex
: spanningRealCellIndex
,
647 realRowIndex
: cellData
.realRowIndex
+ i
,
651 $tds
.each( fixTdCellIndex
);
652 $tds
.first().before( $clone
);
654 $nextRows
.eq( i
).append( $clone
);
661 * Build index to handle colspanned cells in the body.
662 * Set the cell index for each column in an array,
663 * so that colspaned cells set multiple in this array.
664 * columnToCell[collumnIndex] point at the real cell in this row.
666 * @param {jQuery} $table object for a <table>
668 function manageColspans( $table
) {
670 $rows
= $table
.find( '> tbody > tr' ),
671 totalRows
= $rows
.length
|| 0,
672 config
= $table
.data( 'tablesorter' ).config
,
673 columns
= config
.columns
,
674 columnToCell
, cellsInRow
, index
;
676 for ( i
= 0; i
< totalRows
; i
++ ) {
678 $row
= $rows
.eq( i
);
679 // if this is a child row, continue to the next row (as buildCache())
680 if ( $row
.hasClass( config
.cssChildRow
) ) {
681 // go to the next for loop
686 cellsInRow
= ( $row
[ 0 ].cells
.length
) || 0; // all cells in this row
687 index
= 0; // real cell index in this row
688 for ( j
= 0; j
< columns
; index
++ ) {
689 if ( index
=== cellsInRow
) {
690 // Row with cells less than columns: add empty cell
691 $row
.append( '<td>' );
694 for ( k
= 0; k
< $row
[ 0 ].cells
[ index
].colSpan
; k
++ ) {
695 columnToCell
[ j
++ ] = index
;
699 $row
.data( 'columnToCell', columnToCell
);
703 function buildCollationTable() {
704 ts
.collationTable
= mw
.config
.get( 'tableSorterCollation' );
705 ts
.collationRegex
= null;
706 if ( ts
.collationTable
) {
710 // Build array of key names
711 for ( key
in ts
.collationTable
) {
712 // Check hasOwn to be safe
713 if ( ts
.collationTable
.hasOwnProperty( key
) ) {
718 ts
.collationRegex
= new RegExp( '[' + keys
.join( '' ) + ']', 'ig' );
723 function cacheRegexs() {
729 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/ )
732 new RegExp( /(^[£$€¥]|[£$€¥]$)/ ),
733 new RegExp( /[£$€¥]/g )
736 new RegExp( /^(https?|ftp|file):\/\/$/ ),
737 new RegExp( /(https?|ftp|file):\/\// )
740 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)?)?)?/ ),
741 new RegExp( /^([-+]?\d{1,4})-([01]\d)-([0-3]\d)/ )
744 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)))$/ )
747 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/ )
753 * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
754 * structure [ [ Integer , Integer ], ... ]
756 * @param {Array} sortObjects List of sort objects.
757 * @return {Array} List of internal sort definitions.
759 function convertSortList( sortObjects
) {
761 $.each( sortObjects
, function ( i
, sortObject
) {
762 $.each( sortObject
, function ( columnIndex
, order
) {
763 var orderIndex
= ( order
=== 'desc' ) ? 1 : 0;
764 sortList
.push( [ parseInt( columnIndex
, 10 ), orderIndex
] );
774 cssHeader
: 'headerSort',
775 cssAsc
: 'headerSortUp',
776 cssDesc
: 'headerSortDown',
777 cssChildRow
: 'expand-child',
778 sortMultiSortKey
: 'shiftKey',
779 unsortableClass
: 'unsortable',
781 cancelSelection
: true,
793 * @param {jQuery} $tables
794 * @param {Object} [settings]
796 construct: function ( $tables
, settings
) {
797 return $tables
.each( function ( i
, table
) {
798 // Declare and cache.
799 var $headers
, cache
, config
, sortCSS
, sortMsg
,
804 if ( !table
.tBodies
) {
807 if ( !table
.tHead
) {
808 // No thead found. Look for rows with <th>s and
809 // move them into a <thead> tag or a <tfoot> tag
810 emulateTHeadAndFoot( $table
);
812 // Still no thead? Then quit
813 if ( !table
.tHead
) {
817 $table
.addClass( 'jquery-tablesorter' );
820 config
= $.extend( {}, $.tablesorter
.defaultOptions
, settings
);
822 // Save the settings where they read
823 $.data( table
, 'tablesorter', { config
: config
} );
825 // Get the CSS class names, could be done elsewhere
826 sortCSS
= [ config
.cssDesc
, config
.cssAsc
];
827 sortMsg
= [ mw
.msg( 'sort-descending' ), mw
.msg( 'sort-ascending' ) ];
830 $headers
= buildHeaders( table
, sortMsg
);
832 // Grab and process locale settings.
833 buildTransformTable();
836 // Precaching regexps can bring 10 fold
837 // performance improvements in some browsers.
840 function setupForFirstSort() {
843 // Defer buildCollationTable to first sort. As user and site scripts
844 // may customize tableSorterCollation but load after $.ready(), other
845 // scripts may call .tablesorter() before they have done the
846 // tableSorterCollation customizations.
847 buildCollationTable();
849 // Legacy fix of .sortbottoms
850 // Wrap them inside a tfoot (because that's what they actually want to be)
851 // and put the <tfoot> at the end of the <table>
853 $sortbottoms
= $table
.find( '> tbody > tr.sortbottom' );
854 if ( $sortbottoms
.length
) {
855 $tfoot
= $table
.children( 'tfoot' );
856 if ( $tfoot
.length
) {
857 $tfoot
.eq( 0 ).prepend( $sortbottoms
);
859 $table
.append( $( '<tfoot>' ).append( $sortbottoms
) );
863 explodeRowspans( $table
);
864 manageColspans( $table
);
866 // Try to auto detect column type, and store in tables config
867 config
.parsers
= buildParserCache( table
, $headers
);
870 // Apply event handling to headers
871 // this is too big, perhaps break it out?
872 $headers
.on( 'keypress click', function ( e
) {
873 var cell
, $cell
, columns
, newSortList
, i
,
877 if ( e
.type
=== 'click' && e
.target
.nodeName
.toLowerCase() === 'a' ) {
878 // The user clicked on a link inside a table header.
879 // Do nothing and let the default link click action continue.
883 if ( e
.type
=== 'keypress' && e
.which
!== 13 ) {
884 // Only handle keypresses on the "Enter" key.
892 // Build the cache for the tbody cells
893 // to share between calculations for this sort action.
894 // Re-calculated each time a sort action is performed due to possiblity
895 // that sort values change. Shouldn't be too expensive, but if it becomes
896 // too slow an event based system should be implemented somehow where
897 // cells get event .change() and bubbles up to the <table> here
898 cache
= buildCache( table
);
900 totalRows
= ( $table
[ 0 ].tBodies
[ 0 ] && $table
[ 0 ].tBodies
[ 0 ].rows
.length
) || 0;
901 if ( totalRows
> 0 ) {
905 // Get current column sort order
907 order
: $cell
.data( 'count' ) % 2,
908 count
: $cell
.data( 'count' ) + 1
912 // Get current column index
913 columns
= config
.headerToColumns
[ $cell
.data( 'headerIndex' ) ];
914 newSortList
= $.map( columns
, function ( c
) {
915 // jQuery "helpfully" flattens the arrays...
916 return [ [ c
, $cell
.data( 'order' ) ] ];
918 // Index of first column belonging to this header
921 if ( !e
[ config
.sortMultiSortKey
] ) {
922 // User only wants to sort on one column set
923 // Flush the sort list and add new columns
924 config
.sortList
= newSortList
;
926 // Multi column sorting
927 // It is not possible for one column to belong to multiple headers,
928 // so this is okay - we don't need to check for every value in the columns array
929 if ( isValueInArray( i
, config
.sortList
) ) {
930 // The user has clicked on an already sorted column.
931 // Reverse the sorting direction for all tables.
932 for ( j
= 0; j
< config
.sortList
.length
; j
++ ) {
933 s
= config
.sortList
[ j
];
934 o
= config
.headerList
[ config
.columnToHeader
[ s
[ 0 ] ] ];
935 if ( isValueInArray( s
[ 0 ], newSortList
) ) {
936 $( o
).data( 'count', s
[ 1 ] + 1 );
937 s
[ 1 ] = $( o
).data( 'count' ) % 2;
941 // Add columns to sort list array
942 config
.sortList
= config
.sortList
.concat( newSortList
);
946 // Reset order/counts of cells not affected by sorting
947 setHeadersOrder( $headers
, config
.sortList
, config
.headerToColumns
);
949 // Set CSS for headers
950 setHeadersCss( $table
[ 0 ], $headers
, config
.sortList
, sortCSS
, sortMsg
, config
.columnToHeader
);
952 $table
[ 0 ], multisort( $table
[ 0 ], config
.sortList
, cache
)
955 // Stop normal event by returning false
960 } ).mousedown( function () {
961 if ( config
.cancelSelection
) {
962 this.onselectstart = function () {
970 * Sorts the table. If no sorting is specified by passing a list of sort
971 * objects, the table is sorted according to the initial sorting order.
972 * Passing an empty array will reset sorting (basically just reset the headers
973 * making the table appear unsorted).
975 * @param {Array} [sortList] List of sort objects.
977 $table
.data( 'tablesorter' ).sort = function ( sortList
) {
983 if ( sortList
=== undefined ) {
984 sortList
= config
.sortList
;
985 } else if ( sortList
.length
> 0 ) {
986 sortList
= convertSortList( sortList
);
989 // Set each column's sort count to be able to determine the correct sort
990 // order when clicking on a header cell the next time
991 setHeadersOrder( $headers
, sortList
, config
.headerToColumns
);
993 // re-build the cache for the tbody cells
994 cache
= buildCache( table
);
996 // set css for headers
997 setHeadersCss( table
, $headers
, sortList
, sortCSS
, sortMsg
, config
.columnToHeader
);
999 // sort the table and append it to the dom
1000 appendToTable( table
, multisort( table
, sortList
, cache
) );
1004 if ( config
.sortList
.length
> 0 ) {
1005 config
.sortList
= convertSortList( config
.sortList
);
1006 $table
.data( 'tablesorter' ).sort();
1012 addParser: function ( parser
) {
1013 if ( !getParserById( parser
.id
) ) {
1014 parsers
.push( parser
);
1018 formatDigit: function ( s
) {
1020 if ( ts
.transformTable
!== false ) {
1022 for ( p
= 0; p
< s
.length
; p
++ ) {
1024 if ( c
in ts
.transformTable
) {
1025 out
+= ts
.transformTable
[ c
];
1032 i
= parseFloat( s
.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
1033 return isNaN( i
) ? 0 : i
;
1036 formatFloat: function ( s
) {
1037 var i
= parseFloat( s
);
1038 return isNaN( i
) ? 0 : i
;
1041 formatInt: function ( s
) {
1042 var i
= parseInt( s
, 10 );
1043 return isNaN( i
) ? 0 : i
;
1046 clearTableBody: function ( table
) {
1047 $( table
.tBodies
[ 0 ] ).empty();
1050 getParser: function ( id
) {
1051 buildTransformTable();
1054 buildCollationTable();
1056 return getParserById( id
);
1059 getParsers: function () { // for table diagnosis
1067 // Register as jQuery prototype method
1068 $.fn
.tablesorter = function ( settings
) {
1069 return ts
.construct( this, settings
);
1072 // Add default parsers
1078 format: function ( s
) {
1079 s
= $.trim( s
.toLowerCase() );
1080 if ( ts
.collationRegex
) {
1081 var tsc
= ts
.collationTable
;
1082 s
= s
.replace( ts
.collationRegex
, function ( match
) {
1083 var r
= tsc
[ match
] ? tsc
[ match
] : tsc
[ match
.toUpperCase() ];
1084 return r
.toLowerCase();
1094 is: function ( s
) {
1095 return ts
.rgx
.IPAddress
[ 0 ].test( s
);
1097 format: function ( s
) {
1101 for ( i
= 0; i
< a
.length
; i
++ ) {
1103 if ( item
.length
=== 1 ) {
1105 } else if ( item
.length
=== 2 ) {
1111 return $.tablesorter
.formatFloat( r
);
1118 is: function ( s
) {
1119 return ts
.rgx
.currency
[ 0 ].test( s
);
1121 format: function ( s
) {
1122 return $.tablesorter
.formatDigit( s
.replace( ts
.rgx
.currency
[ 1 ], '' ) );
1129 is: function ( s
) {
1130 return ts
.rgx
.url
[ 0 ].test( s
);
1132 format: function ( s
) {
1133 return $.trim( s
.replace( ts
.rgx
.url
[ 1 ], '' ) );
1140 is: function ( s
) {
1141 return ts
.rgx
.isoDate
[ 0 ].test( s
);
1143 format: function ( s
) {
1144 var isodate
, matches
;
1145 if ( !Date
.prototype.toISOString
) {
1146 // Old browsers don't understand iso, Fallback to US date parsing and ignore the time part.
1147 matches
= $.trim( s
).match( ts
.rgx
.isoDate
[ 1 ] );
1149 return $.tablesorter
.formatFloat( 0 );
1151 isodate
= new Date( matches
[ 2 ] + '/' + matches
[ 3 ] + '/' + matches
[ 1 ] );
1153 matches
= s
.match( ts
.rgx
.isoDate
[ 0 ] );
1155 return $.tablesorter
.formatFloat( 0 );
1157 isodate
= new Date( $.trim( matches
[ 0 ] ) );
1159 return $.tablesorter
.formatFloat( ( isodate
!== undefined ) ? isodate
.getTime() : 0 );
1166 is: function ( s
) {
1167 return ts
.rgx
.usLongDate
[ 0 ].test( s
);
1169 format: function ( s
) {
1170 return $.tablesorter
.formatFloat( new Date( s
).getTime() );
1177 is: function ( s
) {
1178 return ( ts
.dateRegex
[ 0 ].test( s
) || ts
.dateRegex
[ 1 ].test( s
) || ts
.dateRegex
[ 2 ].test( s
) );
1180 format: function ( s
) {
1182 s
= $.trim( s
.toLowerCase() );
1184 if ( ( match
= s
.match( ts
.dateRegex
[ 0 ] ) ) !== null ) {
1185 if ( mw
.config
.get( 'wgDefaultDateFormat' ) === 'mdy' || mw
.config
.get( 'wgPageContentLanguage' ) === 'en' ) {
1186 s
= [ match
[ 3 ], match
[ 1 ], match
[ 2 ] ];
1187 } else if ( mw
.config
.get( 'wgDefaultDateFormat' ) === 'dmy' ) {
1188 s
= [ match
[ 3 ], match
[ 2 ], match
[ 1 ] ];
1190 // If we get here, we don't know which order the dd-dd-dddd
1191 // date is in. So return something not entirely invalid.
1194 } else if ( ( match
= s
.match( ts
.dateRegex
[ 1 ] ) ) !== null ) {
1195 s
= [ match
[ 3 ], String( ts
.monthNames
[ match
[ 2 ] ] ), match
[ 1 ] ];
1196 } else if ( ( match
= s
.match( ts
.dateRegex
[ 2 ] ) ) !== null ) {
1197 s
= [ match
[ 3 ], String( ts
.monthNames
[ match
[ 1 ] ] ), match
[ 2 ] ];
1199 // Should never get here
1203 // Pad Month and Day
1204 if ( s
[ 1 ].length
=== 1 ) {
1205 s
[ 1 ] = '0' + s
[ 1 ];
1207 if ( s
[ 2 ].length
=== 1 ) {
1208 s
[ 2 ] = '0' + s
[ 2 ];
1211 if ( ( y
= parseInt( s
[ 0 ], 10 ) ) < 100 ) {
1212 // Guestimate years without centuries
1219 while ( s
[ 0 ].length
< 4 ) {
1220 s
[ 0 ] = '0' + s
[ 0 ];
1222 return parseInt( s
.join( '' ), 10 );
1229 is: function ( s
) {
1230 return ts
.rgx
.time
[ 0 ].test( s
);
1232 format: function ( s
) {
1233 return $.tablesorter
.formatFloat( new Date( '2000/01/01 ' + s
).getTime() );
1240 is: function ( s
) {
1241 return $.tablesorter
.numberRegex
.test( $.trim( s
) );
1243 format: function ( s
) {
1244 return $.tablesorter
.formatDigit( s
);
1249 }( jQuery
, mediaWiki
) );