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