import React, { DetailedHTMLProps, HTMLAttributes } from "react"; import { DocsLinkType } from "."; import Stack from "../../layout/Stack"; import TWUIDocsLink from "./TWUIDocsLink"; import { twMerge } from "tailwind-merge"; import Span from "../../layout/Span"; import Row from "../../layout/Row"; import { ArrowUpRight, LinkIcon, ListIcon } from "lucide-react"; import Link from "../../layout/Link"; type Props = DetailedHTMLProps, HTMLElement> & { before?: React.ReactNode; after?: React.ReactNode; autoExpandAll?: boolean; editPageURL?: string; }; export default function TWUIDocsRightAside({ after, before, autoExpandAll, editPageURL, ...props }: Props) { const [links, setLinks] = React.useState([]); const [ready, setReady] = React.useState(false); React.useEffect(() => { if (!ready) return; const headerHrefs = document.querySelectorAll( ".twui-docs-header-anchor" ); const linksArr: DocsLinkType[] = []; for (let i = 0; i < headerHrefs.length; i++) { const anchorEl = headerHrefs[i] as HTMLAnchorElement; const isH2Element = anchorEl.querySelector("h2") !== null; if (isH2Element) { let newLink: DocsLinkType = { title: anchorEl.textContent || "", href: `#${anchorEl.id}`, }; let nexElIndex = i + 1; while (nexElIndex < headerHrefs.length) { const nextElement = headerHrefs[ nexElIndex ] as HTMLAnchorElement; const nextElementH3 = nextElement.querySelector("h3"); console.log("nextElement", nextElement); const isNextElementH2 = nextElement.querySelector("h2") !== null; if (isNextElementH2) { break; } if (!nextElementH3) { break; } if (!newLink.children) { newLink.children = []; } newLink.children.push({ title: nextElementH3.textContent || "", href: `#${nextElement.id}`, }); nexElIndex++; } linksArr.push(newLink); } } setLinks(linksArr); }, [ready]); React.useEffect(() => { if (!links.length) return; const headerHrefs = document.querySelectorAll( "a.twui-docs-header-anchor" ); const observer = new IntersectionObserver((entries) => { entries.forEach((entry) => { if (entry.isIntersecting) { const id = entry.target.id; const link = document.querySelector( `.twui-docs-right-aside a[href="#${id}"]` ); if (link) { link.classList.add("active"); } } else { const id = entry.target.id; const link = document.querySelector( `.twui-docs-right-aside a[href="#${id}"]` ); if (link) { link.classList.remove("active"); } } }); }); headerHrefs.forEach((headerHref) => { observer.observe(headerHref); }); }, [links]); React.useEffect(() => { setTimeout(() => { setReady(true); }, 100); }, []); return ( ); }