|
1 | 1 | 'use client';
|
2 | 2 | import {useEffect} from 'react';
|
3 | 3 |
|
| 4 | +import {debounce} from 'sentry-docs/utils'; |
| 5 | + |
4 | 6 | type Props = {
|
5 | 7 | activeLinkSelector: string;
|
6 | 8 | };
|
7 | 9 |
|
8 | 10 | /** Make sure the active link is visible in the sidebar */
|
9 | 11 | export function ScrollActiveLink({activeLinkSelector}: Props) {
|
10 |
| - const isVsibible = (link: Element) => { |
11 |
| - const rect = link.getBoundingClientRect(); |
12 |
| - return rect.top >= 0 && rect.bottom <= window.innerHeight; |
13 |
| - }; |
| 12 | + useEffect(() => { |
| 13 | + const sidebar = document.querySelector('[data-sidebar-link]')?.closest('aside'); |
| 14 | + if (!sidebar) { |
| 15 | + return; |
| 16 | + } |
| 17 | + sidebar.addEventListener('click', e => { |
| 18 | + const target = e.target as HTMLElement; |
| 19 | + if (target.hasAttribute('data-sidebar-link')) { |
| 20 | + const top = target.getBoundingClientRect().top; |
| 21 | + sessionStorage.setItem('sidebar-link-poisition', top.toString()); |
| 22 | + } |
| 23 | + }); |
| 24 | + // track active link position on scroll as well |
| 25 | + sidebar.addEventListener( |
| 26 | + 'scroll', |
| 27 | + debounce(() => { |
| 28 | + const activeLink = document.querySelector(activeLinkSelector); |
| 29 | + if (activeLink) { |
| 30 | + const top = activeLink.getBoundingClientRect().top.toString(); |
| 31 | + sessionStorage.setItem('sidebar-link-poisition', top); |
| 32 | + } |
| 33 | + }, 50) |
| 34 | + ); |
| 35 | + }, [activeLinkSelector]); |
14 | 36 |
|
15 | 37 | useEffect(() => {
|
16 | 38 | const activeLink = document.querySelector(activeLinkSelector);
|
17 |
| - if (activeLink && !isVsibible(activeLink)) { |
18 |
| - // try to center the active link in the sidebar |
19 |
| - activeLink.scrollIntoView({block: 'center', behavior: 'smooth'}); |
| 39 | + const sidebar = activeLink?.closest('aside')!; |
| 40 | + if (!activeLink || !sidebar) { |
| 41 | + return; |
| 42 | + } |
| 43 | + const previousBoundingRectTop = sessionStorage.getItem('sidebar-link-poisition'); |
| 44 | + const currentBoundingRectTop = activeLink.getBoundingClientRect().top; |
| 45 | + // scroll the sidebar to make sure the active link is visible & has the same position as when it was clicked |
| 46 | + if (!previousBoundingRectTop) { |
| 47 | + return; |
20 | 48 | }
|
| 49 | + const scrollX = 0; |
| 50 | + const scrollY = sidebar.scrollTop + currentBoundingRectTop - +previousBoundingRectTop; |
| 51 | + sidebar?.scrollTo(scrollX, scrollY); |
21 | 52 | }, [activeLinkSelector]);
|
22 | 53 | // don't render anything, just exist as a client-side component for the useEffect.
|
23 | 54 | return null;
|
|
0 commit comments