@ussebastian/kitdigital
Version:
Kit Digital de la Universidad San Sebastián
118 lines (96 loc) • 2.67 kB
JavaScript
export class Tabs {
constructor(element, key) {
this.key = key;
this.element = element;
this.tablistNode = null;
this.tabs = [];
this.tabpanels = [];
this.firstTab = null;
this.lastTab = null;
}
mount() {
this.tablistNode = this.element;
this.tabs = Array.from(this.tablistNode.querySelectorAll('.uss-tabs__tab'));
this.tabpanels = [];
for (let i = 0; i < this.tabs.length; i += 1) {
const tab = this.tabs[i];
const tabpanel = document.getElementById(tab.getAttribute('aria-controls'));
tab.tabIndex = -1;
tab.setAttribute('aria-selected', 'false');
this.tabpanels.push(tabpanel);
tab.addEventListener('keydown', this.onKeydown.bind(this));
tab.addEventListener('click', this.onClick.bind(this));
if (!this.firstTab) {
this.firstTab = tab;
}
this.lastTab = tab;
}
this.setSelectedTab(this.firstTab);
}
setSelectedTab(currentTab) {
for (let i = 0; i < this.tabs.length; i += 1) {
const tab = this.tabs[i];
if (currentTab === tab) {
tab.setAttribute('aria-selected', 'true');
tab.removeAttribute('tabindex');
this.tabpanels[i].classList.remove('is-hidden');
} else {
tab.setAttribute('aria-selected', 'false');
tab.tabIndex = -1;
this.tabpanels[i].classList.add('is-hidden');
}
}
}
moveFocusToPreviousTab(currentTab) {
let index;
if (currentTab === this.firstTab) {
this.lastTab.focus();
} else {
index = this.tabs.indexOf(currentTab);
this.tabs[index - 1].focus();
}
}
moveFocusToNextTab(currentTab) {
let index;
if (currentTab === this.lastTab) {
this.firstTab.focus();
} else {
index = this.tabs.indexOf(currentTab);
this.tabs[index + 1].focus();
}
}
/* EVENT HANDLERS */
onKeydown(event) {
const tgt = event.currentTarget;
let flag = false;
switch (event.key) {
case 'ArrowLeft':
this.moveFocusToPreviousTab(tgt);
flag = true;
break;
case 'ArrowRight':
this.moveFocusToNextTab(tgt);
flag = true;
break;
case 'Home':
this.firstTab.focus();
flag = true;
break;
case 'End':
this.lastTab.focus();
flag = true;
break;
default:
break;
}
if (flag) {
event.stopPropagation();
event.preventDefault();
}
}
// Since this example uses buttons for the tabs, the click onr also is activated
// with the space and enter keys
onClick(event) {
this.setSelectedTab(event.currentTarget);
}
}