2018-08-10 20:09:28 -04:00
|
|
|
const LightTableSorter = (() => {
|
|
|
|
let th = null;
|
|
|
|
let cellIndex = null;
|
|
|
|
let order = '';
|
2018-08-22 12:54:06 -04:00
|
|
|
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 = () => {
|
2018-11-02 10:48:20 -04:00
|
|
|
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 = () => {
|
2018-11-02 10:48:20 -04:00
|
|
|
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);
|
2018-11-02 10:48:20 -04:00
|
|
|
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-01-20 13:01:41 -05:00
|
|
|
|
2016-02-01 09:49:18 -05:00
|
|
|
LightTableSorter.init();
|