Skip to content

Commit 34a6f60

Browse files
committed
scroll state
1 parent fa1fcee commit 34a6f60

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

astro.config.mjs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,15 @@ export default defineConfig({
99
integrations: [
1010
starlight({
1111
title: "Ecency",
12+
head: [
13+
{
14+
tag: "script",
15+
attrs: {
16+
src: "/sidebar-scroll.js",
17+
type: "module",
18+
},
19+
},
20+
],
1221
social: {
1322
github: "https://github.com/ecency",
1423
},

public/sidebar-scroll.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
(() => {
2+
const storageKey = 'sl-sidebar-state';
3+
4+
const shouldRestoreFromStorage = (sidebar) => {
5+
const persistTarget = sidebar.querySelector('sl-sidebar-state-persist');
6+
const hash = persistTarget?.dataset.hash;
7+
8+
try {
9+
const storedState = JSON.parse(sessionStorage.getItem(storageKey) || 'null');
10+
return Boolean(hash && storedState?.hash === hash && typeof storedState.scroll === 'number');
11+
} catch {
12+
return false;
13+
}
14+
};
15+
16+
const scrollCurrentSidebarLinkIntoView = () => {
17+
const sidebar = document.getElementById('starlight__sidebar');
18+
if (!sidebar || shouldRestoreFromStorage(sidebar)) return;
19+
20+
const activeLink = sidebar.querySelector("a[aria-current='page']");
21+
if (!activeLink) return;
22+
23+
const sidebarRect = sidebar.getBoundingClientRect();
24+
const linkRect = activeLink.getBoundingClientRect();
25+
const linkOffset = linkRect.top - sidebarRect.top + sidebar.scrollTop;
26+
const targetTop = Math.max(linkOffset - sidebar.clientHeight / 2 + linkRect.height / 2, 0);
27+
28+
sidebar.scrollTo({ top: targetTop, behavior: 'auto' });
29+
};
30+
31+
if (document.readyState === 'complete' || document.readyState === 'interactive') {
32+
scrollCurrentSidebarLinkIntoView();
33+
} else {
34+
window.addEventListener('DOMContentLoaded', scrollCurrentSidebarLinkIntoView, { once: true });
35+
}
36+
})();

0 commit comments

Comments
 (0)