Skip to content

Commit 45e2158

Browse files
authored
Merge pull request #2982 from ehuss/fix-sidebar-scroll
Fix sidebar scroll position when heading nav is involved
2 parents f857ab2 + 59017ea commit 45e2158

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)