imfing / hextra

🔯 Modern, batteries-included Hugo theme for creating beautiful doc, blog and static websites
https://imfing.github.io/hextra/
MIT License
699 stars 165 forks source link

Make selected entry in sidebar always visible, same problem like issues#395 #490

Open xue68 opened 2 days ago

xue68 commented 2 days ago

Feature Description

Make selected entry in sidebar always visible. same problem like #395. I want to try a new solution below. The old solution pr#471 always put the active item in the top of the sidebar list. When I merged the pr, I found it looks like strange. After I saw the solution of vitpress, I think saving the bar position is better.

Problem/Solution

This is the new sidebar.js

document.addEventListener("DOMContentLoaded", function () {
  restoreSidebarPosition();
  enableCollapsibles();
});

function enableCollapsibles() {
  const buttons = document.querySelectorAll(".hextra-sidebar-collapsible-button");
  buttons.forEach(function (button) {
    button.addEventListener("click", function (e) {
      e.preventDefault();
      const list = button.parentElement.parentElement;
      if (list) {
        list.classList.toggle("open")
      }
    });
  });
}

function saveSidebarPosition() {
  const sidebarScrollbar = document.querySelector("aside.sidebar-container > .hextra-scrollbar");
  if (sidebarScrollbar) {
    const scrollPosition = sidebarScrollbar.scrollTop;
    sessionStorage.setItem('sidebarScrollPosition', scrollPosition);
  }
}

function restoreSidebarPosition() {
  const sidebarScrollbar = document.querySelector("aside.sidebar-container > .hextra-scrollbar");
  if (sidebarScrollbar) {
    const savedPosition = sessionStorage.getItem('sidebarScrollPosition');

    if (savedPosition !== null) {
      sidebarScrollbar.scrollTo({
        top: parseInt(savedPosition),
        behavior: 'instant'
      });
    }

    sidebarScrollbar.addEventListener('scroll', function() {
      saveSidebarPosition();
    });
  }
}

Alternatives Considered

null

Additional Context

There may be a lot of problems with this place, please advise.

imfing commented 2 days ago

Hi @xue68 thank you for the feedback. Would you mind opening a pull request so we can preview the above changes you proposed

xue68 commented 2 days ago

ok, the new pr #492 has been commit.