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 (
    @@ -17,6 +63,12 @@ function renderItems(items: TocResult["map"], activeId: string, prefix = "") { duration={500} offset={-20} href={child.children[0].url} + className={ + (activeId === child.children[0].url.slice(1) + ? "text-accent" + : "text-zinc-700") + + " truncate inline-block max-w-full align-bottom hover:text-accent" + } > {`${prefix}${index + 1}. ${ child.children[0].children?.[0]?.value @@ -50,6 +102,9 @@ export const PostToc: React.FC<{ } }, [containerRef]) + const idList = getIds(data?.map) + const activeId = useActiveId(idList) + return (
    - {renderItems(data?.map, "activeId")} + {renderItems(data?.map, activeId)}
    ) diff --git a/src/css/prose.css b/src/css/prose.css index 9ee462c8..ce836462 100644 --- a/src/css/prose.css +++ b/src/css/prose.css @@ -155,7 +155,3 @@ .prose .code-wrapper:hover .copy-button { @apply inline-flex; } - -.xlog-post-toc a { - @apply truncate inline-block max-w-full align-bottom text-zinc-700 hover:text-accent-dark; -}