diff --git a/components/Sidebar/index.jsx b/components/Sidebar/index.jsx index 3eb0c6a..23fa99c 100644 --- a/components/Sidebar/index.jsx +++ b/components/Sidebar/index.jsx @@ -1,3 +1,4 @@ +import { useLayoutEffect } from 'react'; import SideBar from '@node-core/ui-components/Containers/Sidebar'; import withIsland from '@doc-kit/generator-react/html/ui/islands/withIsland.jsx'; import { sidebar } from '../../site.json' with { type: 'json' }; @@ -16,14 +17,47 @@ const PrefetchLink = props => ; * * @param {{ pathname: string }} props */ -const Sidebar = ({ pathname }) => ( - -); - -export default withIsland(Sidebar, { name: 'Sidebar', on: { idle: true } }); +const Sidebar = ({ pathname }) => { + // Each navigation is a full page load, so the sidebar always starts at the + // top. Scroll the active link into view (stateless, no storage needed). + useLayoutEffect(() => { + const active = document.querySelector(`aside a[href="${pathname}"]`); + const aside = active?.closest('aside'); + const scroller = + aside && aside.scrollHeight > aside.clientHeight + ? aside + : aside?.parentElement; + + if ( + !scroller || + !active || + scroller.scrollHeight <= scroller.clientHeight + ) { + return; + } + + const scrollerRect = scroller.getBoundingClientRect(); + const activeRect = active.getBoundingClientRect(); + + // Only scroll if the active link is outside the visible area + if ( + activeRect.top < scrollerRect.top || + activeRect.bottom > scrollerRect.bottom + ) { + scroller.scrollTop += + activeRect.top - scrollerRect.top - scroller.clientHeight / 2; + } + }, [pathname]); + + return ( + + ); +}; + +export default withIsland(Sidebar, { name: 'SideBar', on: { idle: true } }); diff --git a/doc-kit.config.mjs b/doc-kit.config.mjs index f705389..dfed01c 100644 --- a/doc-kit.config.mjs +++ b/doc-kit.config.mjs @@ -45,7 +45,7 @@ export default { // Registers the components as islands, so they hydrate client-side components: { Authors: join(import.meta.dirname, 'components/Authors/index.jsx'), - Sidebar: join(import.meta.dirname, 'components/Sidebar/index.jsx'), + SideBar: join(import.meta.dirname, 'components/Sidebar/index.jsx'), }, // Imports diff --git a/tests/e2e/interactions.spec.mjs b/tests/e2e/interactions.spec.mjs index 74c1a5f..8c0d377 100644 --- a/tests/e2e/interactions.spec.mjs +++ b/tests/e2e/interactions.spec.mjs @@ -168,7 +168,7 @@ test.describe('Small screens', () => { await page.goto('/learn/getting-started/fetch'); // The sidebar collapses into a dropdown that only works once hydrated. - await waitForIsland(page, 'Sidebar'); + await waitForIsland(page, 'SideBar'); await page.getByRole('combobox', { name: 'Navigation' }).click(); // Radix ignores a selection made in the first moments after the list