Files
sage-home/components/mdx/TableOfContents.client.tsx

104 lines
2.9 KiB
TypeScript
Raw Normal View History

2026-01-24 16:54:44 +08:00
// components/mdx/TableOfContents.client.tsx
"use client";
import { useEffect, useState } from 'react';
interface TableOfContentsItem {
id: string;
text: string;
level: number;
}
interface TableOfContentsProps {
items: TableOfContentsItem[];
title?: string;
}
export default function TableOfContents({
items = [],
title = "目录"
}: TableOfContentsProps) {
const [activeId, setActiveId] = useState<string>("");
useEffect(() => {
if (items.length === 0) return;
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setActiveId(entry.target.id);
}
});
},
{ rootMargin: "0% 0% -80% 0%" }
);
// 观察所有标题元素
items.forEach((item) => {
const element = document.getElementById(item.id);
if (element) {
observer.observe(element);
}
});
return () => {
items.forEach((item) => {
const element = document.getElementById(item.id);
if (element) {
observer.unobserve(element);
}
});
};
}, [items]);
const handleClick = (e: React.MouseEvent, id: string) => {
e.preventDefault();
const element = document.getElementById(id);
if (element) {
element.scrollIntoView({ behavior: "smooth" });
window.history.pushState(null, "", `#${id}`);
setActiveId(id);
}
};
if (!items || items.length === 0) {
return null;
}
return (
<aside className="fixed left-0 top-0 w-64 h-screen border-r border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 z-10 overflow-y-auto">
<div className="p-6">
<h3 className="text-lg font-semibold mb-4 text-gray-800 dark:text-gray-200">
{title}
</h3>
<nav>
<ul className="space-y-2 border-l-2 border-gray-200 dark:border-gray-700">
{items.map((item) => {
const isActive = activeId === item.id;
return (
<li
key={item.id}
style={{ marginLeft: `${(item.level - 2) * 0.75}rem` }}
className={`text-sm border-l-2 -ml-0.5 pl-4 transition-colors duration-200 ${isActive
? "border-blue-500 text-blue-600 dark:text-blue-400 font-medium"
: "border-transparent hover:border-blue-400"
} hover:text-blue-600 dark:hover:text-blue-400 cursor-pointer`}
>
<a
href={`#${item.id}`}
className={`block py-1 transition-all duration-200 ${isActive ? "translate-x-1" : "hover:translate-x-1"
}`}
onClick={(e) => handleClick(e, item.id)}
>
{item.text}
</a>
</li>
);
})}
</ul>
</nav>
</div>
</aside>
);
}