1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
/**
* This class is used to enhance sortable tables in Stud.IP by using the
* tablesorter plugin.
*
* @see https://mottie.github.io/tablesorter/docs/
*/
class Table
{
/**
* This method will make the given sortable. The table my be given as a
* DOM element or wrapped in a jQuery object.
*
* Additional widgets for the tablesorter may be passed as an array via
* the attribute [data-sort-widgets].
* (see https://mottie.github.io/tablesorter/docs/example-widgets.html)
*
* @param table
*/
static async enhanceSortableTable(table)
{
// Unjquerify table
if (table instanceof jQuery) {
table = table.get(0);
}
// Failproof
if (!table) {
console.error('Called enhanceSortableTable with invalid table object');
return;
}
await STUDIP.loadChunk('tablesorter');
// Iterate over the header columns and determine sorting mechanism
let headers = {};
$('thead tr:last th', table).each((index, element) => {
headers[index] = {
sorter: element.dataset.sort ?? false
};
});
// Handle potential fixed rows
if ($('tbody tr[data-sort-fixed]', table).length > 0) {
$('tbody tr[data-sort-fixed]', table).each(function () {
$(this).data('sort-fixed', {
index: $(this).index(),
tbody: $(this).closest('table').find('tbody').index($(this).parent())
});
});
$(table).on('sortStart', () => {
$('tbody tr[data-sort-fixed]', table).each(function () {
const hidden = $(this).is(':hidden');
$(this).data('sort-hidden', hidden);
});
}).on('sortEnd', () => {
$('tbody tr[data-sort-fixed]', table).detach().each(function () {
const pos = $(this).data('sort-fixed');
if ($(`tbody:eq(${pos.tbody}) tr:eq(${pos.index})`, table).length > 0) {
$(`tbody:eq(${pos.tbody}) tr:eq(${pos.index})`, table).before(this);
} else {
$(`tbody:eq(${pos.tbody})`, table).append(this);
}
if ($(this).data('sort-hidden')) {
setTimeout(() => $(this).hide(), 100);
}
});
});
}
// Get additional widgets
const widgets = table.dataset.sortWidgets ?? [];
// Actually activate table sorter
$(table).tablesorter({
headers: headers,
sortLocaleCompare : true,
sortRestart: true,
widthFixed: false,
widgets: Array.isArray(widgets) ? widgets : []
});
}
}
export default Table;
|