(null);
const measure = useCallback(() => {
const container = containerRef.current;
if (!container || container.clientHeight === 0 || items.length === 0) {
setTrackState(null);
return;
}
const positions: TocTrackPosition[] = [];
for (let index = 0; index < items.length; index += 1) {
const anchor = anchorRefs.current[index];
const item = items[index];
if (!anchor || !item) {
setTrackState(null);
return;
}
const styles = getComputedStyle(anchor);
const paddingTop = Number.parseFloat(styles.paddingTop) || 0;
const paddingBottom = Number.parseFloat(styles.paddingBottom) || 0;
positions.push({
top: anchor.offsetTop + paddingTop,
bottom: anchor.offsetTop + anchor.clientHeight - paddingBottom,
x: getTocTrackOffset(item.depth),
});
}
const geometry = buildTocTrackGeometry(positions);
setTrackState(geometry ? { geometry, positions } : null);
}, [items]);
useEffect(() => {
const container = containerRef.current;
if (!container) return;
const observer = new ResizeObserver(measure);
observer.observe(container);
for (const anchor of anchorRefs.current) if (anchor) observer.observe(anchor);
measure();
return () => observer.disconnect();
}, [measure]);
return (
{trackState ? : null}
{items.map((item, index) => (
{
anchorRefs.current[index] = element;
}}
href={item.url}
className={cn(
"prose relative py-1.5 scroll-m-4 text-fd-muted-foreground transition-colors wrap-anywhere data-[active=true]:text-fd-primary hover:text-fd-accent-foreground text-xs leading-5",
index === 0 && "pt-0",
index === items.length - 1 && "pb-0",
)}
style={{ paddingInlineStart: itemPadding(item.depth) }}
>
{renderTitle(item.title)}
))}
);
}
export function Toc({ items }: { items: TocEntry[] }) {
const viewRef = useRef(null);
// `AnchorProvider`는 `url`(헤딩 id)과 `depth`만 읽는다.
const toc = useMemo(
() => items.map((item) => ({ url: item.url, depth: item.depth, title: item.url })),
[items],
);
return (
{items.length > 0 ? (
목차
) : null}
);
}