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