HummingBirdAnimeClient/public/js/src/base/sort_tables.js

69 lines
1.5 KiB
JavaScript
Raw Normal View History

2018-08-10 20:09:28 -04:00
const LightTableSorter = (() => {
let th = null;
let cellIndex = null;
let order = '';
const text = (row) => row.cells.item(cellIndex).textContent.toLowerCase();
2018-08-10 20:09:28 -04:00
const sort = (a, b) => {
let textA = text(a);
let textB = text(b);
const n = parseInt(textA, 10);
2016-02-01 09:49:18 -05:00
if (n) {
textA = n;
textB = parseInt(textB, 10);
}
if (textA > textB) {
return 1;
}
if (textA < textB) {
return -1;
}
return 0;
};
2018-08-10 20:09:28 -04:00
const toggle = () => {
const c = order !== 'sorting-asc' ? 'sorting-asc' : 'sorting-desc';
2018-08-10 20:09:28 -04:00
th.className = (th.className.replace(order, '') + ' ' + c).trim();
return order = c;
2016-02-01 09:49:18 -05:00
};
2018-08-10 20:09:28 -04:00
const reset = () => {
th.classList.remove('sorting-asc', 'sorting-desc');
2018-08-10 20:09:28 -04:00
th.classList.add('sorting');
return order = '';
2016-02-01 09:49:18 -05:00
};
2018-08-10 20:09:28 -04:00
const onClickEvent = (e) => {
if (th && (cellIndex !== e.target.cellIndex)) {
reset();
2016-02-01 09:49:18 -05:00
}
2018-08-10 20:09:28 -04:00
th = e.target;
if (th.nodeName.toLowerCase() === 'th') {
cellIndex = th.cellIndex;
const tbody = th.offsetParent.getElementsByTagName('tbody')[0];
let rows = Array.from(tbody.rows);
2016-02-01 09:49:18 -05:00
if (rows) {
2018-08-10 20:09:28 -04:00
rows.sort(sort);
if (order === 'sorting-asc') {
2018-08-10 20:09:28 -04:00
rows.reverse();
2016-02-01 09:49:18 -05:00
}
2018-08-10 20:09:28 -04:00
toggle();
2016-02-01 09:49:18 -05:00
tbody.innerHtml = '';
2018-08-10 20:09:28 -04:00
rows.forEach(row => {
2016-02-01 09:49:18 -05:00
tbody.appendChild(row);
2018-08-10 20:09:28 -04:00
});
2016-02-01 09:49:18 -05:00
}
}
};
return {
2018-08-10 20:09:28 -04:00
init: () => {
2016-02-01 09:49:18 -05:00
let ths = document.getElementsByTagName('th');
2018-08-10 20:09:28 -04:00
let results = [];
for (let i = 0, len = ths.length; i < len; i++) {
let th = ths[i];
th.classList.add('sorting');
results.push(th.onclick = onClickEvent);
2016-02-01 09:49:18 -05:00
}
2018-08-10 20:09:28 -04:00
return results;
2016-02-01 09:49:18 -05:00
}
};
})();
2016-02-01 09:49:18 -05:00
LightTableSorter.init();