diff --git a/src/components/site/PostToc.tsx b/src/components/site/PostToc.tsx index ecf41f6c..20ce643b 100644 --- a/src/components/site/PostToc.tsx +++ b/src/components/site/PostToc.tsx @@ -2,6 +2,52 @@ import React, { useEffect, useState, useRef } from "react" import type { Result as TocResult } from "mdast-util-toc" import { Link } from "react-scroll" +function getIds(items: TocResult["map"]) { + return ( + items?.children?.reduce((acc: string[], item) => { + item.children.forEach((child) => { + if (child.type === "paragraph" && (child.children[0] as any).url) { + acc.push((child.children[0] as any).url.slice(1)) + } else if (child.type === "list") { + acc.push(...getIds(child)) + } + }) + return acc + }, []) || [] + ) +} + +function useActiveId(itemIds: string[]) { + const [activeId, setActiveId] = useState(`test`) + useEffect(() => { + const observer = new IntersectionObserver( + (entries) => { + entries.forEach((entry) => { + if (entry.isIntersecting) { + setActiveId(entry.target.id) + } + }) + }, + { rootMargin: `0% 0% -80% 0%` }, + ) + itemIds.forEach((id) => { + const element = document.getElementById(id) + if (element) { + observer.observe(element) + } + }) + return () => { + itemIds.forEach((id) => { + const element = document.getElementById(id) + if (element) { + observer.unobserve(element) + } + }) + } + }, [itemIds]) + return activeId +} + function renderItems(items: TocResult["map"], activeId: string, prefix = "") { return (