2018-08-10 20:09:28 -04:00
|
|
|
'use strict';
|
|
|
|
const LightTableSorter = (() => {
|
|
|
|
let th = null;
|
|
|
|
let cellIndex = null;
|
|
|
|
let order = '';
|
|
|
|
const text = (row) => {
|
|
|
|
return row.cells.item(cellIndex).textContent.toLowerCase();
|
2016-02-01 09:49:18 -05:00
|
|
|
};
|
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';
|
|
|
|
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');
|
|
|
|
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') {
|
|
|
|
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();
|