refactor: toc toggle

This commit is contained in:
hypercross 2026-03-25 10:26:06 +08:00
parent 32e91f7dc8
commit 3aaa991bd8
1 changed files with 14 additions and 3 deletions

View File

@ -83,9 +83,15 @@ export const HeadingNode: Component<{
const navigate = useNavigate(); const navigate = useNavigate();
const anchor = props.node.id || ""; const anchor = props.node.id || "";
const href = `${props.basePath}#${anchor}`; const href = `${props.basePath}#${anchor}`;
const hasChildren = !!props.node.children;
// 默认收起,除非当前锚点在该节点内
const [isExpanded, setIsExpanded] = createSignal(false);
const handleClick = (e: MouseEvent) => { const handleClick = (e: MouseEvent) => {
e.preventDefault(); e.preventDefault();
if (hasChildren) {
setIsExpanded(!isExpanded());
}
navigate(href); navigate(href);
// 滚动到目标元素,考虑导航栏高度偏移 // 滚动到目标元素,考虑导航栏高度偏移
requestAnimationFrame(() => { requestAnimationFrame(() => {
@ -105,13 +111,18 @@ export const HeadingNode: Component<{
<div> <div>
<a <a
href={href} href={href}
class="block py-0.5 px-2 text-sm text-gray-600 hover:text-gray-900 hover:bg-gray-50 rounded truncate" class="flex items-center py-0.5 px-2 text-sm text-gray-600 hover:text-gray-900 hover:bg-gray-50 rounded truncate cursor-pointer"
style={{ "padding-left": `${indent + 8}px` }} style={{ "padding-left": `${indent + 8}px` }}
onClick={handleClick} onClick={handleClick}
> >
{props.node.title} <Show when={hasChildren}>
<span class="mr-1 text-gray-400 text-xs w-3 flex-shrink-0">
{isExpanded() ? "▼" : "▶"}
</span>
</Show>
<span class="truncate">{props.node.title}</span>
</a> </a>
<Show when={props.node.children}> <Show when={hasChildren && isExpanded()}>
<div> <div>
{props.node.children!.map((child) => ( {props.node.children!.map((child) => (
<HeadingNode <HeadingNode