import { useCallback, useEffect, useMemo, useState } from "react"; import type { Editor } from "@tiptap/react"; import { PanelLeftClose, PanelLeftOpen } from "lucide-react"; import { cn } from "@/lib/utils"; import { useDocumentOutline } from "../../hooks/useDocumentOutline"; import type { OutlineHeading } from "../../hooks/useDocumentOutline"; interface DraftOutlineSidebarProps { /** Tiptap 编辑器实例,用于提取标题并解析标题 DOM */ editor: Editor | null; /** 文档滚动容器,点击目录项 / scroll-spy 时在其内部滚动与定位 */ scrollEl: HTMLElement | null; } /** 点击跳转时标题距容器顶部预留的间距(px) */ const SCROLL_TOP_OFFSET = 16; /** scroll-spy:标题顶部进入此阈值内即视为「当前章节」(px) */ const ACTIVE_THRESHOLD = 80; /** * 目录项的展示层级: * - 文档 H1 = 文章标题,单独作顶部标题块(不进列表) * - 文档 H2 = 章节名称 → 列表一级项 * - 文档 H3 = 要点 → 列表二级项 */ function displayLevel(h: OutlineHeading): 1 | 2 { return h.level >= 3 ? 2 : 1; } /** * 草稿文档左侧目录栏(仿豆包 / Word 目录窗格): * 顶部独立标题块 + 章节/要点两级列表,支持点击平滑跳转、滚动高亮、折叠。 */ export function DraftOutlineSidebar({ editor, scrollEl }: DraftOutlineSidebarProps) { const headings = useDocumentOutline(editor); const [activeId, setActiveId] = useState(null); const [collapsed, setCollapsed] = useState(false); // 第一个 H1 作为文章标题,其余标题进目录列表 const { titleHeading, items } = useMemo(() => { const titleIdx = headings.findIndex((h) => h.level === 1); return { titleHeading: titleIdx >= 0 ? headings[titleIdx] : null, items: headings.filter((_, i) => i !== titleIdx), }; }, [headings]); const scrollToHeading = useCallback( (pos: number, id: string) => { if (!editor || !scrollEl) return; const dom = editor.view.nodeDOM(pos) as HTMLElement | null; if (!dom) return; const elTop = dom.getBoundingClientRect().top; const containerTop = scrollEl.getBoundingClientRect().top; const target = scrollEl.scrollTop + (elTop - containerTop) - SCROLL_TOP_OFFSET; scrollEl.scrollTo({ top: Math.max(0, target), behavior: "smooth" }); setActiveId(id); }, [editor, scrollEl], ); // scroll-spy:随文档滚动高亮当前章节(rAF 节流) useEffect(() => { if (!editor || !scrollEl || headings.length === 0) return; let raf = 0; const recompute = () => { raf = 0; const containerTop = scrollEl.getBoundingClientRect().top; let current = headings[0].id; for (const h of headings) { const dom = editor.view.nodeDOM(h.pos) as HTMLElement | null; if (!dom) continue; const relTop = dom.getBoundingClientRect().top - containerTop; // 标题在阈值内或之上 → 当前章节;首个落在阈值下方时其余皆下方,停止 if (relTop <= ACTIVE_THRESHOLD) { current = h.id; } else { break; } } setActiveId(current); }; const onScroll = () => { if (raf) return; raf = requestAnimationFrame(recompute); }; recompute(); scrollEl.addEventListener("scroll", onScroll, { passive: true }); return () => { if (raf) cancelAnimationFrame(raf); scrollEl.removeEventListener("scroll", onScroll); }; }, [editor, scrollEl, headings]); // 没有可导航的章节时不渲染目录栏 if (items.length === 0) return null; // 折叠态:仅留一条窄轨 + 展开按钮 if (collapsed) { return (
); } return (
{/* 头部:目录标签 + 折叠按钮 */}
目录
{/* 文章标题块 */} {titleHeading && ( )} {/* 章节 / 要点列表 */}
); }