import { useDoc } from "@docusaurus/theme-common/internal"; import clsx from "clsx"; import React from "react"; // import { useDocTOCwithTutorial } from "../components/tutorial-toc/index"; import { useHistory, useLocation } from "@docusaurus/router"; export const TOCItem = ({ id, value, level, activeId, onIdChange, }: { id: string; value: string; level: number; activeId: string; onIdChange?: (id: string) => void; }) => { React.useEffect(() => { const targetElement = document.getElementById(id); if (targetElement) { const observer = new IntersectionObserver( (entries) => { entries.forEach((entry) => { if (entry.isIntersecting) { onIdChange(id); } }); }, { rootMargin: "0px 0px -80% 0px", }, ); observer.observe(targetElement); return () => { observer.unobserve(targetElement); }; } }, [id]); return ( ); }; export const DocTOC = () => { const location = useLocation(); const history = useHistory(); const { toc, hasTOC, activeId, setActiveId } = useTOC(); const onIdChange = (id) => { if (id !== `${location.hash ?? ""}`.replace("#", "")) { setActiveId(id); // history.replace({ // ...location, // hash: `#${id}`, // }); window.history.replaceState({}, "", `#${id}`); } }; return (
); }; export const useTOC = () => { const { hash } = useLocation(); const baseActiveId = `${hash}`.replace("#", ""); const [activeId, setActiveId] = React.useState( baseActiveId, ); React.useEffect(() => { setActiveId(baseActiveId); }, [baseActiveId]); // const docTOC = useDocTOCwithTutorial(); const { toc } = useDoc(); const hasTOC = toc?.length > 0; return { toc, activeId, setActiveId, hasTOC, }; };