Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: active position for toc scrolling highlight #2030

Merged
merged 2 commits into from
Apr 29, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 12 additions & 1 deletion src/client/theme-default/slots/Toc/index.tsx
Expand Up @@ -23,6 +23,8 @@ const Toc: FC = () => {
const { loading } = useSiteData();
const prevIndexRef = useRef(0);
const [sectionRefs, setSectionRefs] = useState<RefObject<HTMLElement>[]>([]);
const [headerHeight, setHeaderHeight] = useState(0);

const memoToc = React.useMemo(() => {
let toc = meta.toc;
if (tabMeta) {
Expand All @@ -44,8 +46,17 @@ const Toc: FC = () => {
}
}, [pathname, search, loading, memoToc]);

useEffect(() => {
if (sectionRefs.length > 0) {
// find the header height, and set it to scrollspy offset
// because the header is sticky, so we need to set the offset to avoid the active item is hidden by the header
const header = document.querySelector('.dumi-default-header');
setHeaderHeight(header ? header.clientHeight : 0);
}
}, [sectionRefs]);

return sectionRefs.length ? (
<ScrollSpy sectionRefs={sectionRefs}>
<ScrollSpy sectionRefs={sectionRefs} offset={-headerHeight}>
{({ currentElementIndexInViewport }) => {
// for keep prev item active when no item in viewport
if (currentElementIndexInViewport > -1)
Expand Down