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