refactor: toc behaviour

This commit is contained in:
hypercross 2026-03-25 10:49:15 +08:00
parent 3aaa991bd8
commit a7477666c7
1 changed files with 12 additions and 10 deletions

View File

@ -85,13 +85,15 @@ export const HeadingNode: Component<{
const href = `${props.basePath}#${anchor}`; const href = `${props.basePath}#${anchor}`;
const hasChildren = !!props.node.children; const hasChildren = !!props.node.children;
// 默认收起,除非当前锚点在该节点内 // 默认收起,除非当前锚点在该节点内
const [isExpanded, setIsExpanded] = createSignal(false); const [isExpanded, setIsExpanded] = createSignal(props.depth <= 0);
const handleClick = (e: MouseEvent) => { const handleExpand = (e: MouseEvent) => {
e.preventDefault(); e.preventDefault();
if (hasChildren) { if (hasChildren) {
setIsExpanded(!isExpanded()); setIsExpanded(!isExpanded());
} }
};
const handleClick = (e: MouseEvent) => {
navigate(href); navigate(href);
// 滚动到目标元素,考虑导航栏高度偏移 // 滚动到目标元素,考虑导航栏高度偏移
requestAnimationFrame(() => { requestAnimationFrame(() => {
@ -100,7 +102,7 @@ export const HeadingNode: Component<{
const navBarHeight = 80; const navBarHeight = 80;
const elementPosition = element.getBoundingClientRect().top; const elementPosition = element.getBoundingClientRect().top;
const offsetPosition = window.scrollY + elementPosition - navBarHeight; const offsetPosition = window.scrollY + elementPosition - navBarHeight;
window.scrollTo({ top: offsetPosition, behavior: "smooth" }); window.scrollTo({ top: offsetPosition, behavior: "instant" });
} }
}); });
}; };
@ -109,17 +111,17 @@ export const HeadingNode: Component<{
return ( return (
<div> <div>
<span class={`${hasChildren ? "" : "invisible" } ${isExpanded() ? "rotate-90" : ""} inline-block transition-transform cursor-pointer mr-1 text-gray-400 text-xs w-3 flex-shrink-0`}
style={{ "margin-left": `${indent + 8}px` }}
onClick={handleExpand}
>
</span>
<a <a
href={href} href={href}
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" class="inline-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` }}
onClick={handleClick} onClick={handleClick}
> >
<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> <span class="truncate">{props.node.title}</span>
</a> </a>
<Show when={hasChildren && isExpanded()}> <Show when={hasChildren && isExpanded()}>