import { Card, CardContent, CardHeader, CardTitle, } from "@/components/shadcn/ui/card"; import { useEffect, useRef, useState } from 'react'; const SideContent = ({ parsedHtml }) => { const el = parsedHtml; const [activeId, setActiveId] = useState(''); const titleListRef = useRef([]); const handleScroll = () => { const currentScroll = window.scrollY; titleListRef.current.forEach((title) => { const rect = title.getBoundingClientRect(); const titleTop = rect.top + currentScroll; if (currentScroll >= titleTop -1 ) { setActiveId(title.id); } }); }; useEffect(() => { window.addEventListener('scroll', handleScroll); return () => { window.removeEventListener('scroll', handleScroll); }; }, []); const setElement = (selector) => { let i = 0; selector.forEach((element) => { const elementParent = element.closest("p"); if (elementParent) { elementParent.id = `page-${i}`; elementParent.classList.add('pt-[10px]') titleListRef.current[i] = elementParent; i++; } }); }; useEffect(() => { const allElements = [...document.querySelectorAll(".sub_tit"), ...document.querySelectorAll(".li")]; allElements.sort((a, b) => a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1); setElement(allElements); }, []); const extractTexts = (el) => { let texts = []; const traverse = (node) => { if (node.type === 'p' && node.props.className !== 'nb_date') { const extractText = (child) => { if (typeof child === 'string') { return child.trim(); } if (child && typeof child === 'object' && child.type) { return Array.isArray(child.props.children) ? child.props.children.map(extractText).filter(Boolean).join(' ') : extractText(child.props.children); } return ''; }; const text = Array.isArray(node.props.children) ? node.props.children.map(extractText).filter(Boolean).join(' ').trim() : extractText(node.props.children); if (text) { texts.push(text); } } if (Array.isArray(node)) { node.forEach(traverse); } if (node && node.props && node.props.children) { traverse(node.props.children); } }; traverse(el); return texts; }; const texts = extractTexts(el); const renderContent = () => { let elements = []; let currentList = []; let inList = false; let titleIndex = 0; texts.forEach((text, index) => { if (text[0] === '*') { if (inList) { elements.push( ); currentList = []; inList = false; } elements.push( {text.trim()} ); titleIndex++; } else if (/\d+\./.test(text)) { currentList.push(
  • {text}
  • ); inList = true; titleIndex++; } }); if (inList) { elements.push( ); } return elements; }; return (
    목차 {renderContent()}
    ); }; export default SideContent;