/**
* Set type of table (classname) based on structure.
*
* @param table
*/
export default function Table (table) {
// Only continue if table exist.
if (!table.classList.contains('table')) {
table.classList.add('table');
}
var type = 'default';
if (table.querySelectorAll('thead th').length) {
type = 'stack';
}
switch (type) {
case 'stack':
if (!table.classList.contains('table--stack')) {
table.classList.add('table--stack');
}
initStackTable(table);
break;
}
}
/**
* Initialize stack table.
*
* @param table
*/
function initStackTable (table) {
var headers = table.querySelectorAll('thead th');
if (!headers.length) {
return;
}
// Handle headers
for (var headerIndex = 0; headerIndex < headers.length; headerIndex++) {
headers[headerIndex].setAttribute('scope', 'col');
}
// Handle body
var bodyRows = table.querySelectorAll('tbody tr');
for (var bodyRowIndex = 0; bodyRowIndex < bodyRows.length; bodyRowIndex++) {
var bodyRowCells = bodyRows[bodyRowIndex].getElementsByTagName('td');
for (var bodyCellIndex = 0; bodyCellIndex <
bodyRowCells.length; bodyCellIndex++) {
var bodyCell = bodyRowCells[bodyCellIndex];
var bodyCellContent = bodyCell.innerHTML;
var bodyCellTemplate = '' +
'' + headers[bodyCellIndex].innerHTML +
'' +
'' + bodyCellContent + '';
bodyCell.innerHTML = bodyCellTemplate;
}
}
// Handle footer
var footerCells = table.querySelectorAll('tfoot tr th, tfoot td');
for (var footerCellIndex = 0; footerCellIndex <
footerCells.length; footerCellIndex++) {
var footerCell = footerCells[footerCellIndex];
var footerHeaderCell = footerCells[footerCellIndex - 1];
if (footerCell.tagName === 'TD' && footerHeaderCell &&
footerHeaderCell.tagName === 'TH') {
var footerCellTemplate = '' +
'' +
footerHeaderCell.innerHTML + '' +
'' + footerCell.innerHTML + '';
footerCell.innerHTML = footerCellTemplate;
}
var footerCellContent = footerCell.innerHTML.trim();
if (footerCellContent === '') {
footerCells[footerCellIndex].classList.add('table__empty-cell');
}
}
}