Skip to content

Commit

Permalink
fix: active position for toc scrolling highlight (#2030)
Browse files Browse the repository at this point in the history
* fix: sidebar激活的锚点不对bug

* Update .npmrc

---------

Co-authored-by: Peach <scdzwyxst@gmail.com>
  • Loading branch information
Zhou-Bill and PeachScript committed Apr 29, 2024
1 parent 1360754 commit dbb278a
Showing 1 changed file with 12 additions and 1 deletion.
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

0 comments on commit dbb278a

Please sign in to comment.