Debian Codegraph @

resources/src/jquery.tablesorter/jquery.tablesorter.js

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