scaling-swarms / frontend /src /components /TableOfContents.tsx
tfrere's picture
tfrere HF Staff
Cursor
feat: port the template's new page layout to the editor and published articles
eab9566
Raw History Blame Contribute Delete
9.59 kB
import { useState, useEffect, useCallback, useLayoutEffect, useMemo, useRef } from "react";
import type { Editor } from "@tiptap/core";
const SCROLL_OFFSET_PX = 100;
interface TocItem {
id: string;
text: string;
level: number;
pos: number;
}
interface TocSection extends TocItem {
subs: TocItem[];
}
function extractHeadings(editor: Editor): TocItem[] {
const items: TocItem[] = [];
editor.state.doc.descendants((node, pos) => {
if (node.type.name === "heading") {
const level = node.attrs.level as number;
const text = node.textContent;
if ((level === 2 || level === 3) && text.trim()) {
items.push({ id: `heading-${pos}`, text, level, pos });
}
}
});
return items;
}
/** Same outline as the template's toc.ts: h2 sections with their h3, or h3 sections when there is no h2. */
function buildSections(headings: TocItem[]): TocSection[] {
const topLevel = headings.some((h) => h.level === 2) ? 2 : 3;
const secs: TocSection[] = [];
for (const h of headings) {
if (h.level === topLevel) secs.push({ ...h, subs: [] });
else if (secs.length) secs[secs.length - 1].subs.push(h);
}
return secs;
}
/**
* Resolve ProseMirror position to the closest heading DOM element.
*/
function resolveHeadingElement(editor: Editor, pos: number): HTMLElement | null {
try {
const dom = editor.view.domAtPos(pos + 1);
let el: HTMLElement | null =
dom.node instanceof HTMLElement ? dom.node : dom.node.parentElement;
while (el && !/^H[1-6]$/i.test(el.tagName)) {
el = el.parentElement;
}
return el;
} catch {
return null;
}
}
interface TableOfContentsProps {
editor: Editor | null;
scrollContainer?: HTMLElement | null;
/** Sub-headings always expanded (frontmatter `tocExpanded`), or only for the active section */
expanded?: boolean;
readMinutes?: number;
onNavigate?: () => void;
}
/**
* The template's "line" TOC (Toc.astro + toc.ts) for the editor: same markup
* and classes, styled by template-layout/_toc.css. The outline follows the
* live document instead of the rendered page, and scroll-spy runs on the
* editor's scroll container.
*/
export function TableOfContents({ editor, scrollContainer, expanded = true, readMinutes, onNavigate }: TableOfContentsProps) {
const [headings, setHeadings] = useState<TocItem[]>([]);
const [activePos, setActivePos] = useState<number | null>(null);
const [stuck, setStuck] = useState(false);
const [line, setLine] = useState<{ top: number; height: number; fill: number } | null>(null);
const navRef = useRef<HTMLElement>(null);
const listRef = useRef<HTMLDivElement>(null);
const debounceRef = useRef(0);
useEffect(() => {
if (!editor) return;
setHeadings(extractHeadings(editor));
// 60ms debounce: short enough that headings typed by any collaborator
// (local or remote via Yjs) appear in the TOC with no perceptible lag
// while still coalescing bursts of per-keystroke updates.
const debouncedUpdate = () => {
clearTimeout(debounceRef.current);
debounceRef.current = window.setTimeout(
() => setHeadings(extractHeadings(editor)),
60,
);
};
editor.on("update", debouncedUpdate);
// Yjs remote transactions also fire "transaction" - listen to both so
// the TOC keeps pace with collaborators editing in other browsers.
editor.on("transaction", debouncedUpdate);
return () => {
editor.off("update", debouncedUpdate);
editor.off("transaction", debouncedUpdate);
clearTimeout(debounceRef.current);
};
}, [editor]);
// Scroll-spy via IntersectionObserver - no per-frame scroll work.
//
// Semantics: active heading = the *topmost visible heading inside the scroll
// container's reading zone* (below the SCROLL_OFFSET_PX top margin).
// This is intentionally different from the published page, whose TOC
// (template toc.ts) follows a reading line at 30% of the viewport.
// Rationale: users navigate the editor non-linearly (click TOC, jump, split
// view), and the topmost-visible rule reacts instantly when a heading enters
// the reading zone, so the rail always reflects what the user is looking at.
useEffect(() => {
if (!editor || headings.length === 0) return;
const root = scrollContainer ?? null;
const visibleSet = new Map<Element, number>();
const observer = new IntersectionObserver(
(entries) => {
for (const entry of entries) {
if (entry.isIntersecting) {
visibleSet.set(entry.target, headings.findIndex(
(h) => resolveHeadingElement(editor, h.pos) === entry.target,
));
} else {
visibleSet.delete(entry.target);
}
}
let bestIdx = -1;
for (const idx of visibleSet.values()) {
if (idx >= 0 && (bestIdx < 0 || idx < bestIdx)) bestIdx = idx;
}
if (visibleSet.size > 0) {
setActivePos(bestIdx >= 0 ? headings[bestIdx].pos : null);
}
},
{
root,
rootMargin: `-${SCROLL_OFFSET_PX}px 0px 0px 0px`,
threshold: 0,
},
);
for (const h of headings) {
const el = resolveHeadingElement(editor, h.pos);
if (el) observer.observe(el);
}
return () => observer.disconnect();
}, [editor, headings, scrollContainer]);
// "x min read" appears once the rail is stuck, like on the published page
useEffect(() => {
const nav = navRef.current;
if (!scrollContainer || !nav) return;
let raf = 0;
const check = () => {
cancelAnimationFrame(raf);
raf = requestAnimationFrame(() => {
const stickyTop = parseFloat(getComputedStyle(nav).top) || 0;
const rootTop = scrollContainer.getBoundingClientRect().top;
setStuck(nav.getBoundingClientRect().top - rootTop <= stickyTop + 0.5);
});
};
check();
scrollContainer.addEventListener("scroll", check, { passive: true });
return () => {
scrollContainer.removeEventListener("scroll", check);
cancelAnimationFrame(raf);
};
}, [scrollContainer, headings.length]);
const secs = useMemo(() => buildSections(headings), [headings]);
const activeSec = useMemo(() => {
if (activePos == null) return 0;
let si = 0;
secs.forEach((s, i) => {
if (s.pos <= activePos) si = i;
});
return si;
}, [secs, activePos]);
const activeItemPos = activePos ?? secs[0]?.pos ?? null;
// Indicator on the active link, fill down to it (follows the sub-heading
// expand / collapse transition for a few frames).
useLayoutEffect(() => {
const list = listRef.current;
if (!list) return;
let raf = 0;
const t0 = performance.now();
const place = () => {
const a = list.querySelector<HTMLElement>("a[aria-current]");
if (a) {
const lr = list.getBoundingClientRect();
const ar = a.getBoundingClientRect();
setLine({ top: ar.top - lr.top, height: ar.height, fill: ar.top - lr.top + ar.height });
} else {
setLine(null);
}
if (performance.now() - t0 < 280) raf = requestAnimationFrame(place);
};
place();
return () => cancelAnimationFrame(raf);
}, [activeItemPos, activeSec, secs, expanded]);
const scrollTo = useCallback((pos: number) => {
if (!editor) return;
const el = resolveHeadingElement(editor, pos);
if (el) {
el.scrollIntoView({ behavior: "smooth", block: "start" });
}
editor.chain().focus().setTextSelection(pos).run();
onNavigate?.();
}, [editor, onNavigate]);
const link = (item: TocItem) => (
<a
href="#"
aria-current={item.pos === activeItemPos ? "true" : undefined}
onClick={(e) => {
e.preventDefault();
scrollTo(item.pos);
}}
>
{item.text}
</a>
);
return (
<nav
ref={navRef}
className={`table-of-contents${stuck ? " is-stuck" : ""}${line ? " is-ready" : ""}`}
aria-label="Table of contents"
data-toc-expanded={expanded ? "true" : "false"}
>
<div className="toc-head">
<span className="toc-title">Contents</span>
{readMinutes != null && <span className="toc-meta">{readMinutes} min read</span>}
</div>
{!editor || secs.length === 0 ? (
<div className="toc-empty">Headings will appear here as you write.</div>
) : (
<div className="toc-scroll">
<div className="toc-list" ref={listRef}>
<span className="toc-track" aria-hidden="true" />
<span className="toc-fill" aria-hidden="true" style={{ height: line ? `${line.fill}px` : 0 }} />
<span
className="toc-indicator"
aria-hidden="true"
style={line ? { transform: `translateY(${line.top}px)`, height: `${line.height}px` } : undefined}
/>
<ol>
{secs.map((s, i) => (
<li
key={s.id}
className={`toc-sec${i === activeSec ? " is-active is-open" : ""}${i < activeSec ? " is-read" : ""}`}
>
{link(s)}
{s.subs.length > 0 && (
<div className="toc-sub">
<ol>
{s.subs.map((h) => (
<li key={h.id}>{link(h)}</li>
))}
</ol>
</div>
)}
</li>
))}
</ol>
</div>
</div>
)}
</nav>
);
}