2024-06-29 20:52:45 +00:00
|
|
|
function initTabs(container, {
|
|
|
|
initialTab = null,
|
|
|
|
onSelect = (name) => {},
|
|
|
|
}) {
|
2024-06-24 18:36:50 +00:00
|
|
|
const buttons = Array.from(container.querySelectorAll("[data-tab-button]"));
|
|
|
|
const tabs = Array.from(container.querySelectorAll("[data-tab]"));
|
2021-08-27 17:58:52 +00:00
|
|
|
|
2024-06-29 20:52:45 +00:00
|
|
|
const firstTab = tabs[0].getAttribute("data-tab");
|
|
|
|
|
|
|
|
function selectTab(name, { sendEvent = true } = {}) {
|
|
|
|
if (!document.querySelector(`[data-tab="${name}"]`)) {
|
|
|
|
console.warn("no tab found with name", name);
|
|
|
|
return selectTab(firstTab, initial);
|
|
|
|
}
|
2021-08-27 17:58:52 +00:00
|
|
|
|
2024-06-24 18:36:50 +00:00
|
|
|
for (const tab of tabs) {
|
|
|
|
tab.hidden = tab.getAttribute("data-tab") !== name;
|
|
|
|
}
|
|
|
|
for (const button of buttons) {
|
|
|
|
button.classList.toggle("tab-button-active", button.getAttribute("data-tab-button") === name);
|
2021-08-27 17:58:52 +00:00
|
|
|
}
|
2024-06-29 20:52:45 +00:00
|
|
|
|
|
|
|
if (sendEvent) {
|
|
|
|
onSelect(name);
|
|
|
|
}
|
2021-08-27 17:58:52 +00:00
|
|
|
}
|
2024-06-29 20:52:45 +00:00
|
|
|
selectTab(initialTab || firstTab, { sendEvent: false });
|
2021-08-27 17:58:52 +00:00
|
|
|
|
2024-06-24 18:36:50 +00:00
|
|
|
for (const button of buttons) {
|
|
|
|
button.addEventListener("click", () => {
|
2024-06-29 20:52:45 +00:00
|
|
|
selectTab(button.getAttribute("data-tab-button"));
|
2024-06-24 18:36:50 +00:00
|
|
|
});
|
2021-08-27 17:58:52 +00:00
|
|
|
}
|
2024-06-29 20:52:45 +00:00
|
|
|
|
|
|
|
return {
|
|
|
|
selectTab,
|
|
|
|
};
|
2021-11-25 03:59:51 +00:00
|
|
|
}
|