51 lines
1.5 KiB
JavaScript
51 lines
1.5 KiB
JavaScript
// Generic tab navigation handler
|
|
// Manages active tab styling after HTMX content swaps.
|
|
//
|
|
// Usage: Add data-tab-nav="<content-target-id>" to your <nav> element.
|
|
// Tab links inside the nav should have href attributes ending with the section name.
|
|
//
|
|
// Example:
|
|
// <nav data-tab-nav="admin-content">
|
|
// <a href="/admin/users" hx-post="/admin/users" hx-target="#admin-content">Users</a>
|
|
// </nav>
|
|
// <main id="admin-content">...</main>
|
|
|
|
(function () {
|
|
var activeClasses = ["border-blue", "text-blue", "font-semibold"];
|
|
var inactiveClasses = [
|
|
"border-transparent",
|
|
"text-subtext0",
|
|
"hover:text-text",
|
|
"hover:border-surface2",
|
|
];
|
|
|
|
function updateActiveTab(targetId) {
|
|
var nav = document.querySelector('[data-tab-nav="' + targetId + '"]');
|
|
if (!nav) return;
|
|
|
|
var path = window.location.pathname;
|
|
var section = path.split("/").pop() || "";
|
|
|
|
nav.querySelectorAll("a").forEach(function (link) {
|
|
var href = link.getAttribute("href");
|
|
var isActive = href && href.endsWith("/" + section);
|
|
|
|
activeClasses.forEach(function (cls) {
|
|
isActive ? link.classList.add(cls) : link.classList.remove(cls);
|
|
});
|
|
inactiveClasses.forEach(function (cls) {
|
|
isActive ? link.classList.remove(cls) : link.classList.add(cls);
|
|
});
|
|
});
|
|
}
|
|
|
|
document.addEventListener("DOMContentLoaded", function () {
|
|
document.body.addEventListener("htmx:afterSwap", function (event) {
|
|
var targetId = event.detail.target.id;
|
|
if (targetId) {
|
|
updateActiveTab(targetId);
|
|
}
|
|
});
|
|
});
|
|
})();
|