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
,
112 // Start with 1 because 0 is the fallback parser
118 needed
= ( rows
.length
> 4 ) ? 5 : rows
.length
;
121 if ( rows
[ rowIndex
] ) {
122 if ( rowIndex
!== lastRowIndex
) {
123 lastRowIndex
= rowIndex
;
124 cellIndex
= $( rows
[ rowIndex
] ).data( 'columnToCell' )[ column
];
125 nodeValue
= $.trim( getElementSortKey( rows
[ rowIndex
].cells
[ cellIndex
] ) );
131 if ( nodeValue
!== '' ) {
132 if ( parsers
[ i
].is( nodeValue
, table
) ) {
135 if ( concurrent
>= needed
) {
136 // Confirmed the parser for multiple cells, let's return it
140 // Check next parser, reset rows
150 if ( rowIndex
>= rows
.length
) {
151 if ( concurrent
>= rows
.length
- empty
) {
152 // Confirmed the parser for all filled cells
155 // Check next parser, reset rows
164 // 0 is always the generic parser (text)
168 function buildParserCache( table
, $headers
) {
169 var sortType
, len
, j
, parser
,
170 rows
= table
.tBodies
[ 0 ].rows
,
171 config
= $( table
).data( 'tablesorter' ).config
,
175 len
= config
.columns
;
176 for ( j
= 0; j
< len
; j
++ ) {
178 sortType
= $headers
.eq( config
.columnToHeader
[ j
] ).data( 'sortType' );
179 if ( sortType
!== undefined ) {
180 parser
= getParserById( sortType
);
183 if ( parser
=== false ) {
184 parser
= detectParserForColumn( table
, rows
, j
);
187 parsers
.push( parser
);
193 /* Other utility functions */
195 function buildCache( table
) {
196 var i
, j
, $row
, cols
,
197 totalRows
= ( table
.tBodies
[ 0 ] && table
.tBodies
[ 0 ].rows
.length
) || 0,
198 config
= $( table
).data( 'tablesorter' ).config
,
199 parsers
= config
.parsers
,
200 len
= parsers
.length
,
207 for ( i
= 0; i
< totalRows
; i
++ ) {
209 // Add the table data to main data array
210 $row
= $( table
.tBodies
[ 0 ].rows
[ i
] );
213 // if this is a child row, add it to the last row's children and
214 // continue to the next row
215 if ( $row
.hasClass( config
.cssChildRow
) ) {
216 cache
.row
[ cache
.row
.length
- 1 ] = cache
.row
[ cache
.row
.length
- 1 ].add( $row
);
217 // go to the next for loop
221 cache
.row
.push( $row
);
223 for ( j
= 0; j
< len
; j
++ ) {
224 cellIndex
= $row
.data( 'columnToCell' )[ j
];
225 cols
.push( parsers
[ j
].format( getElementSortKey( $row
[ 0 ].cells
[ cellIndex
] ) ) );
228 cols
.push( cache
.normalized
.length
); // add position for rowCache
229 cache
.normalized
.push( cols
);
236 function appendToTable( table
, cache
) {
239 normalized
= cache
.normalized
,
240 totalRows
= normalized
.length
,
241 checkCell
= ( normalized
[ 0 ].length
- 1 ),
242 fragment
= document
.createDocumentFragment();
244 for ( i
= 0; i
< totalRows
; i
++ ) {
245 pos
= normalized
[ i
][ checkCell
];
247 l
= row
[ pos
].length
;
249 for ( j
= 0; j
< l
; j
++ ) {
250 fragment
.appendChild( row
[ pos
][ j
] );
254 table
.tBodies
[ 0 ].appendChild( fragment
);
256 $( table
).trigger( 'sortEnd.tablesorter' );
260 * Find all header rows in a thead-less table and put them in a <thead> tag.
261 * This only treats a row as a header row if it contains only <th>s (no <td>s)
262 * and if it is preceded entirely by header rows. The algorithm stops when
263 * it encounters the first non-header row.
265 * After this, it will look at all rows at the bottom for footer rows
266 * And place these in a tfoot using similar rules.
268 * @param {jQuery} $table object for a <table>
270 function emulateTHeadAndFoot( $table
) {
271 var $thead
, $tfoot
, i
, len
,
272 $rows
= $table
.find( '> tbody > tr' );
273 if ( !$table
.get( 0 ).tHead
) {
274 $thead
= $( '<thead>' );
275 $rows
.each( function () {
276 if ( $( this ).children( 'td' ).length
) {
277 // This row contains a <td>, so it's not a header row
281 $thead
.append( this );
283 $table
.find( ' > tbody:first' ).before( $thead
);
285 if ( !$table
.get( 0 ).tFoot
) {
286 $tfoot
= $( '<tfoot>' );
288 for ( i
= len
- 1; i
>= 0; i
-- ) {
289 if ( $( $rows
[ i
] ).children( 'td' ).length
) {
292 $tfoot
.prepend( $( $rows
[ i
] ) );
294 $table
.append( $tfoot
);
298 function uniqueElements( array
) {
300 $.each( array
, function ( index
, elem
) {
301 if ( elem
!== undefined && $.inArray( elem
, uniques
) === -1 ) {
302 uniques
.push( elem
);
308 function buildHeaders( table
, msg
) {
309 var config
= $( table
).data( 'tablesorter' ).config
,
321 $tableHeaders
= $( [] ),
322 $tableRows
= $( 'thead:eq(0) > tr', table
);
323 if ( $tableRows
.length
<= 1 ) {
324 $tableHeaders
= $tableRows
.children( 'th' );
328 // Loop through all the dom cells of the thead
329 $tableRows
.each( function ( rowIndex
, row
) {
330 $.each( row
.cells
, function ( columnIndex
, cell
) {
334 rowspan
= Number( cell
.rowSpan
);
335 colspan
= Number( cell
.colSpan
);
337 // Skip the spots in the exploded matrix that are already filled
338 while ( exploded
[ rowIndex
] && exploded
[ rowIndex
][ columnIndex
] !== undefined ) {
342 // Find the actual dimensions of the thead, by placing each cell
343 // in the exploded matrix rowspan times colspan times, with the proper offsets
344 for ( matrixColumnIndex
= columnIndex
; matrixColumnIndex
< columnIndex
+ colspan
; ++matrixColumnIndex
) {
345 for ( matrixRowIndex
= rowIndex
; matrixRowIndex
< rowIndex
+ rowspan
; ++matrixRowIndex
) {
346 if ( !exploded
[ matrixRowIndex
] ) {
347 exploded
[ matrixRowIndex
] = [];
349 exploded
[ matrixRowIndex
][ matrixColumnIndex
] = cell
;
354 // We want to find the row that has the most columns (ignoring colspan)
355 $.each( exploded
, function ( index
, cellArray
) {
356 headerCount
= $( uniqueElements( cellArray
) ).filter( 'th' ).length
;
357 if ( headerCount
>= maxSeen
) {
358 maxSeen
= headerCount
;
362 // We cannot use $.unique() here because it sorts into dom order, which is undesirable
363 $tableHeaders
= $( uniqueElements( exploded
[ longestTR
] ) ).filter( 'th' );
366 // as each header can span over multiple columns (using colspan=N),
367 // we have to bidirectionally map headers to their columns and columns to their headers
368 config
.columnToHeader
= [];
369 config
.headerToColumns
= [];
370 config
.headerList
= [];
372 $tableHeaders
.each( function () {
376 if ( !$cell
.hasClass( config
.unsortableClass
) ) {
378 .addClass( config
.cssHeader
)
379 .prop( 'tabIndex', 0 )
381 role
: 'columnheader button',
385 for ( k
= 0; k
< this.colSpan
; k
++ ) {
386 config
.columnToHeader
[ colspanOffset
+ k
] = headerIndex
;
387 columns
.push( colspanOffset
+ k
);
390 config
.headerToColumns
[ headerIndex
] = columns
;
393 headerIndex
: headerIndex
,
398 // add only sortable cells to headerList
399 config
.headerList
[ headerIndex
] = this;
403 colspanOffset
+= this.colSpan
;
406 // number of columns with extended colspan, inclusive unsortable
407 // parsers[j], cache[][j], columnToHeader[j], columnToCell[j] have so many elements
408 config
.columns
= colspanOffset
;
410 return $tableHeaders
.not( '.' + config
.unsortableClass
);
413 function isValueInArray( v
, a
) {
416 for ( i
= 0; i
< len
; i
++ ) {
417 if ( a
[ i
][ 0 ] === v
) {
425 * Sets the sort count of the columns that are not affected by the sorting to have them sorted
426 * in default (ascending) order when their header cell is clicked the next time.
428 * @param {jQuery} $headers
429 * @param {Number[][]} sortList
430 * @param {Number[][]} headerToColumns
432 function setHeadersOrder( $headers
, sortList
, headerToColumns
) {
433 // Loop through all headers to retrieve the indices of the columns the header spans across:
434 $.each( headerToColumns
, function ( headerIndex
, columns
) {
436 $.each( columns
, function ( i
, columnIndex
) {
437 var header
= $headers
[ headerIndex
],
438 $header
= $( header
);
440 if ( !isValueInArray( columnIndex
, sortList
) ) {
441 // Column shall not be sorted: Reset header count and order.
447 // Column shall be sorted: Apply designated count and order.
448 $.each( sortList
, function ( j
, sortColumn
) {
449 if ( sortColumn
[ 0 ] === i
) {
451 order
: sortColumn
[ 1 ],
452 count
: sortColumn
[ 1 ] + 1
463 function setHeadersCss( table
, $headers
, list
, css
, msg
, columnToHeader
) {
464 // Remove all header information and reset titles to default message
465 $headers
.removeClass( css
[ 0 ] ).removeClass( css
[ 1 ] ).attr( 'title', msg
[ 1 ] );
467 for ( var i
= 0; i
< list
.length
; i
++ ) {
468 $headers
.eq( columnToHeader
[ list
[ i
][ 0 ] ] )
469 .addClass( css
[ list
[ i
][ 1 ] ] )
470 .attr( 'title', msg
[ list
[ i
][ 1 ] ] );
474 function sortText( a
, b
) {
475 return ( ( a
< b
) ? -1 : ( ( a
> b
) ? 1 : 0 ) );
478 function sortTextDesc( a
, b
) {
479 return ( ( b
< a
) ? -1 : ( ( b
> a
) ? 1 : 0 ) );
482 function multisort( table
, sortList
, cache
) {
485 len
= sortList
.length
;
486 for ( i
= 0; i
< len
; i
++ ) {
487 sortFn
[ i
] = ( sortList
[ i
][ 1 ] ) ? sortTextDesc
: sortText
;
489 cache
.normalized
.sort( function ( array1
, array2
) {
491 for ( i
= 0; i
< len
; i
++ ) {
492 col
= sortList
[ i
][ 0 ];
493 ret
= sortFn
[ i
].call( this, array1
[ col
], array2
[ col
] );
498 // Fall back to index number column to ensure stable sort
499 return sortText
.call( this, array1
[ array1
.length
- 1 ], array2
[ array2
.length
- 1 ] );
504 function buildTransformTable() {
505 var ascii
, localised
, i
, digitClass
,
506 digits
= '0123456789,.'.split( '' ),
507 separatorTransformTable
= mw
.config
.get( 'wgSeparatorTransformTable' ),
508 digitTransformTable
= mw
.config
.get( 'wgDigitTransformTable' );
510 if ( separatorTransformTable
=== null || ( separatorTransformTable
[ 0 ] === '' && digitTransformTable
[ 2 ] === '' ) ) {
511 ts
.transformTable
= false;
513 ts
.transformTable
= {};
515 // Unpack the transform table
516 ascii
= separatorTransformTable
[ 0 ].split( '\t' ).concat( digitTransformTable
[ 0 ].split( '\t' ) );
517 localised
= separatorTransformTable
[ 1 ].split( '\t' ).concat( digitTransformTable
[ 1 ].split( '\t' ) );
519 // Construct regex for number identification
520 for ( i
= 0; i
< ascii
.length
; i
++ ) {
521 ts
.transformTable
[ localised
[ i
] ] = ascii
[ i
];
522 digits
.push( mw
.RegExp
.escape( localised
[ i
] ) );
525 digitClass
= '[' + digits
.join( '', digits
) + ']';
527 // We allow a trailing percent sign, which we just strip. This works fine
528 // if percents and regular numbers aren't being mixed.
529 ts
.numberRegex
= new RegExp( '^(' + '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
530 '|' + '[-+\u2212]?' + digitClass
+ '+[\\s\\xa0]*%?' + // Generic localised
534 function buildDateTable() {
540 for ( i
= 0; i
< 12; i
++ ) {
541 name
= mw
.language
.months
.names
[ i
].toLowerCase();
542 ts
.monthNames
[ name
] = i
+ 1;
543 regex
.push( mw
.RegExp
.escape( name
) );
544 name
= mw
.language
.months
.genitive
[ i
].toLowerCase();
545 ts
.monthNames
[ name
] = i
+ 1;
546 regex
.push( mw
.RegExp
.escape( name
) );
547 name
= mw
.language
.months
.abbrev
[ i
].toLowerCase().replace( '.', '' );
548 ts
.monthNames
[ name
] = i
+ 1;
549 regex
.push( mw
.RegExp
.escape( name
) );
552 // Build piped string
553 regex
= regex
.join( '|' );
556 // Any date formated with . , ' - or /
557 ts
.dateRegex
[ 0 ] = new RegExp( /^\s*(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{2,4})\s*?/i );
559 // Written Month name, dmy
560 ts
.dateRegex
[ 1 ] = new RegExp( '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
562 // Written Month name, mdy
563 ts
.dateRegex
[ 2 ] = new RegExp( '^\\s*(' + regex
+ ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
568 * Replace all rowspanned cells in the body with clones in each row, so sorting
569 * need not worry about them.
571 * @param {jQuery} $table jQuery object for a <table>
573 function explodeRowspans( $table
) {
574 var spanningRealCellIndex
, rowSpan
, colSpan
,
575 cell
, cellData
, i
, $tds
, $clone
, $nextRows
,
576 rowspanCells
= $table
.find( '> tbody > tr > [rowspan]' ).get();
579 if ( !rowspanCells
.length
) {
583 // First, we need to make a property like cellIndex but taking into
584 // account colspans. We also cache the rowIndex to avoid having to take
585 // cell.parentNode.rowIndex in the sorting function below.
586 $table
.find( '> tbody > tr' ).each( function () {
589 l
= this.cells
.length
;
590 for ( i
= 0; i
< l
; i
++ ) {
591 $( this.cells
[ i
] ).data( 'tablesorter', {
593 realRowIndex
: this.rowIndex
595 col
+= this.cells
[ i
].colSpan
;
599 // Split multi row cells into multiple cells with the same content.
600 // Sort by column then row index to avoid problems with odd table structures.
601 // Re-sort whenever a rowspanned cell's realCellIndex is changed, because it
602 // might change the sort order.
603 function resortCells() {
607 rowspanCells
= rowspanCells
.sort( function ( a
, b
) {
608 cellAData
= $.data( a
, 'tablesorter' );
609 cellBData
= $.data( b
, 'tablesorter' );
610 ret
= cellAData
.realCellIndex
- cellBData
.realCellIndex
;
612 ret
= cellAData
.realRowIndex
- cellBData
.realRowIndex
;
616 $.each( rowspanCells
, function () {
617 $.data( this, 'tablesorter' ).needResort
= false;
622 function filterfunc() {
623 return $.data( this, 'tablesorter' ).realCellIndex
>= spanningRealCellIndex
;
626 function fixTdCellIndex() {
627 $.data( this, 'tablesorter' ).realCellIndex
+= colSpan
;
628 if ( this.rowSpan
> 1 ) {
629 $.data( this, 'tablesorter' ).needResort
= true;
633 while ( rowspanCells
.length
) {
634 if ( $.data( rowspanCells
[ 0 ], 'tablesorter' ).needResort
) {
638 cell
= rowspanCells
.shift();
639 cellData
= $.data( cell
, 'tablesorter' );
640 rowSpan
= cell
.rowSpan
;
641 colSpan
= cell
.colSpan
;
642 spanningRealCellIndex
= cellData
.realCellIndex
;
644 $nextRows
= $( cell
).parent().nextAll();
645 for ( i
= 0; i
< rowSpan
- 1; i
++ ) {
646 $tds
= $( $nextRows
[ i
].cells
).filter( filterfunc
);
647 $clone
= $( cell
).clone();
648 $clone
.data( 'tablesorter', {
649 realCellIndex
: spanningRealCellIndex
,
650 realRowIndex
: cellData
.realRowIndex
+ i
,
654 $tds
.each( fixTdCellIndex
);
655 $tds
.first().before( $clone
);
657 $nextRows
.eq( i
).append( $clone
);
664 * Build index to handle colspanned cells in the body.
665 * Set the cell index for each column in an array,
666 * so that colspaned cells set multiple in this array.
667 * columnToCell[collumnIndex] point at the real cell in this row.
669 * @param {jQuery} $table object for a <table>
671 function manageColspans( $table
) {
673 $rows
= $table
.find( '> tbody > tr' ),
674 totalRows
= $rows
.length
|| 0,
675 config
= $table
.data( 'tablesorter' ).config
,
676 columns
= config
.columns
,
677 columnToCell
, cellsInRow
, index
;
679 for ( i
= 0; i
< totalRows
; i
++ ) {
681 $row
= $rows
.eq( i
);
682 // if this is a child row, continue to the next row (as buildCache())
683 if ( $row
.hasClass( config
.cssChildRow
) ) {
684 // go to the next for loop
689 cellsInRow
= ( $row
[ 0 ].cells
.length
) || 0; // all cells in this row
690 index
= 0; // real cell index in this row
691 for ( j
= 0; j
< columns
; index
++ ) {
692 if ( index
=== cellsInRow
) {
693 // Row with cells less than columns: add empty cell
694 $row
.append( '<td>' );
697 for ( k
= 0; k
< $row
[ 0 ].cells
[ index
].colSpan
; k
++ ) {
698 columnToCell
[ j
++ ] = index
;
702 $row
.data( 'columnToCell', columnToCell
);
706 function buildCollationTable() {
707 ts
.collationTable
= mw
.config
.get( 'tableSorterCollation' );
708 ts
.collationRegex
= null;
709 if ( ts
.collationTable
) {
713 // Build array of key names
714 for ( key
in ts
.collationTable
) {
715 // Check hasOwn to be safe
716 if ( ts
.collationTable
.hasOwnProperty( key
) ) {
721 ts
.collationRegex
= new RegExp( '[' + keys
.join( '' ) + ']', 'ig' );
726 function cacheRegexs() {
732 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/ )
735 new RegExp( /(^[£$€¥]|[£$€¥]$)/ ),
736 new RegExp( /[£$€¥]/g )
739 new RegExp( /^(https?|ftp|file):\/\/$/ ),
740 new RegExp( /(https?|ftp|file):\/\// )
743 new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/ )
746 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)))$/ )
749 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/ )
755 * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
756 * structure [ [ Integer , Integer ], ... ]
758 * @param sortObjects {Array} List of sort objects.
759 * @return {Array} List of internal sort definitions.
762 function convertSortList( sortObjects
) {
764 $.each( sortObjects
, function ( i
, sortObject
) {
765 $.each( sortObject
, function ( columnIndex
, order
) {
766 var orderIndex
= ( order
=== 'desc' ) ? 1 : 0;
767 sortList
.push( [ parseInt( columnIndex
, 10 ), orderIndex
] );
777 cssHeader
: 'headerSort',
778 cssAsc
: 'headerSortUp',
779 cssDesc
: 'headerSortDown',
780 cssChildRow
: 'expand-child',
781 sortMultiSortKey
: 'shiftKey',
782 unsortableClass
: 'unsortable',
784 cancelSelection
: true,
796 * @param {jQuery} $tables
797 * @param {Object} [settings]
799 construct: function ( $tables
, settings
) {
800 return $tables
.each( function ( i
, table
) {
801 // Declare and cache.
802 var $headers
, cache
, config
, sortCSS
, sortMsg
,
807 if ( !table
.tBodies
) {
810 if ( !table
.tHead
) {
811 // No thead found. Look for rows with <th>s and
812 // move them into a <thead> tag or a <tfoot> tag
813 emulateTHeadAndFoot( $table
);
815 // Still no thead? Then quit
816 if ( !table
.tHead
) {
820 $table
.addClass( 'jquery-tablesorter' );
823 config
= $.extend( {}, $.tablesorter
.defaultOptions
, settings
);
825 // Save the settings where they read
826 $.data( table
, 'tablesorter', { config
: config
} );
828 // Get the CSS class names, could be done elsewhere
829 sortCSS
= [ config
.cssDesc
, config
.cssAsc
];
830 sortMsg
= [ mw
.msg( 'sort-descending' ), mw
.msg( 'sort-ascending' ) ];
833 $headers
= buildHeaders( table
, sortMsg
);
835 // Grab and process locale settings.
836 buildTransformTable();
839 // Precaching regexps can bring 10 fold
840 // performance improvements in some browsers.
843 function setupForFirstSort() {
846 // Defer buildCollationTable to first sort. As user and site scripts
847 // may customize tableSorterCollation but load after $.ready(), other
848 // scripts may call .tablesorter() before they have done the
849 // tableSorterCollation customizations.
850 buildCollationTable();
852 // Legacy fix of .sortbottoms
853 // Wrap them inside a tfoot (because that's what they actually want to be)
854 // and put the <tfoot> at the end of the <table>
856 $sortbottoms
= $table
.find( '> tbody > tr.sortbottom' );
857 if ( $sortbottoms
.length
) {
858 $tfoot
= $table
.children( 'tfoot' );
859 if ( $tfoot
.length
) {
860 $tfoot
.eq( 0 ).prepend( $sortbottoms
);
862 $table
.append( $( '<tfoot>' ).append( $sortbottoms
) );
866 explodeRowspans( $table
);
867 manageColspans( $table
);
869 // Try to auto detect column type, and store in tables config
870 config
.parsers
= buildParserCache( table
, $headers
);
873 // Apply event handling to headers
874 // this is too big, perhaps break it out?
875 $headers
.on( 'keypress click', function ( e
) {
876 var cell
, $cell
, columns
, newSortList
, i
,
880 if ( e
.type
=== 'click' && e
.target
.nodeName
.toLowerCase() === 'a' ) {
881 // The user clicked on a link inside a table header.
882 // Do nothing and let the default link click action continue.
886 if ( e
.type
=== 'keypress' && e
.which
!== 13 ) {
887 // Only handle keypresses on the "Enter" key.
895 // Build the cache for the tbody cells
896 // to share between calculations for this sort action.
897 // Re-calculated each time a sort action is performed due to possiblity
898 // that sort values change. Shouldn't be too expensive, but if it becomes
899 // too slow an event based system should be implemented somehow where
900 // cells get event .change() and bubbles up to the <table> here
901 cache
= buildCache( table
);
903 totalRows
= ( $table
[ 0 ].tBodies
[ 0 ] && $table
[ 0 ].tBodies
[ 0 ].rows
.length
) || 0;
904 if ( totalRows
> 0 ) {
908 // Get current column sort order
910 order
: $cell
.data( 'count' ) % 2,
911 count
: $cell
.data( 'count' ) + 1
915 // Get current column index
916 columns
= config
.headerToColumns
[ $cell
.data( 'headerIndex' ) ];
917 newSortList
= $.map( columns
, function ( c
) {
918 // jQuery "helpfully" flattens the arrays...
919 return [ [ c
, $cell
.data( 'order' ) ] ];
921 // Index of first column belonging to this header
924 if ( !e
[ config
.sortMultiSortKey
] ) {
925 // User only wants to sort on one column set
926 // Flush the sort list and add new columns
927 config
.sortList
= newSortList
;
929 // Multi column sorting
930 // It is not possible for one column to belong to multiple headers,
931 // so this is okay - we don't need to check for every value in the columns array
932 if ( isValueInArray( i
, config
.sortList
) ) {
933 // The user has clicked on an already sorted column.
934 // Reverse the sorting direction for all tables.
935 for ( j
= 0; j
< config
.sortList
.length
; j
++ ) {
936 s
= config
.sortList
[ j
];
937 o
= config
.headerList
[ config
.columnToHeader
[ s
[ 0 ] ] ];
938 if ( isValueInArray( s
[ 0 ], newSortList
) ) {
939 $( o
).data( 'count', s
[ 1 ] + 1 );
940 s
[ 1 ] = $( o
).data( 'count' ) % 2;
944 // Add columns to sort list array
945 config
.sortList
= config
.sortList
.concat( newSortList
);
949 // Reset order/counts of cells not affected by sorting
950 setHeadersOrder( $headers
, config
.sortList
, config
.headerToColumns
);
952 // Set CSS for headers
953 setHeadersCss( $table
[ 0 ], $headers
, config
.sortList
, sortCSS
, sortMsg
, config
.columnToHeader
);
955 $table
[ 0 ], multisort( $table
[ 0 ], config
.sortList
, cache
)
958 // Stop normal event by returning false
963 } ).mousedown( function () {
964 if ( config
.cancelSelection
) {
965 this.onselectstart = function () {
973 * Sorts the table. If no sorting is specified by passing a list of sort
974 * objects, the table is sorted according to the initial sorting order.
975 * Passing an empty array will reset sorting (basically just reset the headers
976 * making the table appear unsorted).
978 * @param {Array} [sortList] List of sort objects.
980 $table
.data( 'tablesorter' ).sort = function ( sortList
) {
986 if ( sortList
=== undefined ) {
987 sortList
= config
.sortList
;
988 } else if ( sortList
.length
> 0 ) {
989 sortList
= convertSortList( sortList
);
992 // Set each column's sort count to be able to determine the correct sort
993 // order when clicking on a header cell the next time
994 setHeadersOrder( $headers
, sortList
, config
.headerToColumns
);
996 // re-build the cache for the tbody cells
997 cache
= buildCache( table
);
999 // set css for headers
1000 setHeadersCss( table
, $headers
, sortList
, sortCSS
, sortMsg
, config
.columnToHeader
);
1002 // sort the table and append it to the dom
1003 appendToTable( table
, multisort( table
, sortList
, cache
) );
1007 if ( config
.sortList
.length
> 0 ) {
1008 config
.sortList
= convertSortList( config
.sortList
);
1009 $table
.data( 'tablesorter' ).sort();
1015 addParser: function ( parser
) {
1017 len
= parsers
.length
,
1019 for ( i
= 0; i
< len
; i
++ ) {
1020 if ( parsers
[ i
].id
.toLowerCase() === parser
.id
.toLowerCase() ) {
1025 parsers
.push( parser
);
1029 formatDigit: function ( s
) {
1031 if ( ts
.transformTable
!== false ) {
1033 for ( p
= 0; p
< s
.length
; p
++ ) {
1035 if ( c
in ts
.transformTable
) {
1036 out
+= ts
.transformTable
[ c
];
1043 i
= parseFloat( s
.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
1044 return isNaN( i
) ? 0 : i
;
1047 formatFloat: function ( s
) {
1048 var i
= parseFloat( s
);
1049 return isNaN( i
) ? 0 : i
;
1052 formatInt: function ( s
) {
1053 var i
= parseInt( s
, 10 );
1054 return isNaN( i
) ? 0 : i
;
1057 clearTableBody: function ( table
) {
1058 $( table
.tBodies
[ 0 ] ).empty();
1061 getParser: function ( id
) {
1062 buildTransformTable();
1065 buildCollationTable();
1067 return getParserById( id
);
1070 getParsers: function () { // for table diagnosis
1078 // Register as jQuery prototype method
1079 $.fn
.tablesorter = function ( settings
) {
1080 return ts
.construct( this, settings
);
1083 // Add default parsers
1089 format: function ( s
) {
1090 s
= $.trim( s
.toLowerCase() );
1091 if ( ts
.collationRegex
) {
1092 var tsc
= ts
.collationTable
;
1093 s
= s
.replace( ts
.collationRegex
, function ( match
) {
1094 var r
= tsc
[ match
] ? tsc
[ match
] : tsc
[ match
.toUpperCase() ];
1095 return r
.toLowerCase();
1105 is: function ( s
) {
1106 return ts
.rgx
.IPAddress
[ 0 ].test( s
);
1108 format: function ( s
) {
1113 for ( i
= 0; i
< len
; i
++ ) {
1115 if ( item
.length
=== 1 ) {
1117 } else if ( item
.length
=== 2 ) {
1123 return $.tablesorter
.formatFloat( r
);
1130 is: function ( s
) {
1131 return ts
.rgx
.currency
[ 0 ].test( s
);
1133 format: function ( s
) {
1134 return $.tablesorter
.formatDigit( s
.replace( ts
.rgx
.currency
[ 1 ], '' ) );
1141 is: function ( s
) {
1142 return ts
.rgx
.url
[ 0 ].test( s
);
1144 format: function ( s
) {
1145 return $.trim( s
.replace( ts
.rgx
.url
[ 1 ], '' ) );
1152 is: function ( s
) {
1153 return ts
.rgx
.isoDate
[ 0 ].test( s
);
1155 format: function ( s
) {
1156 return $.tablesorter
.formatFloat( ( s
!== '' ) ? new Date( s
.replace(
1157 new RegExp( /-/g ), '/' ) ).getTime() : '0' );
1164 is: function ( s ) {
1165 return ts.rgx.usLongDate[ 0 ].test( s );
1167 format: function ( s ) {
1168 return $.tablesorter.formatFloat( new Date( s ).getTime() );
1175 is: function ( s ) {
1176 return ( ts.dateRegex[ 0 ].test( s ) || ts.dateRegex[ 1 ].test( s ) || ts.dateRegex[ 2 ].test( s ) );
1178 format: function ( s ) {
1180 s = $.trim( s.toLowerCase() );
1182 if ( ( match = s.match( ts.dateRegex[ 0 ] ) ) !== null ) {
1183 if ( mw.config.get( 'wgDefaultDateFormat
' ) === 'mdy
' || mw.config.get( 'wgPageContentLanguage
' ) === 'en
' ) {
1184 s = [ match[ 3 ], match[ 1 ], match[ 2 ] ];
1185 } else if ( mw.config.get( 'wgDefaultDateFormat
' ) === 'dmy
' ) {
1186 s = [ match[ 3 ], match[ 2 ], match[ 1 ] ];
1188 // If we get here, we don't know which order the dd
-dd
-dddd
1189 // date is in. So return something not entirely invalid.
1192 } else if ( ( match
= s
.match( ts
.dateRegex
[ 1 ] ) ) !== null ) {
1193 s
= [ match
[ 3 ], String( ts
.monthNames
[ match
[ 2 ] ] ), match
[ 1 ] ];
1194 } else if ( ( match
= s
.match( ts
.dateRegex
[ 2 ] ) ) !== null ) {
1195 s
= [ match
[ 3 ], String( ts
.monthNames
[ match
[ 1 ] ] ), match
[ 2 ] ];
1197 // Should never get here
1201 // Pad Month and Day
1202 if ( s
[ 1 ].length
=== 1 ) {
1203 s
[ 1 ] = '0' + s
[ 1 ];
1205 if ( s
[ 2 ].length
=== 1 ) {
1206 s
[ 2 ] = '0' + s
[ 2 ];
1209 if ( ( y
= parseInt( s
[ 0 ], 10 ) ) < 100 ) {
1210 // Guestimate years without centuries
1217 while ( s
[ 0 ].length
< 4 ) {
1218 s
[ 0 ] = '0' + s
[ 0 ];
1220 return parseInt( s
.join( '' ), 10 );
1227 is: function ( s
) {
1228 return ts
.rgx
.time
[ 0 ].test( s
);
1230 format: function ( s
) {
1231 return $.tablesorter
.formatFloat( new Date( '2000/01/01 ' + s
).getTime() );
1238 is: function ( s
) {
1239 return $.tablesorter
.numberRegex
.test( $.trim( s
) );
1241 format: function ( s
) {
1242 return $.tablesorter
.formatDigit( s
);
1247 }( jQuery
, mediaWiki
) );