Merge "jquery.tablesorter: buildCollationTable() on first sort, not on load"
[lhc/web/wiklou.git] / resources / jquery / jquery.tablesorter.js
1 /**
2 * TableSorter for MediaWiki
3 *
4 * Written 2011 Leo Koppelkamm
5 * Based on tablesorter.com plugin, written (c) 2007 Christian Bach.
6 *
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
10 *
11 * Depends on mw.config (wgDigitTransformTable, wgMonthNames, wgMonthNamesShort,
12 * wgDefaultDateFormat, wgContentLanguage)
13 * Uses 'tableSorterCollation' in mw.config (if available)
14 */
15 /**
16 *
17 * @description Create a sortable table with multi-column sorting capabilitys
18 *
19 * @example $( 'table' ).tablesorter();
20 * @desc Create a simple tablesorter interface.
21 *
22 * @example $( 'table' ).tablesorter( { sortList: [ { 0: 'desc' }, { 1: 'asc' } ] } );
23 * @desc Create a tablesorter interface initially sorting on the first and second column.
24 *
25 * @option String cssHeader ( optional ) A string of the class name to be appended
26 * to sortable tr elements in the thead of the table. Default value:
27 * "header"
28 *
29 * @option String cssAsc ( optional ) A string of the class name to be appended to
30 * sortable tr elements in the thead on a ascending sort. Default value:
31 * "headerSortUp"
32 *
33 * @option String cssDesc ( optional ) A string of the class name to be appended
34 * to sortable tr elements in the thead on a descending sort. Default
35 * value: "headerSortDown"
36 *
37 * @option String sortInitialOrder ( optional ) A string of the inital sorting
38 * order can be asc or desc. Default value: "asc"
39 *
40 * @option String sortMultisortKey ( optional ) A string of the multi-column sort
41 * key. Default value: "shiftKey"
42 *
43 * @option Boolean sortLocaleCompare ( optional ) Boolean flag indicating whatever
44 * to use String.localeCampare method or not. Set to false.
45 *
46 * @option Boolean cancelSelection ( optional ) Boolean flag indicating if
47 * tablesorter should cancel selection of the table headers text.
48 * Default value: true
49 *
50 * @option Array sortList ( optional ) An array containing objects specifying sorting.
51 * By passing more than one object, multi-sorting will be applied. Object structure:
52 * { <Integer column index>: <String 'asc' or 'desc'> }
53 * Default value: []
54 *
55 * @option Boolean debug ( optional ) Boolean flag indicating if tablesorter
56 * should display debuging information usefull for development.
57 *
58 * @event sortEnd.tablesorter: Triggered as soon as any sorting has been applied.
59 *
60 * @type jQuery
61 *
62 * @name tablesorter
63 *
64 * @cat Plugins/Tablesorter
65 *
66 * @author Christian Bach/christian.bach@polyester.se
67 */
68
69 ( function ( $, mw ) {
70 /*jshint onevar:false */
71
72 /* Local scope */
73
74 var ts,
75 parsers = [];
76
77 /* Parser utility functions */
78
79 function getParserById( name ) {
80 var len = parsers.length;
81 for ( var i = 0; i < len; i++ ) {
82 if ( parsers[i].id.toLowerCase() === name.toLowerCase() ) {
83 return parsers[i];
84 }
85 }
86 return false;
87 }
88
89 function getElementSortKey( node ) {
90 var $node = $( node ),
91 // Use data-sort-value attribute.
92 // Use data() instead of attr() so that live value changes
93 // are processed as well (bug 38152).
94 data = $node.data( 'sortValue' );
95
96 if ( data !== null && data !== undefined ) {
97 // Cast any numbers or other stuff to a string, methods
98 // like charAt, toLowerCase and split are expected.
99 return String( data );
100 } else {
101 if ( !node ) {
102 return $node.text();
103 } else if ( node.tagName.toLowerCase() === 'img' ) {
104 return $node.attr( 'alt' ) || ''; // handle undefined alt
105 } else {
106 return $.map( $.makeArray( node.childNodes ), function( elem ) {
107 // 1 is for document.ELEMENT_NODE (the constant is undefined on old browsers)
108 if ( elem.nodeType === 1 ) {
109 return getElementSortKey( elem );
110 } else {
111 return $.text( elem );
112 }
113 } ).join( '' );
114 }
115 }
116 }
117
118 function detectParserForColumn( table, rows, cellIndex ) {
119 var l = parsers.length,
120 nodeValue,
121 // Start with 1 because 0 is the fallback parser
122 i = 1,
123 rowIndex = 0,
124 concurrent = 0,
125 needed = ( rows.length > 4 ) ? 5 : rows.length;
126
127 while ( i < l ) {
128 if ( rows[rowIndex] && rows[rowIndex].cells[cellIndex] ) {
129 nodeValue = $.trim( getElementSortKey( rows[rowIndex].cells[cellIndex] ) );
130 } else {
131 nodeValue = '';
132 }
133
134 if ( nodeValue !== '') {
135 if ( parsers[i].is( nodeValue, table ) ) {
136 concurrent++;
137 rowIndex++;
138 if ( concurrent >= needed ) {
139 // Confirmed the parser for multiple cells, let's return it
140 return parsers[i];
141 }
142 } else {
143 // Check next parser, reset rows
144 i++;
145 rowIndex = 0;
146 concurrent = 0;
147 }
148 } else {
149 // Empty cell
150 rowIndex++;
151 if ( rowIndex > rows.length ) {
152 rowIndex = 0;
153 i++;
154 }
155 }
156 }
157
158 // 0 is always the generic parser (text)
159 return parsers[0];
160 }
161
162 function buildParserCache( table, $headers ) {
163 var rows = table.tBodies[0].rows,
164 sortType,
165 parsers = [];
166
167 if ( rows[0] ) {
168
169 var cells = rows[0].cells,
170 len = cells.length,
171 i, parser;
172
173 for ( i = 0; i < len; i++ ) {
174 parser = false;
175 sortType = $headers.eq( i ).data( 'sortType' );
176 if ( sortType !== undefined ) {
177 parser = getParserById( sortType );
178 }
179
180 if ( parser === false ) {
181 parser = detectParserForColumn( table, rows, i );
182 }
183
184 parsers.push( parser );
185 }
186 }
187 return parsers;
188 }
189
190 /* Other utility functions */
191
192 function buildCache( table ) {
193 var totalRows = ( table.tBodies[0] && table.tBodies[0].rows.length ) || 0,
194 totalCells = ( table.tBodies[0].rows[0] && table.tBodies[0].rows[0].cells.length ) || 0,
195 parsers = table.config.parsers,
196 cache = {
197 row: [],
198 normalized: []
199 };
200
201 for ( var i = 0; i < totalRows; ++i ) {
202
203 // Add the table data to main data array
204 var $row = $( table.tBodies[0].rows[i] ),
205 cols = [];
206
207 // if this is a child row, add it to the last row's children and
208 // continue to the next row
209 if ( $row.hasClass( table.config.cssChildRow ) ) {
210 cache.row[cache.row.length - 1] = cache.row[cache.row.length - 1].add( $row );
211 // go to the next for loop
212 continue;
213 }
214
215 cache.row.push( $row );
216
217 for ( var j = 0; j < totalCells; ++j ) {
218 cols.push( parsers[j].format( getElementSortKey( $row[0].cells[j] ), table, $row[0].cells[j] ) );
219 }
220
221 cols.push( cache.normalized.length ); // add position for rowCache
222 cache.normalized.push( cols );
223 cols = null;
224 }
225
226 return cache;
227 }
228
229 function appendToTable( table, cache ) {
230 var row = cache.row,
231 normalized = cache.normalized,
232 totalRows = normalized.length,
233 checkCell = ( normalized[0].length - 1 ),
234 fragment = document.createDocumentFragment();
235
236 for ( var i = 0; i < totalRows; i++ ) {
237 var pos = normalized[i][checkCell];
238
239 var l = row[pos].length;
240
241 for ( var j = 0; j < l; j++ ) {
242 fragment.appendChild( row[pos][j] );
243 }
244
245 }
246 table.tBodies[0].appendChild( fragment );
247
248 $( table ).trigger( 'sortEnd.tablesorter' );
249 }
250
251 /**
252 * Find all header rows in a thead-less table and put them in a <thead> tag.
253 * This only treats a row as a header row if it contains only <th>s (no <td>s)
254 * and if it is preceded entirely by header rows. The algorithm stops when
255 * it encounters the first non-header row.
256 *
257 * After this, it will look at all rows at the bottom for footer rows
258 * And place these in a tfoot using similar rules.
259 * @param $table jQuery object for a <table>
260 */
261 function emulateTHeadAndFoot( $table ) {
262 var $rows = $table.find( '> tbody > tr' );
263 if( !$table.get(0).tHead ) {
264 var $thead = $( '<thead>' );
265 $rows.each( function () {
266 if ( $(this).children( 'td' ).length > 0 ) {
267 // This row contains a <td>, so it's not a header row
268 // Stop here
269 return false;
270 }
271 $thead.append( this );
272 } );
273 $table.find(' > tbody:first').before( $thead );
274 }
275 if( !$table.get(0).tFoot ) {
276 var $tfoot = $( '<tfoot>' );
277 var len = $rows.length;
278 for ( var i = len-1; i >= 0; i-- ) {
279 if( $( $rows[i] ).children( 'td' ).length > 0 ){
280 break;
281 }
282 $tfoot.prepend( $( $rows[i] ));
283 }
284 $table.append( $tfoot );
285 }
286 }
287
288 function buildHeaders( table, msg ) {
289 var maxSeen = 0,
290 colspanOffset = 0,
291 longest,
292 columns,
293 i,
294 $tableHeaders = $( [] ),
295 $tableRows = $( 'thead:eq(0) > tr', table );
296 if ( $tableRows.length <= 1 ) {
297 $tableHeaders = $tableRows.children( 'th' );
298 } else {
299 // We need to find the cells of the row containing the most columns
300 var rowspan,
301 headersIndex = [];
302 $tableRows.each( function ( rowIndex ) {
303 $.each( this.cells, function( index2, cell ) {
304 rowspan = Number( cell.rowSpan );
305 for ( i = 0; i < rowspan; i++ ) {
306 if ( headersIndex[rowIndex+i] === undefined ) {
307 headersIndex[rowIndex+i] = $( [] );
308 }
309 headersIndex[rowIndex+i].push( cell );
310 }
311 } );
312 } );
313 $.each( headersIndex, function ( index, cellArray ) {
314 if ( cellArray.length >= maxSeen ) {
315 maxSeen = cellArray.length;
316 longest = index;
317 }
318 } );
319 $tableHeaders = headersIndex[longest];
320 }
321
322 // as each header can span over multiple columns (using colspan=N),
323 // we have to bidirectionally map headers to their columns and columns to their headers
324 table.headerToColumns = [];
325 table.columnToHeader = [];
326
327 $tableHeaders.each( function ( headerIndex ) {
328 columns = [];
329 for ( i = 0; i < this.colSpan; i++ ) {
330 table.columnToHeader[ colspanOffset + i ] = headerIndex;
331 columns.push( colspanOffset + i );
332 }
333
334 table.headerToColumns[ headerIndex ] = columns;
335 colspanOffset += this.colSpan;
336
337 this.headerIndex = headerIndex;
338 this.order = 0;
339 this.count = 0;
340
341 if ( $( this ).hasClass( table.config.unsortableClass ) ) {
342 this.sortDisabled = true;
343 }
344
345 if ( !this.sortDisabled ) {
346 $( this )
347 .addClass( table.config.cssHeader )
348 .prop( 'tabIndex', 0 )
349 .attr( {
350 role: 'columnheader button',
351 title: msg[1]
352 } );
353 }
354
355 // add cell to headerList
356 table.config.headerList[headerIndex] = this;
357 } );
358
359 return $tableHeaders;
360
361 }
362
363 /**
364 * Sets the sort count of the columns that are not affected by the sorting to have them sorted
365 * in default (ascending) order when their header cell is clicked the next time.
366 *
367 * @param {jQuery} $headers
368 * @param {Number[][]} sortList
369 * @param {Number[][]} headerToColumns
370 */
371 function setHeadersOrder( $headers, sortList, headerToColumns ) {
372 // Loop through all headers to retrieve the indices of the columns the header spans across:
373 $.each( headerToColumns, function( headerIndex, columns ) {
374
375 $.each( columns, function( i, columnIndex ) {
376 var header = $headers[headerIndex];
377
378 if ( !isValueInArray( columnIndex, sortList ) ) {
379 // Column shall not be sorted: Reset header count and order.
380 header.order = 0;
381 header.count = 0;
382 } else {
383 // Column shall be sorted: Apply designated count and order.
384 $.each( sortList, function( j, sortColumn ) {
385 if ( sortColumn[0] === i ) {
386 header.order = sortColumn[1];
387 header.count = sortColumn[1] + 1;
388 return false;
389 }
390 } );
391 }
392 } );
393
394 } );
395 }
396
397 function isValueInArray( v, a ) {
398 var l = a.length;
399 for ( var i = 0; i < l; i++ ) {
400 if ( a[i][0] === v ) {
401 return true;
402 }
403 }
404 return false;
405 }
406
407 function setHeadersCss( table, $headers, list, css, msg, columnToHeader ) {
408 // Remove all header information and reset titles to default message
409 $headers.removeClass( css[0] ).removeClass( css[1] ).attr( 'title', msg[1] );
410
411 for ( var i = 0; i < list.length; i++ ) {
412 $headers.eq( columnToHeader[ list[i][0] ] )
413 .addClass( css[ list[i][1] ] )
414 .attr( 'title', msg[ list[i][1] ] );
415 }
416 }
417
418 function sortText( a, b ) {
419 return ( (a < b) ? -1 : ((a > b) ? 1 : 0) );
420 }
421
422 function sortTextDesc( a, b ) {
423 return ( (b < a) ? -1 : ((b > a) ? 1 : 0) );
424 }
425
426 function multisort( table, sortList, cache ) {
427 var sortFn = [];
428 var len = sortList.length;
429 for ( var i = 0; i < len; i++ ) {
430 sortFn[i] = ( sortList[i][1] ) ? sortTextDesc : sortText;
431 }
432 cache.normalized.sort( function ( array1, array2 ) {
433 var col, ret;
434 for ( var i = 0; i < len; i++ ) {
435 col = sortList[i][0];
436 ret = sortFn[i].call( this, array1[col], array2[col] );
437 if ( ret !== 0 ) {
438 return ret;
439 }
440 }
441 // Fall back to index number column to ensure stable sort
442 return sortText.call( this, array1[array1.length - 1], array2[array2.length - 1] );
443 } );
444 return cache;
445 }
446
447 function buildTransformTable() {
448 var digits = '0123456789,.'.split( '' );
449 var separatorTransformTable = mw.config.get( 'wgSeparatorTransformTable' );
450 var digitTransformTable = mw.config.get( 'wgDigitTransformTable' );
451 if ( separatorTransformTable === null || ( separatorTransformTable[0] === '' && digitTransformTable[2] === '' ) ) {
452 ts.transformTable = false;
453 } else {
454 ts.transformTable = {};
455
456 // Unpack the transform table
457 var ascii = separatorTransformTable[0].split( '\t' ).concat( digitTransformTable[0].split( '\t' ) );
458 var localised = separatorTransformTable[1].split( '\t' ).concat( digitTransformTable[1].split( '\t' ) );
459
460 // Construct regex for number identification
461 for ( var i = 0; i < ascii.length; i++ ) {
462 ts.transformTable[localised[i]] = ascii[i];
463 digits.push( $.escapeRE( localised[i] ) );
464 }
465 }
466 var digitClass = '[' + digits.join( '', digits ) + ']';
467
468 // We allow a trailing percent sign, which we just strip. This works fine
469 // if percents and regular numbers aren't being mixed.
470 ts.numberRegex = new RegExp('^(' + '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
471 '|' + '[-+\u2212]?' + digitClass + '+[\\s\\xa0]*%?' + // Generic localised
472 ')$', 'i');
473 }
474
475 function buildDateTable() {
476 var regex = [];
477 ts.monthNames = {};
478
479 for ( var i = 1; i < 13; i++ ) {
480 var name = mw.config.get( 'wgMonthNames' )[i].toLowerCase();
481 ts.monthNames[name] = i;
482 regex.push( $.escapeRE( name ) );
483 name = mw.config.get( 'wgMonthNamesShort' )[i].toLowerCase().replace( '.', '' );
484 ts.monthNames[name] = i;
485 regex.push( $.escapeRE( name ) );
486 }
487
488 // Build piped string
489 regex = regex.join( '|' );
490
491 // Build RegEx
492 // Any date formated with . , ' - or /
493 ts.dateRegex[0] = new RegExp( /^\s*(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{2,4})\s*?/i);
494
495 // Written Month name, dmy
496 ts.dateRegex[1] = new RegExp( '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
497
498 // Written Month name, mdy
499 ts.dateRegex[2] = new RegExp( '^\\s*(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
500
501 }
502
503 /**
504 * Replace all rowspanned cells in the body with clones in each row, so sorting
505 * need not worry about them.
506 *
507 * @param $table jQuery object for a <table>
508 */
509 function explodeRowspans( $table ) {
510 var rowspanCells = $table.find( '> tbody > tr > [rowspan]' ).get();
511
512 // Short circuit
513 if ( !rowspanCells.length ) {
514 return;
515 }
516
517 // First, we need to make a property like cellIndex but taking into
518 // account colspans. We also cache the rowIndex to avoid having to take
519 // cell.parentNode.rowIndex in the sorting function below.
520 $table.find( '> tbody > tr' ).each( function () {
521 var col = 0;
522 var l = this.cells.length;
523 for ( var i = 0; i < l; i++ ) {
524 this.cells[i].realCellIndex = col;
525 this.cells[i].realRowIndex = this.rowIndex;
526 col += this.cells[i].colSpan;
527 }
528 } );
529
530 // Split multi row cells into multiple cells with the same content.
531 // Sort by column then row index to avoid problems with odd table structures.
532 // Re-sort whenever a rowspanned cell's realCellIndex is changed, because it
533 // might change the sort order.
534 function resortCells() {
535 rowspanCells = rowspanCells.sort( function ( a, b ) {
536 var ret = a.realCellIndex - b.realCellIndex;
537 if ( !ret ) {
538 ret = a.realRowIndex - b.realRowIndex;
539 }
540 return ret;
541 } );
542 $.each( rowspanCells, function () {
543 this.needResort = false;
544 } );
545 }
546 resortCells();
547
548 var spanningRealCellIndex, rowSpan, colSpan;
549 function filterfunc() {
550 return this.realCellIndex >= spanningRealCellIndex;
551 }
552
553 function fixTdCellIndex() {
554 this.realCellIndex += colSpan;
555 if ( this.rowSpan > 1 ) {
556 this.needResort = true;
557 }
558 }
559
560 while ( rowspanCells.length ) {
561 if ( rowspanCells[0].needResort ) {
562 resortCells();
563 }
564
565 var cell = rowspanCells.shift();
566 rowSpan = cell.rowSpan;
567 colSpan = cell.colSpan;
568 spanningRealCellIndex = cell.realCellIndex;
569 cell.rowSpan = 1;
570 var $nextRows = $( cell ).parent().nextAll();
571 for ( var i = 0; i < rowSpan - 1; i++ ) {
572 var $tds = $( $nextRows[i].cells ).filter( filterfunc );
573 var $clone = $( cell ).clone();
574 $clone[0].realCellIndex = spanningRealCellIndex;
575 if ( $tds.length ) {
576 $tds.each( fixTdCellIndex );
577 $tds.first().before( $clone );
578 } else {
579 $nextRows.eq( i ).append( $clone );
580 }
581 }
582 }
583 }
584
585 function buildCollationTable() {
586 ts.collationTable = mw.config.get( 'tableSorterCollation' );
587 ts.collationRegex = null;
588 if ( ts.collationTable ) {
589 var keys = [];
590
591 // Build array of key names
592 for ( var key in ts.collationTable ) {
593 if ( ts.collationTable.hasOwnProperty(key) ) { //to be safe
594 keys.push(key);
595 }
596 }
597 if (keys.length) {
598 ts.collationRegex = new RegExp( '[' + keys.join( '' ) + ']', 'ig' );
599 }
600 }
601 }
602
603 function cacheRegexs() {
604 if ( ts.rgx ) {
605 return;
606 }
607 ts.rgx = {
608 IPAddress: [
609 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/)
610 ],
611 currency: [
612 new RegExp( /(^[£$€¥]|[£$€¥]$)/),
613 new RegExp( /[£$€¥]/g)
614 ],
615 url: [
616 new RegExp( /^(https?|ftp|file):\/\/$/),
617 new RegExp( /(https?|ftp|file):\/\//)
618 ],
619 isoDate: [
620 new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/)
621 ],
622 usLongDate: [
623 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)))$/)
624 ],
625 time: [
626 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/)
627 ]
628 };
629 }
630
631 /**
632 * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
633 * structure [ [ Integer , Integer ], ... ]
634 *
635 * @param sortObjects {Array} List of sort objects.
636 * @return {Array} List of internal sort definitions.
637 */
638
639 function convertSortList( sortObjects ) {
640 var sortList = [];
641 $.each( sortObjects, function( i, sortObject ) {
642 $.each ( sortObject, function( columnIndex, order ) {
643 var orderIndex = ( order === 'desc' ) ? 1 : 0;
644 sortList.push( [parseInt( columnIndex, 10 ), orderIndex] );
645 } );
646 } );
647 return sortList;
648 }
649
650 /* Public scope */
651
652 $.tablesorter = {
653
654 defaultOptions: {
655 cssHeader: 'headerSort',
656 cssAsc: 'headerSortUp',
657 cssDesc: 'headerSortDown',
658 cssChildRow: 'expand-child',
659 sortInitialOrder: 'asc',
660 sortMultiSortKey: 'shiftKey',
661 sortLocaleCompare: false,
662 unsortableClass: 'unsortable',
663 parsers: {},
664 widgets: [],
665 headers: {},
666 cancelSelection: true,
667 sortList: [],
668 headerList: [],
669 selectorHeaders: 'thead tr:eq(0) th',
670 debug: false
671 },
672
673 dateRegex: [],
674 monthNames: {},
675
676 /**
677 * @param $tables {jQuery}
678 * @param settings {Object} (optional)
679 */
680 construct: function ( $tables, settings ) {
681 return $tables.each( function ( i, table ) {
682 // Declare and cache.
683 var $headers, cache, config,
684 $table = $( table ),
685 firstTime = true;
686
687 // Quit if no tbody
688 if ( !table.tBodies ) {
689 return;
690 }
691 if ( !table.tHead ) {
692 // No thead found. Look for rows with <th>s and
693 // move them into a <thead> tag or a <tfoot> tag
694 emulateTHeadAndFoot( $table );
695
696 // Still no thead? Then quit
697 if ( !table.tHead ) {
698 return;
699 }
700 }
701 $table.addClass( 'jquery-tablesorter' );
702
703 // FIXME config should probably not be stored in the plain table node
704 // New config object.
705 table.config = {};
706
707 // Merge and extend.
708 config = $.extend( table.config, $.tablesorter.defaultOptions, settings );
709
710 // Save the settings where they read
711 $.data( table, 'tablesorter', { config: config } );
712
713 // Get the CSS class names, could be done else where.
714 var sortCSS = [ config.cssDesc, config.cssAsc ];
715 var sortMsg = [ mw.msg( 'sort-descending' ), mw.msg( 'sort-ascending' ) ];
716
717 // Build headers
718 $headers = buildHeaders( table, sortMsg );
719
720 // Grab and process locale settings.
721 buildTransformTable();
722 buildDateTable();
723
724 // Precaching regexps can bring 10 fold
725 // performance improvements in some browsers.
726 cacheRegexs();
727
728 function setupForFirstSort() {
729 firstTime = false;
730
731 // Defer buildCollationTable to first sort. As user and site scripts
732 // may customize tableSorterCollation but load after $.ready(), other
733 // scripts may call .tablesorter() before they have done the
734 // tableSorterCollation customizations.
735 buildCollationTable();
736
737 // Legacy fix of .sortbottoms
738 // Wrap them inside inside a tfoot (because that's what they actually want to be) &
739 // and put the <tfoot> at the end of the <table>
740 var $sortbottoms = $table.find( '> tbody > tr.sortbottom' );
741 if ( $sortbottoms.length ) {
742 var $tfoot = $table.children( 'tfoot' );
743 if ( $tfoot.length ) {
744 $tfoot.eq(0).prepend( $sortbottoms );
745 } else {
746 $table.append( $( '<tfoot>' ).append( $sortbottoms ) );
747 }
748 }
749
750 explodeRowspans( $table );
751
752 // try to auto detect column type, and store in tables config
753 table.config.parsers = buildParserCache( table, $headers );
754 }
755
756 // Apply event handling to headers
757 // this is too big, perhaps break it out?
758 $headers.not( '.' + table.config.unsortableClass ).on( 'keypress click', function ( e ) {
759 if ( e.type === 'click' && e.target.nodeName.toLowerCase() === 'a' ) {
760 // The user clicked on a link inside a table header.
761 // Do nothing and let the default link click action continue.
762 return true;
763 }
764
765 if ( e.type === 'keypress' && e.which !== 13 ) {
766 // Only handle keypresses on the "Enter" key.
767 return true;
768 }
769
770 if ( firstTime ) {
771 setupForFirstSort();
772 }
773
774 // Build the cache for the tbody cells
775 // to share between calculations for this sort action.
776 // Re-calculated each time a sort action is performed due to possiblity
777 // that sort values change. Shouldn't be too expensive, but if it becomes
778 // too slow an event based system should be implemented somehow where
779 // cells get event .change() and bubbles up to the <table> here
780 cache = buildCache( table );
781
782 var totalRows = ( $table[0].tBodies[0] && $table[0].tBodies[0].rows.length ) || 0;
783 if ( !table.sortDisabled && totalRows > 0 ) {
784 // Get current column sort order
785 this.order = this.count % 2;
786 this.count++;
787
788 var cell = this;
789 // Get current column index
790 var columns = table.headerToColumns[ this.headerIndex ];
791 var newSortList = $.map( columns, function (c) {
792 // jQuery "helpfully" flattens the arrays...
793 return [[c, cell.order]];
794 });
795 // Index of first column belonging to this header
796 var i = columns[0];
797
798 if ( !e[config.sortMultiSortKey] ) {
799 // User only wants to sort on one column set
800 // Flush the sort list and add new columns
801 config.sortList = newSortList;
802 } else {
803 // Multi column sorting
804 // It is not possible for one column to belong to multiple headers,
805 // so this is okay - we don't need to check for every value in the columns array
806 if ( isValueInArray( i, config.sortList ) ) {
807 // The user has clicked on an already sorted column.
808 // Reverse the sorting direction for all tables.
809 for ( var j = 0; j < config.sortList.length; j++ ) {
810 var s = config.sortList[j],
811 o = config.headerList[s[0]];
812 if ( isValueInArray( s[0], newSortList ) ) {
813 o.count = s[1];
814 o.count++;
815 s[1] = o.count % 2;
816 }
817 }
818 } else {
819 // Add columns to sort list array
820 config.sortList = config.sortList.concat( newSortList );
821 }
822 }
823
824 // Reset order/counts of cells not affected by sorting
825 setHeadersOrder( $headers, config.sortList, table.headerToColumns );
826
827 // Set CSS for headers
828 setHeadersCss( $table[0], $headers, config.sortList, sortCSS, sortMsg, table.columnToHeader );
829 appendToTable(
830 $table[0], multisort( $table[0], config.sortList, cache )
831 );
832
833 // Stop normal event by returning false
834 return false;
835 }
836
837 // Cancel selection
838 } ).mousedown( function () {
839 if ( config.cancelSelection ) {
840 this.onselectstart = function () {
841 return false;
842 };
843 return false;
844 }
845 } );
846
847 /**
848 * Sorts the table. If no sorting is specified by passing a list of sort
849 * objects, the table is sorted according to the initial sorting order.
850 * Passing an empty array will reset sorting (basically just reset the headers
851 * making the table appear unsorted).
852 *
853 * @param sortList {Array} (optional) List of sort objects.
854 */
855 $table.data( 'tablesorter' ).sort = function( sortList ) {
856
857 if ( firstTime ) {
858 setupForFirstSort();
859 }
860
861 if ( sortList === undefined ) {
862 sortList = config.sortList;
863 } else if ( sortList.length > 0 ) {
864 sortList = convertSortList( sortList );
865 }
866
867 // Set each column's sort count to be able to determine the correct sort
868 // order when clicking on a header cell the next time
869 setHeadersOrder( $headers, sortList, table.headerToColumns );
870
871 // re-build the cache for the tbody cells
872 cache = buildCache( table );
873
874 // set css for headers
875 setHeadersCss( table, $headers, sortList, sortCSS, sortMsg, table.columnToHeader );
876
877 // sort the table and append it to the dom
878 appendToTable( table, multisort( table, sortList, cache ) );
879 };
880
881 // sort initially
882 if ( config.sortList.length > 0 ) {
883 setupForFirstSort();
884 config.sortList = convertSortList( config.sortList );
885 $table.data( 'tablesorter' ).sort();
886 }
887
888 } );
889 },
890
891 addParser: function ( parser ) {
892 var l = parsers.length,
893 a = true;
894 for ( var i = 0; i < l; i++ ) {
895 if ( parsers[i].id.toLowerCase() === parser.id.toLowerCase() ) {
896 a = false;
897 }
898 }
899 if ( a ) {
900 parsers.push( parser );
901 }
902 },
903
904 formatDigit: function ( s ) {
905 var out, c, p, i;
906 if ( ts.transformTable !== false ) {
907 out = '';
908 for ( p = 0; p < s.length; p++ ) {
909 c = s.charAt(p);
910 if ( c in ts.transformTable ) {
911 out += ts.transformTable[c];
912 } else {
913 out += c;
914 }
915 }
916 s = out;
917 }
918 i = parseFloat( s.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
919 return isNaN( i ) ? 0 : i;
920 },
921
922 formatFloat: function ( s ) {
923 var i = parseFloat(s);
924 return isNaN( i ) ? 0 : i;
925 },
926
927 formatInt: function ( s ) {
928 var i = parseInt( s, 10 );
929 return isNaN( i ) ? 0 : i;
930 },
931
932 clearTableBody: function ( table ) {
933 $( table.tBodies[0] ).empty();
934 }
935 };
936
937 // Shortcut
938 ts = $.tablesorter;
939
940 // Register as jQuery prototype method
941 $.fn.tablesorter = function ( settings ) {
942 return ts.construct( this, settings );
943 };
944
945 // Add default parsers
946 ts.addParser( {
947 id: 'text',
948 is: function () {
949 return true;
950 },
951 format: function ( s ) {
952 s = $.trim( s.toLowerCase() );
953 if ( ts.collationRegex ) {
954 var tsc = ts.collationTable;
955 s = s.replace( ts.collationRegex, function ( match ) {
956 var r = tsc[match] ? tsc[match] : tsc[match.toUpperCase()];
957 return r.toLowerCase();
958 } );
959 }
960 return s;
961 },
962 type: 'text'
963 } );
964
965 ts.addParser( {
966 id: 'IPAddress',
967 is: function ( s ) {
968 return ts.rgx.IPAddress[0].test(s);
969 },
970 format: function ( s ) {
971 var a = s.split( '.' ),
972 r = '',
973 l = a.length;
974 for ( var i = 0; i < l; i++ ) {
975 var item = a[i];
976 if ( item.length === 1 ) {
977 r += '00' + item;
978 } else if ( item.length === 2 ) {
979 r += '0' + item;
980 } else {
981 r += item;
982 }
983 }
984 return $.tablesorter.formatFloat(r);
985 },
986 type: 'numeric'
987 } );
988
989 ts.addParser( {
990 id: 'currency',
991 is: function ( s ) {
992 return ts.rgx.currency[0].test(s);
993 },
994 format: function ( s ) {
995 return $.tablesorter.formatDigit( s.replace( ts.rgx.currency[1], '' ) );
996 },
997 type: 'numeric'
998 } );
999
1000 ts.addParser( {
1001 id: 'url',
1002 is: function ( s ) {
1003 return ts.rgx.url[0].test(s);
1004 },
1005 format: function ( s ) {
1006 return $.trim( s.replace( ts.rgx.url[1], '' ) );
1007 },
1008 type: 'text'
1009 } );
1010
1011 ts.addParser( {
1012 id: 'isoDate',
1013 is: function ( s ) {
1014 return ts.rgx.isoDate[0].test(s);
1015 },
1016 format: function ( s ) {
1017 return $.tablesorter.formatFloat((s !== '') ? new Date(s.replace(
1018 new RegExp( /-/g), '/')).getTime() : '0' );
1019 },
1020 type: 'numeric'
1021 } );
1022
1023 ts.addParser( {
1024 id: 'usLongDate',
1025 is: function ( s ) {
1026 return ts.rgx.usLongDate[0].test(s);
1027 },
1028 format: function ( s ) {
1029 return $.tablesorter.formatFloat( new Date(s).getTime() );
1030 },
1031 type: 'numeric'
1032 } );
1033
1034 ts.addParser( {
1035 id: 'date',
1036 is: function ( s ) {
1037 return ( ts.dateRegex[0].test(s) || ts.dateRegex[1].test(s) || ts.dateRegex[2].test(s ));
1038 },
1039 format: function ( s ) {
1040 var match;
1041 s = $.trim( s.toLowerCase() );
1042
1043 if ( ( match = s.match( ts.dateRegex[0] ) ) !== null ) {
1044 if ( mw.config.get( 'wgDefaultDateFormat' ) === 'mdy' || mw.config.get( 'wgContentLanguage' ) === 'en' ) {
1045 s = [ match[3], match[1], match[2] ];
1046 } else if ( mw.config.get( 'wgDefaultDateFormat' ) === 'dmy' ) {
1047 s = [ match[3], match[2], match[1] ];
1048 } else {
1049 // If we get here, we don't know which order the dd-dd-dddd
1050 // date is in. So return something not entirely invalid.
1051 return '99999999';
1052 }
1053 } else if ( ( match = s.match( ts.dateRegex[1] ) ) !== null ) {
1054 s = [ match[3], '' + ts.monthNames[match[2]], match[1] ];
1055 } else if ( ( match = s.match( ts.dateRegex[2] ) ) !== null ) {
1056 s = [ match[3], '' + ts.monthNames[match[1]], match[2] ];
1057 } else {
1058 // Should never get here
1059 return '99999999';
1060 }
1061
1062 // Pad Month and Day
1063 if ( s[1].length === 1 ) {
1064 s[1] = '0' + s[1];
1065 }
1066 if ( s[2].length === 1 ) {
1067 s[2] = '0' + s[2];
1068 }
1069
1070 var y;
1071 if ( ( y = parseInt( s[0], 10) ) < 100 ) {
1072 // Guestimate years without centuries
1073 if ( y < 30 ) {
1074 s[0] = 2000 + y;
1075 } else {
1076 s[0] = 1900 + y;
1077 }
1078 }
1079 while ( s[0].length < 4 ) {
1080 s[0] = '0' + s[0];
1081 }
1082 return parseInt( s.join( '' ), 10 );
1083 },
1084 type: 'numeric'
1085 } );
1086
1087 ts.addParser( {
1088 id: 'time',
1089 is: function ( s ) {
1090 return ts.rgx.time[0].test(s);
1091 },
1092 format: function ( s ) {
1093 return $.tablesorter.formatFloat( new Date( '2000/01/01 ' + s ).getTime() );
1094 },
1095 type: 'numeric'
1096 } );
1097
1098 ts.addParser( {
1099 id: 'number',
1100 is: function ( s ) {
1101 return $.tablesorter.numberRegex.test( $.trim( s ));
1102 },
1103 format: function ( s ) {
1104 return $.tablesorter.formatDigit(s);
1105 },
1106 type: 'numeric'
1107 } );
1108
1109 }( jQuery, mediaWiki ) );