From 97ea67198b2f5439b5ba727e831ea4f7d30a0df2 Mon Sep 17 00:00:00 2001 From: yuri <1969yuri1969@gmail.com> Date: Sat, 12 Oct 2024 20:55:39 +0200 Subject: [PATCH] feat: scroll selected sidebar entry into view (#471) Long sidebars did not scroll to show the selected entry. This made working with such long sidebars quite confusing. --- assets/js/sidebar.js | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/assets/js/sidebar.js b/assets/js/sidebar.js index 3b10eb49..65f7b15f 100644 --- a/assets/js/sidebar.js +++ b/assets/js/sidebar.js @@ -1,4 +1,9 @@ document.addEventListener("DOMContentLoaded", function () { + scrollToActiveItem(); + enableCollapsibles(); +}); + +function enableCollapsibles() { const buttons = document.querySelectorAll(".hextra-sidebar-collapsible-button"); buttons.forEach(function (button) { button.addEventListener("click", function (e) { @@ -9,4 +14,23 @@ document.addEventListener("DOMContentLoaded", function () { } }); }); -}); +} + +function scrollToActiveItem() { + const sidebarScrollbar = document.querySelector("aside.sidebar-container > .hextra-scrollbar"); + const activeItems = document.querySelectorAll(".sidebar-active-item"); + const visibleActiveItem = Array.from(activeItems).find(function (activeItem) { + return activeItem.getBoundingClientRect().height > 0; + }); + + if (!visibleActiveItem) { + return; + } + + const yOffset = visibleActiveItem.clientHeight; + const yDistance = visibleActiveItem.getBoundingClientRect().top - sidebarScrollbar.getBoundingClientRect().top; + sidebarScrollbar.scrollTo({ + behavior: "instant", + top: yDistance - yOffset + }); +}