Skip to content

Commit 59017ea

Browse files
committed
Fix sidebar scroll position when heading nav is involved
This fixes an issue where the sidebar was scrolling incorrectly when clicking on chapters when a heading nav is currently in view. The problem was that it was storing the scrollTop of the sidebar, but it was not considering that when navigating to another chapter that the heading nav of the previous chapter would disappear. The solution is to keep of an offset instead so that it can make sure that the vertical position of the clicked chapter stays in the same relative position when the new page loads. Fixes #2967
1 parent 6457b38 commit 59017ea

File tree

104 files changed

+339
-5
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

104 files changed

+339
-5
lines changed

crates/mdbook-html/front-end/templates/toc.js.hbs

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,14 +40,22 @@ class MDBookSidebarScrollbox extends HTMLElement {
4040
// Track and set sidebar scroll position
4141
this.addEventListener('click', e => {
4242
if (e.target.tagName === 'A') {
43-
sessionStorage.setItem('sidebar-scroll', this.scrollTop);
43+
const clientRect = e.target.getBoundingClientRect();
44+
const sidebarRect = this.getBoundingClientRect();
45+
sessionStorage.setItem('sidebar-scroll-offset', clientRect.top - sidebarRect.top);
4446
}
4547
}, { passive: true });
46-
const sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
47-
sessionStorage.removeItem('sidebar-scroll');
48-
if (sidebarScrollTop) {
48+
const sidebarScrollOffset = sessionStorage.getItem('sidebar-scroll-offset');
49+
sessionStorage.removeItem('sidebar-scroll-offset');
50+
if (sidebarScrollOffset !== null) {
4951
// preserve sidebar scroll position when navigating via links within sidebar
50-
this.scrollTop = sidebarScrollTop;
52+
const activeSection = this.querySelector('.active');
53+
if (activeSection) {
54+
const clientRect = activeSection.getBoundingClientRect();
55+
const sidebarRect = this.getBoundingClientRect();
56+
const currentOffset = clientRect.top - sidebarRect.top;
57+
this.scrollTop += currentOffset - parseFloat(sidebarScrollOffset);
58+
}
5159
} else {
5260
// scroll sidebar to current active section when navigating via
5361
// 'next/previous chapter' buttons
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
[book]
2+
title = "sidebar-scroll"
3+
language = "en"
Lines changed: 102 additions & 0 deletions
Lines changed: 3 additions & 0 deletions
Lines changed: 28 additions & 0 deletions
Lines changed: 1 addition & 0 deletions
Lines changed: 1 addition & 0 deletions
Lines changed: 1 addition & 0 deletions
Lines changed: 1 addition & 0 deletions
Lines changed: 1 addition & 0 deletions

0 commit comments

Comments
 (0)