add sorting to wiki tables

This commit is contained in:
Frédéric Péters 2016-10-10 14:09:18 +02:00
parent 34114942b7
commit 8c0d5aa80c
1 changed files with 81 additions and 0 deletions

View File

@ -1,4 +1,85 @@
function sort_table() {
var table = $(this).parents('tbody')[0];
/* get table column index */
var child = $(this)[0];
var col = 0;
while( (child = child.previousSibling) != null ) {
if (child.tagName == 'TD') col++;
}
/* save sorting preferences */
var asc = parseInt($(table).data('sort-asc') || 1);
var ccol = parseInt($(table).data('sort-col') || 0);
if (col == ccol) { asc = -asc; } else { asc = 1; }
$(table).data('sort-col', col);
$(table).data('sort-asc', asc);
/* fill the array with values from the table */
var rows = table.rows, rlen = rows.length, arr = new Array(), i, j, cells, clen;
for (i=0; i<rlen; i++){
cells = rows[i].cells;
clen = cells.length;
arr[i] = new Array();
for (j = 0; j < clen; j++){
var v = cells[j].innerHTML;
/* try to guess column type */
var date = v.match(/(\d\d?)\/(\d\d?)\/(\d\d\d\d)/i);
if (date) {
v = new Date();
v.setYear(date[3]);
v.setMonth(date[2]);
v.setDate(date[1]);
} else {
var date = v.match(/(\d\d?)\/(\d\d\d\d)/i);
if (date) {
v = new Date();
v.setYear(date[2]);
v.setMonth(date[1]);
v.setDate(1);
} else {
v = v.match(/\d+/i);
if (v) {
v = parseInt(v);
} else {
v = cells[j].innerHTML;
}
}
}
if (cells[j].innerText == '') {
v = null;
}
/* store both original html and typed value */
arr[i][j] = Array(cells[j].innerHTML, v);
}
}
var first_row = arr.shift(); /* skip first row (header) */
/* sort rows, empty cells last */
arr.sort(function(a, b){
a = a[col][1]; b = b[col][1];
if (a === null && b === null) return 0;
if (a === null) return 1;
if (b === null) return -1;
return (a == b) ? 0 : ((a > b) ? asc : -1*asc);
});
arr.unshift(first_row); /* pub back first row */
/* recreate content */
for (i = 0; i < rlen; i++){
arr[i] = "<td>"+arr[i].map(function(x) {return x[0];}).join("</td><td>")+"</td>";
}
table.innerHTML = "<tr>"+arr.join("</tr><tr>")+"</tr>";
/* set back callback */
$(table).find('tr:first-child td').on('click', sort_table).css('cursor', 'row-resize');
}
$(function() {
$('.wiki table tr:first-child td').on('click', sort_table).css('cursor', 'row-resize');
if ($('.administration').length == 0) {
/* fake access control */
return;