Benutzer:MatthiasDD/ts diagnosis.js
Erscheinungsbild
Hinweis: Leere nach dem Veröffentlichen den Browser-Cache, um die Änderungen sehen zu können.
- Firefox/Safari: Umschalttaste drücken und gleichzeitig Aktualisieren anklicken oder entweder Strg+F5 oder Strg+R (⌘+R auf dem Mac) drücken
- Google Chrome: Umschalttaste+Strg+R (⌘+Umschalttaste+R auf dem Mac) drücken
- Edge: Strg+F5 drücken oder Strg drücken und gleichzeitig Aktualisieren anklicken
//Diagnose sortierbarer Tabellen
//
//Nach rechts-Klick auf den Tabellenkopf wird die Sortierfunktion und alle Sortierschlüssel angezeigt,
//wenn angegeben erscheint oben das Attribut 'data-sort-type' mit Wert.
//Danach wird als Tooltip für jede Zelle einzeln die Sortierfunktion und der daraus folgende Sortierschlüssel angezeigt.
//Wenn die Seite geladen ist, wird die Tabellendiagnose erstellt:
jQuery(document).ready(function() {
if($('table.sortable').length){
if(jQuery.isFunction(jQuery.fn["tablediagnosis"])){
ts_diagnosis_init();
}else{
//manchmal ist die Funktion tablediagnosis noch nicht vorhanden
//wait=true;
//console.log( "wait: "+wait );
return setTimeout(ts_diagnosis_init,1000);
}
}
});
function ts_diagnosis_init() {
if($('table.sortable').length){
if(jQuery.isFunction(jQuery.fn["tablediagnosis"])){
//wait=false;
//console.log( "wait: "+wait );
//jede sortierbare Tabelle bearbeiten
$('table.sortable').tablediagnosis();
}
}
}
// This script uses code copyed from MediaWiki 1.26wmf11
// https://git.wikimedia.org/raw/mediawiki%2Fcore.git/4559185ae816f316f9244ecfcab7a995b2b13eb0/resources%2Fsrc%2Fjquery%2Fjquery.tablesorter.js
// last change: 2015-06-20 Timo Tijhof Remove use of $.escapeRE in favour of mw.RegExp.escape
//
//( function ( $, mw ) {
var ts,
parsers = [];
function getParserById( name ) {
var len = parsers.length;
for ( var i = 0; i < len; i++ ) {
if ( parsers[i].id.toLowerCase() === name.toLowerCase() ) {
return parsers[i];
}
}
return false;
}
function getElementSortKey( node ) {
var $node = $( node ),
// Use data-sort-value attribute.
// Use data() instead of attr() so that live value changes
// are processed as well (bug 38152).
data = $node.data( 'sortValue' );
if ( data !== null && data !== undefined ) {
// Cast any numbers or other stuff to a string, methods
// like charAt, toLowerCase and split are expected.
return String( data );
} else {
if ( !node ) {
return $node.text();
} else if ( node.tagName.toLowerCase() === 'img' ) {
return $node.attr( 'alt' ) || ''; // handle undefined alt
} else {
return $.map( $.makeArray( node.childNodes ), function ( elem ) {
// 1 is for document.ELEMENT_NODE (the constant is undefined on old browsers)
if ( elem.nodeType === 1 ) {
return getElementSortKey( elem );
} else {
return $.text( elem );
}
} ).join( '' );
}
}
}
function getTextFromRowAndCellIndex( rows, rowIndex, cellIndex ) {
if ( rows[rowIndex] && rows[rowIndex].cells[cellIndex] ) {
return $.trim( getElementSortKey( rows[rowIndex].cells[cellIndex] ) );
} else {
return '';
}
}
function detectParserForColumn( table, rows, cellIndex ) {
var l = parsers.length,
nodeValue,
// Start with 1 because 0 is the fallback parser
i = 1,
rowIndex = 0,
concurrent = 0,
needed = ( rows.length > 4 ) ? 5 : rows.length;
while( i < l ) {
nodeValue = getTextFromRowAndCellIndex( rows, rowIndex, cellIndex );
if ( nodeValue !== '') {
if ( parsers[i].is( nodeValue, table ) ) {
concurrent++;
rowIndex++;
if ( concurrent >= needed ) {
// Confirmed the parser for multiple cells, let's return it
return parsers[i];
}
} else {
// Check next parser, reset rows
i++;
rowIndex = 0;
concurrent = 0;
}
} else {
// Empty cell
rowIndex++;
if ( rowIndex > rows.length ) {
rowIndex = 0;
i++;
}
}
}
// 0 is always the generic parser (text)
return parsers[0];
}
//neu geschrieben:
function detectParserForCell(table,rows,rowIndex,cellIndex){var l=parsers.length,nodeValue,i=1;
nodeValue=getTextFromRowAndCellIndex(rows,rowIndex,cellIndex);
while(i<l){
if(nodeValue!==''){
if(parsers[i].is(nodeValue,table)){
return parsers[i]; // Confirmed the parser, let's return it
}
else{i++;} // Check next parser
}
else{return parsers[0];} // Empty cell
}
return parsers[0];
}
//ähnlich wie buildCache()
function addTitleTags(table) {
var i, j, $row,
totalRows=(table.tBodies[0]&&table.tBodies[0].rows.length)||0,
totalCells=(table.tBodies[0].rows[0]&&table.tBodies[0].rows[0].cells.length)||0,
config = $( table ).data( 'tablesorter' ).config,
//parsers=config.parsers,
//cache={row:[],normalized:[]};
$node, out, data, cellParser; // extra Variable
for ( i = 0; i < totalRows; ++i ) {
$row = $( table.tBodies[0].rows[i] );
if ( $row.hasClass( config.cssChildRow ) ) {
continue;
}
for ( j = 0; j < totalCells; ++j ) {
$node=$($row[0].cells[j]);
// wenn vorhanden, für jede Zelle das Attribut data-sort-value anzeigen
data = $node.attr( 'data-sort-value' );
if ( data !== undefined ) {
out = "data-sort-value = \"" +data +"\"\n";
}else{
out = "";
}
// für jede Zelle den Parser ermitteln
cellParser = detectParserForCell(table, table.tBodies[0].rows, i, j);
// die Parser.id und den vom Parser ermittelten Sortiertext anzeigen
out += cellParser.id+": "+cellParser.format(getElementSortKey($row[0].cells[j]), table, $row[0].cells[j]);
// dem Attribut title zuordnen
$node.attr('title', out);
}
}
}
//end neu geschrieben
function buildParserCache( table, $headers ) {
var sortType, cells, len, i, parser,
rows = table.tBodies[0].rows,
parsers = [];
if ( rows[0] ) {
cells = rows[0].cells;
len = cells.length;
for ( i = 0; i < len; i++ ) {
parser = false;
sortType = $headers.eq( i ).data( 'sortType' );
if ( sortType !== undefined ) {
parser = getParserById( sortType );
}
if ( parser === false ) {
parser = detectParserForColumn( table, rows, i );
}
parsers.push( parser );
}
}
return parsers;
}
//
//...
//
function buildHeaders( table, msg ) {
var config = $( table ).data( 'tablesorter' ).config,
maxSeen = 0,
colspanOffset = 0,
columns,
i,
$cell,
rowspan,
colspan,
headerCount,
longestTR,
exploded,
$tableHeaders = $( [] ),
$tableRows = $( 'thead:eq(0) > tr', table );
if ( $tableRows.length <= 1 ) {
$tableHeaders = $tableRows.children( 'th' );
} else {
exploded = [];
// Loop through all the dom cells of the thead
$tableRows.each( function ( rowIndex, row ) {
$.each( row.cells, function ( columnIndex, cell ) {
var matrixRowIndex,
matrixColumnIndex;
rowspan = Number( cell.rowSpan );
colspan = Number( cell.colSpan );
// Skip the spots in the exploded matrix that are already filled
while ( exploded[rowIndex] && exploded[rowIndex][columnIndex] !== undefined ) {
++columnIndex;
}
// Find the actual dimensions of the thead, by placing each cell
// in the exploded matrix rowspan times colspan times, with the proper offsets
for ( matrixColumnIndex = columnIndex; matrixColumnIndex < columnIndex + colspan; ++matrixColumnIndex ) {
for ( matrixRowIndex = rowIndex; matrixRowIndex < rowIndex + rowspan; ++matrixRowIndex ) {
if ( !exploded[matrixRowIndex] ) {
exploded[matrixRowIndex] = [];
}
exploded[matrixRowIndex][matrixColumnIndex] = cell;
}
}
} );
} );
// We want to find the row that has the most columns (ignoring colspan)
$.each( exploded, function ( index, cellArray ) {
headerCount = $( uniqueElements( cellArray ) ).filter( 'th' ).length;
if ( headerCount >= maxSeen ) {
maxSeen = headerCount;
longestTR = index;
}
} );
// We cannot use $.unique() here because it sorts into dom order, which is undesirable
$tableHeaders = $( uniqueElements( exploded[longestTR] ) ).filter( 'th' );
}
// as each header can span over multiple columns (using colspan=N),
// we have to bidirectionally map headers to their columns and columns to their headers
$tableHeaders.each( function ( headerIndex ) {
$cell = $( this );
columns = [];
for ( i = 0; i < this.colSpan; i++ ) {
config.columnToHeader[ colspanOffset + i ] = headerIndex;
columns.push( colspanOffset + i );
}
config.headerToColumns[ headerIndex ] = columns;
colspanOffset += this.colSpan;
$cell.data( {
headerIndex: headerIndex,
order: 0,
count: 0
} );
if ( $cell.hasClass( config.unsortableClass ) ) {
$cell.data( 'sortDisabled', true );
}
if ( !$cell.data( 'sortDisabled' ) ) {
$cell
.addClass( config.cssHeader )
.prop( 'tabIndex', 0 )
.attr( {
role: 'columnheader button',
title: msg[1]
} );
}
// add cell to headerList
config.headerList[headerIndex] = this;
} );
return $tableHeaders;
}
//
//...
//
function uniqueElements( array ) {
var uniques = [];
$.each( array, function ( index, elem ) {
if ( elem !== undefined && $.inArray( elem, uniques ) === -1 ) {
uniques.push( elem );
}
} );
return uniques;
}
//
//...
//
function buildTransformTable() {
var ascii, localised, i, digitClass,
digits = '0123456789,.'.split( '' ),
separatorTransformTable = mw.config.get( 'wgSeparatorTransformTable' ),
digitTransformTable = mw.config.get( 'wgDigitTransformTable' );
if ( separatorTransformTable === null || ( separatorTransformTable[0] === '' && digitTransformTable[2] === '' ) ) {
ts.transformTable = false;
} else {
ts.transformTable = {};
// Unpack the transform table
ascii = separatorTransformTable[0].split( '\t' ).concat( digitTransformTable[0].split( '\t' ) );
localised = separatorTransformTable[1].split( '\t' ).concat( digitTransformTable[1].split( '\t' ) );
// Construct regex for number identification
for ( i = 0; i < ascii.length; i++ ) {
ts.transformTable[localised[i]] = ascii[i];
digits.push( mw.RegExp.escape( localised[i] ) );
}
}
digitClass = '[' + digits.join( '', digits ) + ']';
// We allow a trailing percent sign, which we just strip. This works fine
// if percents and regular numbers aren't being mixed.
ts.numberRegex = new RegExp( '^(' + '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
'|' + '[-+\u2212]?' + digitClass + '+[\\s\\xa0]*%?' + // Generic localised
')$', 'i' );
}
function buildDateTable() {
var i, name,
regex = [];
ts.monthNames = {};
for ( i = 0; i < 12; i++ ) {
name = mw.language.months.names[i].toLowerCase();
ts.monthNames[name] = i + 1;
regex.push( mw.RegExp.escape( name ) );
name = mw.language.months.genitive[i].toLowerCase();
ts.monthNames[name] = i + 1;
regex.push( mw.RegExp.escape( name ) );
name = mw.language.months.abbrev[i].toLowerCase().replace( '.', '' );
ts.monthNames[name] = i + 1;
regex.push( mw.RegExp.escape( name ) );
}
// Build piped string
regex = regex.join( '|' );
// Build RegEx
// Any date formated with . , ' - or /
ts.dateRegex[0] = new RegExp( /^\s*(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{2,4})\s*?/i );
// Written Month name, dmy
ts.dateRegex[1] = new RegExp( '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
// Written Month name, mdy
ts.dateRegex[2] = new RegExp( '^\\s*(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
}
/**
* Replace all rowspanned cells in the body with clones in each row, so sorting
* need not worry about them.
*
* @param $table jQuery object for a <table>
*/
//function explodeRowspans( $table )
//function buildCollationTable()
function cacheRegexs() {
if ( ts.rgx ) {
return;
}
ts.rgx = {
IPAddress: [
new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/ )
],
currency: [
new RegExp( /(^[£$€¥]|[£$€¥]$)/ ),
new RegExp( /[£$€¥]/g )
],
url: [
new RegExp( /^(https?|ftp|file):\/\/$/ ),
new RegExp( /(https?|ftp|file):\/\// )
],
isoDate: [
new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/ )
],
usLongDate: [
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)))$/ )
],
time: [
new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/ )
]
};
}
//
//--------------
/* Public scope */
$.tablesorter_diag = { //ohne TAB eingerückte Zeilen sind hier geändert.
defaultOptions: {
cssHeader: 'headerSort',
cssAsc: 'headerSortUp',
cssDesc: 'headerSortDown',
cssChildRow: 'expand-child',
sortMultiSortKey: 'shiftKey',
unsortableClass: 'unsortable',
parsers: {},
cancelSelection: true,
sortList: [],
headerList: [],
headerToColumns: [],
columnToHeader: []
},
dateRegex: [],
monthNames: {},
/**
* @param $tables {jQuery}
* @param settings {Object} (optional)
*/
construct: function ( $tables, settings ) {
return $tables.each( function ( i, table ) {
// Declare and cache.
var $headers, cache, config, sortCSS, sortMsg,
$table = $( table ),
firstTime = true;
// Quit if no tbody
if ( !table.tBodies ) {
return;
}
if ( !table.tHead ) {
// No thead found. Look for rows with <th>s and
// move them into a <thead> tag or a <tfoot> tag
emulateTHeadAndFoot( $table );
// Still no thead? Then quit
if ( !table.tHead ) {
return;
}
}
$table.addClass( 'jquery-tablesorter' );
// Merge and extend
config = $.extend( {}, $.tablesorter.defaultOptions, settings );
// Save the settings where they read
$.data( table, 'tablesorter', { config: config } );
// Get the CSS class names, could be done elsewhere
sortCSS = [ config.cssDesc, config.cssAsc ];
sortMsg = [ mw.msg( 'sort-descending' ), mw.msg( 'sort-ascending' ) ];
// Build headers
$headers = buildHeaders( table, sortMsg );
// Grab and process locale settings.
buildTransformTable();
buildDateTable();
// Precaching regexps can bring 10 fold
// performance improvements in some browsers.
cacheRegexs();
//function setupForFirstSort()
//$headers.not( '.' + config.unsortableClass ).on( 'keypress click', function ( e ) {
// Überschreibe nur event 'mousedown' für headers
$headers.not( '.' + config.unsortableClass ).mousedown( function (e) {
// Rechtsclick:
if(e.button==2){
//Beim ersten Klick muß 'config.parsers' ermittelt werden
if(firstTime){
//von setupForFirstSort() kopiert:
// try to auto detect column type, and store in tables config
config.parsers = buildParserCache( table, $headers );
addTitleTags(table);
}
//neu geschrieben:
//Für diese Spalte die Parser.id und die Sortierwerte im alert()-Fenster anzeigen
var cell = this;
var $cell = $( cell );
var columns = config.headerToColumns[ $cell.data( 'headerIndex' ) ];
// Index of first column belonging to this header
var j= columns[0];
var out = "";
//aus BuildParserCache() (hier j !)
var parser, sortType;
parser = false;
sortType = $headers.eq( j ).data( 'sortType' );
if ( sortType !== undefined ) {
out += "data-sort-type = \"" +sortType +"\"";
parser = getParserById( sortType );
if(!parser){
out += " !"; //wrong data-sort-type
}
out += "\n";
}
out += "Parser: "+config.parsers[j].id +"\n\n";
///dieser cache wurde früher nicht angelegt und nicht sortiert!
///for(var j=0;j<cache.normalized.length;i++){
/// out += cache.normalized[i][j]+"\n";
/// }
///deshalb direkt aus der sortierten Tabelle lesen: (aus buildCache() )
var totalRows = ( $table[0].tBodies[0] && $table[0].tBodies[0].rows.length ) || 0;
for( var i = 0; i < totalRows; ++i ){
var $row = $( table.tBodies[0].rows[i] );
if( $row.hasClass( config.cssChildRow )){
continue;
}
//nur diese Spalte j
//for( var j = 0; j < totalCells; ++j ){
var norm = config.parsers[j].format( getElementSortKey( $row[0].cells[j] ), table, $row[0].cells[j] );
out += norm+"\n";
//}
}
///
alert(out);
}
// --- ab hier Original jquery.tablesorter.js $headers.not( '.' + config.unsortableClass ).mousedown() ---
if ( config.cancelSelection ) {
this.onselectstart = function () {
return false;
};
return false;
}
});
});
}, //end construct
addParser: function ( parser ) {
var i,
len = parsers.length,
a = true;
for ( i = 0; i < len; i++ ) {
if ( parsers[i].id.toLowerCase() === parser.id.toLowerCase() ) {
a = false;
}
}
if ( a ) {
parsers.push( parser );
}
}
//
//...
//
};
// Shortcut
ts = $.tablesorter_diag;
// Register as jQuery prototype method
$.fn.tablediagnosis = function ( settings ) {
return ts.construct( this, settings );
};
// Add default parsers
ts.addParser( {
id: 'text',
is: function () {
return true;
},
format: function ( s ) {
s = $.trim( s.toLowerCase() );
if ( ts.collationRegex ) {
var tsc = ts.collationTable;
s = s.replace( ts.collationRegex, function ( match ) {
var r = tsc[match] ? tsc[match] : tsc[match.toUpperCase()];
return r.toLowerCase();
} );
}
return s;
},
type: 'text'
} );
ts.addParser( {
id: 'IPAddress',
is: function ( s ) {
return ts.rgx.IPAddress[0].test( s );
},
format: function ( s ) {
var i, item,
a = s.split( '.' ),
r = '',
len = a.length;
for ( i = 0; i < len; i++ ) {
item = a[i];
if ( item.length === 1 ) {
r += '00' + item;
} else if ( item.length === 2 ) {
r += '0' + item;
} else {
r += item;
}
}
return $.tablesorter.formatFloat( r );
},
type: 'numeric'
} );
ts.addParser( {
id: 'currency',
is: function ( s ) {
return ts.rgx.currency[0].test( s );
},
format: function ( s ) {
return $.tablesorter.formatDigit( s.replace( ts.rgx.currency[1], '' ) );
},
type: 'numeric'
} );
ts.addParser( {
id: 'url',
is: function ( s ) {
return ts.rgx.url[0].test( s );
},
format: function ( s ) {
return $.trim( s.replace( ts.rgx.url[1], '' ) );
},
type: 'text'
} );
ts.addParser( {
id: 'isoDate',
is: function ( s ) {
return ts.rgx.isoDate[0].test( s );
},
format: function ( s ) {
return $.tablesorter.formatFloat( ( s !== '' ) ? new Date( s.replace(
new RegExp( /-/g ), '/' ) ).getTime() : '0' );
},
type: 'numeric'
} );
ts.addParser( {
id: 'usLongDate',
is: function ( s ) {
return ts.rgx.usLongDate[0].test( s );
},
format: function ( s ) {
return $.tablesorter.formatFloat( new Date( s ).getTime() );
},
type: 'numeric'
} );
ts.addParser( {
id: 'date',
is: function ( s ) {
return ( ts.dateRegex[0].test( s ) || ts.dateRegex[1].test( s ) || ts.dateRegex[2].test( s ) );
},
format: function ( s ) {
var match, y;
s = $.trim( s.toLowerCase() );
if ( ( match = s.match( ts.dateRegex[0] ) ) !== null ) {
if ( mw.config.get( 'wgDefaultDateFormat' ) === 'mdy' || mw.config.get( 'wgPageContentLanguage' ) === 'en' ) {
s = [ match[3], match[1], match[2] ];
} else if ( mw.config.get( 'wgDefaultDateFormat' ) === 'dmy' ) {
s = [ match[3], match[2], match[1] ];
} else {
// If we get here, we don't know which order the dd-dd-dddd
// date is in. So return something not entirely invalid.
return '99999999';
}
} else if ( ( match = s.match( ts.dateRegex[1] ) ) !== null ) {
s = [ match[3], String( ts.monthNames[match[2]] ), match[1] ];
} else if ( ( match = s.match( ts.dateRegex[2] ) ) !== null ) {
s = [ match[3], String( ts.monthNames[match[1]] ), match[2] ];
} else {
// Should never get here
return '99999999';
}
// Pad Month and Day
if ( s[1].length === 1 ) {
s[1] = '0' + s[1];
}
if ( s[2].length === 1 ) {
s[2] = '0' + s[2];
}
if ( ( y = parseInt( s[0], 10 ) ) < 100 ) {
// Guestimate years without centuries
if ( y < 30 ) {
s[0] = 2000 + y;
} else {
s[0] = 1900 + y;
}
}
while ( s[0].length < 4 ) {
s[0] = '0' + s[0];
}
return parseInt( s.join( '' ), 10 );
},
type: 'numeric'
} );
ts.addParser( {
id: 'time',
is: function ( s ) {
return ts.rgx.time[0].test( s );
},
format: function ( s ) {
return $.tablesorter.formatFloat( new Date( '2000/01/01 ' + s ).getTime() );
},
type: 'numeric'
} );
ts.addParser( {
id: 'number',
is: function ( s ) {
return $.tablesorter.numberRegex.test( $.trim( s ) );
},
format: function ( s ) {
return $.tablesorter.formatDigit( s );
},
type: 'numeric'
} );
//}( jQuery, mediaWiki ) );