Merge "JSON i18n shim: Only register LocalisationCacheRecache handler once"
[lhc/web/wiklou.git] / resources / src / 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 /* Local scope */
72
73 var ts,
74 parsers = [];
75
76 /* Parser utility functions */
77
78 function getParserById( name ) {
79 var i,
80 len = parsers.length;
81 for ( 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 i, pos, l, j,
231 row = cache.row,
232 normalized = cache.normalized,
233 totalRows = normalized.length,
234 checkCell = ( normalized[0].length - 1 ),
235 fragment = document.createDocumentFragment();
236
237 for ( i = 0; i < totalRows; i++ ) {
238 pos = normalized[i][checkCell];
239
240 l = row[pos].length;
241
242 for ( 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 $thead, $tfoot, i, len,
264 $rows = $table.find( '> tbody > tr' );
265 if ( !$table.get( 0 ).tHead ) {
266 $thead = $( '<thead>' );
267 $rows.each( function () {
268 if ( $( this ).children( 'td' ).length ) {
269 // This row contains a <td>, so it's not a header row
270 // Stop here
271 return false;
272 }
273 $thead.append( this );
274 } );
275 $table.find( ' > tbody:first' ).before( $thead );
276 }
277 if ( !$table.get( 0 ).tFoot ) {
278 $tfoot = $( '<tfoot>' );
279 len = $rows.length;
280 for ( i = len - 1; i >= 0; i-- ) {
281 if ( $( $rows[i] ).children( 'td' ).length ) {
282 break;
283 }
284 $tfoot.prepend( $( $rows[i] ) );
285 }
286 $table.append( $tfoot );
287 }
288 }
289
290 function buildHeaders( table, msg ) {
291 var maxSeen = 0,
292 colspanOffset = 0,
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 var rowspan,
301 colspan,
302 headerCount,
303 longestTR,
304 matrixRowIndex,
305 matrixColumnIndex,
306 exploded = [];
307
308 // Loop through all the dom cells of the thead
309 $tableRows.each( function ( rowIndex, row ) {
310 $.each( row.cells, function ( columnIndex, cell ) {
311 rowspan = Number( cell.rowSpan );
312 colspan = Number( cell.colSpan );
313
314 // Skip the spots in the exploded matrix that are already filled
315 while ( exploded[rowIndex] && exploded[rowIndex][columnIndex] !== undefined ) {
316 ++columnIndex;
317 }
318
319 // Find the actual dimensions of the thead, by placing each cell
320 // in the exploded matrix rowspan times colspan times, with the proper offsets
321 for ( matrixColumnIndex = columnIndex; matrixColumnIndex < columnIndex + colspan; ++matrixColumnIndex ) {
322 for ( matrixRowIndex = rowIndex; matrixRowIndex < rowIndex + rowspan; ++matrixRowIndex ) {
323 if ( !exploded[matrixRowIndex] ) {
324 exploded[matrixRowIndex] = [];
325 }
326 exploded[matrixRowIndex][matrixColumnIndex] = cell;
327 }
328 }
329 } );
330 } );
331 // We want to find the row that has the most columns (ignoring colspan)
332 $.each( exploded, function ( index, cellArray ) {
333 headerCount = $.unique( $( cellArray ) ).length;
334 if ( headerCount >= maxSeen ) {
335 maxSeen = headerCount;
336 longestTR = index;
337 }
338 } );
339 // We cannot use $.unique() here because it sorts into dom order, which is undesirable
340 $tableHeaders = $( uniqueElements( exploded[longestTR] ) );
341 }
342
343 // as each header can span over multiple columns (using colspan=N),
344 // we have to bidirectionally map headers to their columns and columns to their headers
345 table.headerToColumns = [];
346 table.columnToHeader = [];
347
348 $tableHeaders.each( function ( headerIndex ) {
349 columns = [];
350 for ( i = 0; i < this.colSpan; i++ ) {
351 table.columnToHeader[ colspanOffset + i ] = headerIndex;
352 columns.push( colspanOffset + i );
353 }
354
355 table.headerToColumns[ headerIndex ] = columns;
356 colspanOffset += this.colSpan;
357
358 this.headerIndex = headerIndex;
359 this.order = 0;
360 this.count = 0;
361
362 if ( $( this ).hasClass( table.config.unsortableClass ) ) {
363 this.sortDisabled = true;
364 }
365
366 if ( !this.sortDisabled ) {
367 $( this )
368 .addClass( table.config.cssHeader )
369 .prop( 'tabIndex', 0 )
370 .attr( {
371 role: 'columnheader button',
372 title: msg[1]
373 } );
374 }
375
376 // add cell to headerList
377 table.config.headerList[headerIndex] = this;
378 } );
379
380 return $tableHeaders;
381
382 }
383
384 /**
385 * Sets the sort count of the columns that are not affected by the sorting to have them sorted
386 * in default (ascending) order when their header cell is clicked the next time.
387 *
388 * @param {jQuery} $headers
389 * @param {Number[][]} sortList
390 * @param {Number[][]} headerToColumns
391 */
392 function setHeadersOrder( $headers, sortList, headerToColumns ) {
393 // Loop through all headers to retrieve the indices of the columns the header spans across:
394 $.each( headerToColumns, function ( headerIndex, columns ) {
395
396 $.each( columns, function ( i, columnIndex ) {
397 var header = $headers[headerIndex];
398
399 if ( !isValueInArray( columnIndex, sortList ) ) {
400 // Column shall not be sorted: Reset header count and order.
401 header.order = 0;
402 header.count = 0;
403 } else {
404 // Column shall be sorted: Apply designated count and order.
405 $.each( sortList, function ( j, sortColumn ) {
406 if ( sortColumn[0] === i ) {
407 header.order = sortColumn[1];
408 header.count = sortColumn[1] + 1;
409 return false;
410 }
411 } );
412 }
413 } );
414
415 } );
416 }
417
418 function isValueInArray( v, a ) {
419 var l = a.length;
420 for ( var i = 0; i < l; i++ ) {
421 if ( a[i][0] === v ) {
422 return true;
423 }
424 }
425 return false;
426 }
427
428 function uniqueElements( array ) {
429 var uniques = [];
430 $.each( array, function ( index, elem ) {
431 if ( elem !== undefined && $.inArray( elem, uniques ) === -1 ) {
432 uniques.push( elem );
433 }
434 } );
435 return uniques;
436 }
437
438 function setHeadersCss( table, $headers, list, css, msg, columnToHeader ) {
439 // Remove all header information and reset titles to default message
440 $headers.removeClass( css[0] ).removeClass( css[1] ).attr( 'title', msg[1] );
441
442 for ( var i = 0; i < list.length; i++ ) {
443 $headers.eq( columnToHeader[ list[i][0] ] )
444 .addClass( css[ list[i][1] ] )
445 .attr( 'title', msg[ list[i][1] ] );
446 }
447 }
448
449 function sortText( a, b ) {
450 return ( ( a < b ) ? -1 : ( ( a > b ) ? 1 : 0 ) );
451 }
452
453 function sortTextDesc( a, b ) {
454 return ( ( b < a ) ? -1 : ( ( b > a ) ? 1 : 0 ) );
455 }
456
457 function multisort( table, sortList, cache ) {
458 var i,
459 sortFn = [],
460 len = sortList.length;
461 for ( i = 0; i < len; i++ ) {
462 sortFn[i] = ( sortList[i][1] ) ? sortTextDesc : sortText;
463 }
464 cache.normalized.sort( function ( array1, array2 ) {
465 var i, col, ret;
466 for ( i = 0; i < len; i++ ) {
467 col = sortList[i][0];
468 ret = sortFn[i].call( this, array1[col], array2[col] );
469 if ( ret !== 0 ) {
470 return ret;
471 }
472 }
473 // Fall back to index number column to ensure stable sort
474 return sortText.call( this, array1[array1.length - 1], array2[array2.length - 1] );
475 } );
476 return cache;
477 }
478
479 function buildTransformTable() {
480 var ascii, localised, i, digitClass,
481 digits = '0123456789,.'.split( '' ),
482 separatorTransformTable = mw.config.get( 'wgSeparatorTransformTable' ),
483 digitTransformTable = mw.config.get( 'wgDigitTransformTable' );
484
485 if ( separatorTransformTable === null || ( separatorTransformTable[0] === '' && digitTransformTable[2] === '' ) ) {
486 ts.transformTable = false;
487 } else {
488 ts.transformTable = {};
489
490 // Unpack the transform table
491 ascii = separatorTransformTable[0].split( '\t' ).concat( digitTransformTable[0].split( '\t' ) );
492 localised = separatorTransformTable[1].split( '\t' ).concat( digitTransformTable[1].split( '\t' ) );
493
494 // Construct regex for number identification
495 for ( i = 0; i < ascii.length; i++ ) {
496 ts.transformTable[localised[i]] = ascii[i];
497 digits.push( $.escapeRE( localised[i] ) );
498 }
499 }
500 digitClass = '[' + digits.join( '', digits ) + ']';
501
502 // We allow a trailing percent sign, which we just strip. This works fine
503 // if percents and regular numbers aren't being mixed.
504 ts.numberRegex = new RegExp( '^(' + '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
505 '|' + '[-+\u2212]?' + digitClass + '+[\\s\\xa0]*%?' + // Generic localised
506 ')$', 'i' );
507 }
508
509 function buildDateTable() {
510 var i, name,
511 regex = [];
512
513 ts.monthNames = {};
514
515 for ( i = 0; i < 12; i++ ) {
516 name = mw.language.months.names[i].toLowerCase();
517 ts.monthNames[name] = i + 1;
518 regex.push( $.escapeRE( name ) );
519 name = mw.language.months.genitive[i].toLowerCase();
520 ts.monthNames[name] = i + 1;
521 regex.push( $.escapeRE( name ) );
522 name = mw.language.months.abbrev[i].toLowerCase().replace( '.', '' );
523 ts.monthNames[name] = i + 1;
524 regex.push( $.escapeRE( name ) );
525 }
526
527 // Build piped string
528 regex = regex.join( '|' );
529
530 // Build RegEx
531 // Any date formated with . , ' - or /
532 ts.dateRegex[0] = new RegExp( /^\s*(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{2,4})\s*?/i );
533
534 // Written Month name, dmy
535 ts.dateRegex[1] = new RegExp( '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
536
537 // Written Month name, mdy
538 ts.dateRegex[2] = new RegExp( '^\\s*(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
539
540 }
541
542 /**
543 * Replace all rowspanned cells in the body with clones in each row, so sorting
544 * need not worry about them.
545 *
546 * @param $table jQuery object for a <table>
547 */
548 function explodeRowspans( $table ) {
549 var spanningRealCellIndex, rowSpan, colSpan,
550 cell, i, $tds, $clone, $nextRows,
551 rowspanCells = $table.find( '> tbody > tr > [rowspan]' ).get();
552
553 // Short circuit
554 if ( !rowspanCells.length ) {
555 return;
556 }
557
558 // First, we need to make a property like cellIndex but taking into
559 // account colspans. We also cache the rowIndex to avoid having to take
560 // cell.parentNode.rowIndex in the sorting function below.
561 $table.find( '> tbody > tr' ).each( function () {
562 var i,
563 col = 0,
564 l = this.cells.length;
565 for ( i = 0; i < l; i++ ) {
566 this.cells[i].realCellIndex = col;
567 this.cells[i].realRowIndex = this.rowIndex;
568 col += this.cells[i].colSpan;
569 }
570 } );
571
572 // Split multi row cells into multiple cells with the same content.
573 // Sort by column then row index to avoid problems with odd table structures.
574 // Re-sort whenever a rowspanned cell's realCellIndex is changed, because it
575 // might change the sort order.
576 function resortCells() {
577 rowspanCells = rowspanCells.sort( function ( a, b ) {
578 var ret = a.realCellIndex - b.realCellIndex;
579 if ( !ret ) {
580 ret = a.realRowIndex - b.realRowIndex;
581 }
582 return ret;
583 } );
584 $.each( rowspanCells, function () {
585 this.needResort = false;
586 } );
587 }
588 resortCells();
589
590 function filterfunc() {
591 return this.realCellIndex >= spanningRealCellIndex;
592 }
593
594 function fixTdCellIndex() {
595 this.realCellIndex += colSpan;
596 if ( this.rowSpan > 1 ) {
597 this.needResort = true;
598 }
599 }
600
601 while ( rowspanCells.length ) {
602 if ( rowspanCells[0].needResort ) {
603 resortCells();
604 }
605
606 cell = rowspanCells.shift();
607 rowSpan = cell.rowSpan;
608 colSpan = cell.colSpan;
609 spanningRealCellIndex = cell.realCellIndex;
610 cell.rowSpan = 1;
611 $nextRows = $( cell ).parent().nextAll();
612 for ( i = 0; i < rowSpan - 1; i++ ) {
613 $tds = $( $nextRows[i].cells ).filter( filterfunc );
614 $clone = $( cell ).clone();
615 $clone[0].realCellIndex = spanningRealCellIndex;
616 if ( $tds.length ) {
617 $tds.each( fixTdCellIndex );
618 $tds.first().before( $clone );
619 } else {
620 $nextRows.eq( i ).append( $clone );
621 }
622 }
623 }
624 }
625
626 function buildCollationTable() {
627 ts.collationTable = mw.config.get( 'tableSorterCollation' );
628 ts.collationRegex = null;
629 if ( ts.collationTable ) {
630 var key,
631 keys = [];
632
633 // Build array of key names
634 for ( key in ts.collationTable ) {
635 // Check hasOwn to be safe
636 if ( ts.collationTable.hasOwnProperty( key ) ) {
637 keys.push( key );
638 }
639 }
640 if ( keys.length ) {
641 ts.collationRegex = new RegExp( '[' + keys.join( '' ) + ']', 'ig' );
642 }
643 }
644 }
645
646 function cacheRegexs() {
647 if ( ts.rgx ) {
648 return;
649 }
650 ts.rgx = {
651 IPAddress: [
652 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/ )
653 ],
654 currency: [
655 new RegExp( /(^[£$€¥]|[£$€¥]$)/ ),
656 new RegExp( /[£$€¥]/g )
657 ],
658 url: [
659 new RegExp( /^(https?|ftp|file):\/\/$/ ),
660 new RegExp( /(https?|ftp|file):\/\// )
661 ],
662 isoDate: [
663 new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/ )
664 ],
665 usLongDate: [
666 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)))$/ )
667 ],
668 time: [
669 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/ )
670 ]
671 };
672 }
673
674 /**
675 * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
676 * structure [ [ Integer , Integer ], ... ]
677 *
678 * @param sortObjects {Array} List of sort objects.
679 * @return {Array} List of internal sort definitions.
680 */
681
682 function convertSortList( sortObjects ) {
683 var sortList = [];
684 $.each( sortObjects, function ( i, sortObject ) {
685 $.each( sortObject, function ( columnIndex, order ) {
686 var orderIndex = ( order === 'desc' ) ? 1 : 0;
687 sortList.push( [parseInt( columnIndex, 10 ), orderIndex] );
688 } );
689 } );
690 return sortList;
691 }
692
693 /* Public scope */
694
695 $.tablesorter = {
696
697 defaultOptions: {
698 cssHeader: 'headerSort',
699 cssAsc: 'headerSortUp',
700 cssDesc: 'headerSortDown',
701 cssChildRow: 'expand-child',
702 sortInitialOrder: 'asc',
703 sortMultiSortKey: 'shiftKey',
704 sortLocaleCompare: false,
705 unsortableClass: 'unsortable',
706 parsers: {},
707 widgets: [],
708 headers: {},
709 cancelSelection: true,
710 sortList: [],
711 headerList: [],
712 selectorHeaders: 'thead tr:eq(0) th',
713 debug: false
714 },
715
716 dateRegex: [],
717 monthNames: {},
718
719 /**
720 * @param $tables {jQuery}
721 * @param settings {Object} (optional)
722 */
723 construct: function ( $tables, settings ) {
724 return $tables.each( function ( i, table ) {
725 // Declare and cache.
726 var $headers, cache, config, sortCSS, sortMsg,
727 $table = $( table ),
728 firstTime = true;
729
730 // Quit if no tbody
731 if ( !table.tBodies ) {
732 return;
733 }
734 if ( !table.tHead ) {
735 // No thead found. Look for rows with <th>s and
736 // move them into a <thead> tag or a <tfoot> tag
737 emulateTHeadAndFoot( $table );
738
739 // Still no thead? Then quit
740 if ( !table.tHead ) {
741 return;
742 }
743 }
744 $table.addClass( 'jquery-tablesorter' );
745
746 // FIXME config should probably not be stored in the plain table node
747 // New config object.
748 table.config = {};
749
750 // Merge and extend.
751 config = $.extend( table.config, $.tablesorter.defaultOptions, settings );
752
753 // Save the settings where they read
754 $.data( table, 'tablesorter', { config: config } );
755
756 // Get the CSS class names, could be done else where.
757 sortCSS = [ config.cssDesc, config.cssAsc ];
758 sortMsg = [ mw.msg( 'sort-descending' ), mw.msg( 'sort-ascending' ) ];
759
760 // Build headers
761 $headers = buildHeaders( table, sortMsg );
762
763 // Grab and process locale settings.
764 buildTransformTable();
765 buildDateTable();
766
767 // Precaching regexps can bring 10 fold
768 // performance improvements in some browsers.
769 cacheRegexs();
770
771 function setupForFirstSort() {
772 firstTime = false;
773
774 // Defer buildCollationTable to first sort. As user and site scripts
775 // may customize tableSorterCollation but load after $.ready(), other
776 // scripts may call .tablesorter() before they have done the
777 // tableSorterCollation customizations.
778 buildCollationTable();
779
780 // Legacy fix of .sortbottoms
781 // Wrap them inside inside a tfoot (because that's what they actually want to be) &
782 // and put the <tfoot> at the end of the <table>
783 var $sortbottoms = $table.find( '> tbody > tr.sortbottom' );
784 if ( $sortbottoms.length ) {
785 var $tfoot = $table.children( 'tfoot' );
786 if ( $tfoot.length ) {
787 $tfoot.eq( 0 ).prepend( $sortbottoms );
788 } else {
789 $table.append( $( '<tfoot>' ).append( $sortbottoms ) );
790 }
791 }
792
793 explodeRowspans( $table );
794
795 // try to auto detect column type, and store in tables config
796 table.config.parsers = buildParserCache( table, $headers );
797 }
798
799 // Apply event handling to headers
800 // this is too big, perhaps break it out?
801 $headers.not( '.' + table.config.unsortableClass ).on( 'keypress click', function ( e ) {
802 if ( e.type === 'click' && e.target.nodeName.toLowerCase() === 'a' ) {
803 // The user clicked on a link inside a table header.
804 // Do nothing and let the default link click action continue.
805 return true;
806 }
807
808 if ( e.type === 'keypress' && e.which !== 13 ) {
809 // Only handle keypresses on the "Enter" key.
810 return true;
811 }
812
813 if ( firstTime ) {
814 setupForFirstSort();
815 }
816
817 // Build the cache for the tbody cells
818 // to share between calculations for this sort action.
819 // Re-calculated each time a sort action is performed due to possiblity
820 // that sort values change. Shouldn't be too expensive, but if it becomes
821 // too slow an event based system should be implemented somehow where
822 // cells get event .change() and bubbles up to the <table> here
823 cache = buildCache( table );
824
825 var totalRows = ( $table[0].tBodies[0] && $table[0].tBodies[0].rows.length ) || 0;
826 if ( !table.sortDisabled && totalRows > 0 ) {
827 // Get current column sort order
828 this.order = this.count % 2;
829 this.count++;
830
831 var cell, columns, newSortList, i;
832
833 cell = this;
834 // Get current column index
835 columns = table.headerToColumns[ this.headerIndex ];
836 newSortList = $.map( columns, function ( c ) {
837 // jQuery "helpfully" flattens the arrays...
838 return [[c, cell.order]];
839 } );
840 // Index of first column belonging to this header
841 i = columns[0];
842
843 if ( !e[config.sortMultiSortKey] ) {
844 // User only wants to sort on one column set
845 // Flush the sort list and add new columns
846 config.sortList = newSortList;
847 } else {
848 // Multi column sorting
849 // It is not possible for one column to belong to multiple headers,
850 // so this is okay - we don't need to check for every value in the columns array
851 if ( isValueInArray( i, config.sortList ) ) {
852 // The user has clicked on an already sorted column.
853 // Reverse the sorting direction for all tables.
854 for ( var j = 0; j < config.sortList.length; j++ ) {
855 var s = config.sortList[j],
856 o = config.headerList[s[0]];
857 if ( isValueInArray( s[0], newSortList ) ) {
858 o.count = s[1];
859 o.count++;
860 s[1] = o.count % 2;
861 }
862 }
863 } else {
864 // Add columns to sort list array
865 config.sortList = config.sortList.concat( newSortList );
866 }
867 }
868
869 // Reset order/counts of cells not affected by sorting
870 setHeadersOrder( $headers, config.sortList, table.headerToColumns );
871
872 // Set CSS for headers
873 setHeadersCss( $table[0], $headers, config.sortList, sortCSS, sortMsg, table.columnToHeader );
874 appendToTable(
875 $table[0], multisort( $table[0], config.sortList, cache )
876 );
877
878 // Stop normal event by returning false
879 return false;
880 }
881
882 // Cancel selection
883 } ).mousedown( function () {
884 if ( config.cancelSelection ) {
885 this.onselectstart = function () {
886 return false;
887 };
888 return false;
889 }
890 } );
891
892 /**
893 * Sorts the table. If no sorting is specified by passing a list of sort
894 * objects, the table is sorted according to the initial sorting order.
895 * Passing an empty array will reset sorting (basically just reset the headers
896 * making the table appear unsorted).
897 *
898 * @param sortList {Array} (optional) List of sort objects.
899 */
900 $table.data( 'tablesorter' ).sort = function ( sortList ) {
901
902 if ( firstTime ) {
903 setupForFirstSort();
904 }
905
906 if ( sortList === undefined ) {
907 sortList = config.sortList;
908 } else if ( sortList.length > 0 ) {
909 sortList = convertSortList( sortList );
910 }
911
912 // Set each column's sort count to be able to determine the correct sort
913 // order when clicking on a header cell the next time
914 setHeadersOrder( $headers, sortList, table.headerToColumns );
915
916 // re-build the cache for the tbody cells
917 cache = buildCache( table );
918
919 // set css for headers
920 setHeadersCss( table, $headers, sortList, sortCSS, sortMsg, table.columnToHeader );
921
922 // sort the table and append it to the dom
923 appendToTable( table, multisort( table, sortList, cache ) );
924 };
925
926 // sort initially
927 if ( config.sortList.length > 0 ) {
928 setupForFirstSort();
929 config.sortList = convertSortList( config.sortList );
930 $table.data( 'tablesorter' ).sort();
931 }
932
933 } );
934 },
935
936 addParser: function ( parser ) {
937 var l = parsers.length,
938 a = true;
939 for ( var i = 0; i < l; i++ ) {
940 if ( parsers[i].id.toLowerCase() === parser.id.toLowerCase() ) {
941 a = false;
942 }
943 }
944 if ( a ) {
945 parsers.push( parser );
946 }
947 },
948
949 formatDigit: function ( s ) {
950 var out, c, p, i;
951 if ( ts.transformTable !== false ) {
952 out = '';
953 for ( p = 0; p < s.length; p++ ) {
954 c = s.charAt( p );
955 if ( c in ts.transformTable ) {
956 out += ts.transformTable[c];
957 } else {
958 out += c;
959 }
960 }
961 s = out;
962 }
963 i = parseFloat( s.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
964 return isNaN( i ) ? 0 : i;
965 },
966
967 formatFloat: function ( s ) {
968 var i = parseFloat( s );
969 return isNaN( i ) ? 0 : i;
970 },
971
972 formatInt: function ( s ) {
973 var i = parseInt( s, 10 );
974 return isNaN( i ) ? 0 : i;
975 },
976
977 clearTableBody: function ( table ) {
978 $( table.tBodies[0] ).empty();
979 }
980 };
981
982 // Shortcut
983 ts = $.tablesorter;
984
985 // Register as jQuery prototype method
986 $.fn.tablesorter = function ( settings ) {
987 return ts.construct( this, settings );
988 };
989
990 // Add default parsers
991 ts.addParser( {
992 id: 'text',
993 is: function () {
994 return true;
995 },
996 format: function ( s ) {
997 s = $.trim( s.toLowerCase() );
998 if ( ts.collationRegex ) {
999 var tsc = ts.collationTable;
1000 s = s.replace( ts.collationRegex, function ( match ) {
1001 var r = tsc[match] ? tsc[match] : tsc[match.toUpperCase()];
1002 return r.toLowerCase();
1003 } );
1004 }
1005 return s;
1006 },
1007 type: 'text'
1008 } );
1009
1010 ts.addParser( {
1011 id: 'IPAddress',
1012 is: function ( s ) {
1013 return ts.rgx.IPAddress[0].test( s );
1014 },
1015 format: function ( s ) {
1016 var a = s.split( '.' ),
1017 r = '',
1018 l = a.length;
1019 for ( var i = 0; i < l; i++ ) {
1020 var item = a[i];
1021 if ( item.length === 1 ) {
1022 r += '00' + item;
1023 } else if ( item.length === 2 ) {
1024 r += '0' + item;
1025 } else {
1026 r += item;
1027 }
1028 }
1029 return $.tablesorter.formatFloat( r );
1030 },
1031 type: 'numeric'
1032 } );
1033
1034 ts.addParser( {
1035 id: 'currency',
1036 is: function ( s ) {
1037 return ts.rgx.currency[0].test( s );
1038 },
1039 format: function ( s ) {
1040 return $.tablesorter.formatDigit( s.replace( ts.rgx.currency[1], '' ) );
1041 },
1042 type: 'numeric'
1043 } );
1044
1045 ts.addParser( {
1046 id: 'url',
1047 is: function ( s ) {
1048 return ts.rgx.url[0].test( s );
1049 },
1050 format: function ( s ) {
1051 return $.trim( s.replace( ts.rgx.url[1], '' ) );
1052 },
1053 type: 'text'
1054 } );
1055
1056 ts.addParser( {
1057 id: 'isoDate',
1058 is: function ( s ) {
1059 return ts.rgx.isoDate[0].test( s );
1060 },
1061 format: function ( s ) {
1062 return $.tablesorter.formatFloat( ( s !== '' ) ? new Date( s.replace(
1063 new RegExp( /-/g ), '/' ) ).getTime() : '0' );
1064 },
1065 type: 'numeric'
1066 } );
1067
1068 ts.addParser( {
1069 id: 'usLongDate',
1070 is: function ( s ) {
1071 return ts.rgx.usLongDate[0].test( s );
1072 },
1073 format: function ( s ) {
1074 return $.tablesorter.formatFloat( new Date( s ).getTime() );
1075 },
1076 type: 'numeric'
1077 } );
1078
1079 ts.addParser( {
1080 id: 'date',
1081 is: function ( s ) {
1082 return ( ts.dateRegex[0].test( s ) || ts.dateRegex[1].test( s ) || ts.dateRegex[2].test( s ) );
1083 },
1084 format: function ( s ) {
1085 var match;
1086 s = $.trim( s.toLowerCase() );
1087
1088 if ( ( match = s.match( ts.dateRegex[0] ) ) !== null ) {
1089 if ( mw.config.get( 'wgDefaultDateFormat' ) === 'mdy' || mw.config.get( 'wgContentLanguage' ) === 'en' ) {
1090 s = [ match[3], match[1], match[2] ];
1091 } else if ( mw.config.get( 'wgDefaultDateFormat' ) === 'dmy' ) {
1092 s = [ match[3], match[2], match[1] ];
1093 } else {
1094 // If we get here, we don't know which order the dd-dd-dddd
1095 // date is in. So return something not entirely invalid.
1096 return '99999999';
1097 }
1098 } else if ( ( match = s.match( ts.dateRegex[1] ) ) !== null ) {
1099 s = [ match[3], '' + ts.monthNames[match[2]], match[1] ];
1100 } else if ( ( match = s.match( ts.dateRegex[2] ) ) !== null ) {
1101 s = [ match[3], '' + ts.monthNames[match[1]], match[2] ];
1102 } else {
1103 // Should never get here
1104 return '99999999';
1105 }
1106
1107 // Pad Month and Day
1108 if ( s[1].length === 1 ) {
1109 s[1] = '0' + s[1];
1110 }
1111 if ( s[2].length === 1 ) {
1112 s[2] = '0' + s[2];
1113 }
1114
1115 var y;
1116 if ( ( y = parseInt( s[0], 10 ) ) < 100 ) {
1117 // Guestimate years without centuries
1118 if ( y < 30 ) {
1119 s[0] = 2000 + y;
1120 } else {
1121 s[0] = 1900 + y;
1122 }
1123 }
1124 while ( s[0].length < 4 ) {
1125 s[0] = '0' + s[0];
1126 }
1127 return parseInt( s.join( '' ), 10 );
1128 },
1129 type: 'numeric'
1130 } );
1131
1132 ts.addParser( {
1133 id: 'time',
1134 is: function ( s ) {
1135 return ts.rgx.time[0].test( s );
1136 },
1137 format: function ( s ) {
1138 return $.tablesorter.formatFloat( new Date( '2000/01/01 ' + s ).getTime() );
1139 },
1140 type: 'numeric'
1141 } );
1142
1143 ts.addParser( {
1144 id: 'number',
1145 is: function ( s ) {
1146 return $.tablesorter.numberRegex.test( $.trim( s ) );
1147 },
1148 format: function ( s ) {
1149 return $.tablesorter.formatDigit( s );
1150 },
1151 type: 'numeric'
1152 } );
1153
1154 }( jQuery, mediaWiki ) );