diff --git a/assets/js/sidebar.js b/assets/js/sidebar.js index 65f7b15f..58f032bd 100644 --- a/assets/js/sidebar.js +++ b/assets/js/sidebar.js @@ -1,8 +1,20 @@ document.addEventListener("DOMContentLoaded", function () { - scrollToActiveItem(); + restoreSidebarPosition(); enableCollapsibles(); }); +function debounce(func, wait) { + let timeout; + return function executedFunction(...args) { + const later = () => { + clearTimeout(timeout); + func(...args); + }; + clearTimeout(timeout); + timeout = setTimeout(later, wait); + }; +} + function enableCollapsibles() { const buttons = document.querySelectorAll(".hextra-sidebar-collapsible-button"); buttons.forEach(function (button) { @@ -16,21 +28,31 @@ function enableCollapsibles() { }); } -function scrollToActiveItem() { +function saveSidebarPosition(scrollPosition) { + const currentPosition = sessionStorage.getItem('sidebarScrollPosition'); + if (currentPosition === null || parseInt(currentPosition) !== scrollPosition) { + sessionStorage.setItem('sidebarScrollPosition', scrollPosition); + } +} + +function restoreSidebarPosition() { 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 (sidebarScrollbar) { + const savedPosition = sessionStorage.getItem('sidebarScrollPosition'); + + if (savedPosition !== null) { + sidebarScrollbar.scrollTo({ + top: parseInt(savedPosition), + behavior: 'instant' + }); + } - if (!visibleActiveItem) { - return; + const debouncedSave = debounce((position) => { + saveSidebarPosition(position); + }, 150); + + sidebarScrollbar.addEventListener('scroll', function() { + debouncedSave(this.scrollTop); + }); } - - const yOffset = visibleActiveItem.clientHeight; - const yDistance = visibleActiveItem.getBoundingClientRect().top - sidebarScrollbar.getBoundingClientRect().top; - sidebarScrollbar.scrollTo({ - behavior: "instant", - top: yDistance - yOffset - }); -} +} \ No newline at end of file