import Icon from "@/components/Icon"; import Button from "@/components/Button"; import { useState, useRef, useEffect } from "react"; type Props = { content: React.ReactNode; onBack: () => void; }; const EditorArticle = ({ content, onBack }: Props) => { const [isTextSelected, setIsTextSelected] = useState(false); const [selectionPosition, setSelectionPosition] = useState({ top: 0, left: 0, }); const contentRef = useRef(null); const handleTextSelection = () => { const selection = window.getSelection(); if (selection && selection.toString().trim().length > 0) { const range = selection.getRangeAt(0); const rect = range.getBoundingClientRect(); const contentRect = contentRef.current?.getBoundingClientRect(); if (contentRect) { setSelectionPosition({ top: rect.top - contentRect.top - 50, left: rect.left - contentRect.left + rect.width / 2 - 100, }); setIsTextSelected(true); } } else { setIsTextSelected(false); } }; const handleFormatText = (format: string) => { const selection = window.getSelection(); if (selection && selection.rangeCount > 0) { const range = selection.getRangeAt(0); const selectedText = selection.toString(); if (selectedText) { let formattedText = selectedText; switch (format) { case "bold": formattedText = `${selectedText}`; break; case "italic": formattedText = `${selectedText}`; break; case "underline": formattedText = `${selectedText}`; break; case "strikethrough": formattedText = `${selectedText}`; break; } range.deleteContents(); const tempDiv = document.createElement("div"); tempDiv.innerHTML = formattedText; const fragment = document.createDocumentFragment(); while (tempDiv.firstChild) { fragment.appendChild(tempDiv.firstChild); } range.insertNode(fragment); selection.removeAllRanges(); setIsTextSelected(false); } } }; useEffect(() => { document.addEventListener("selectionchange", handleTextSelection); return () => { document.removeEventListener( "selectionchange", handleTextSelection ); }; }, []); return (
{content} {isTextSelected && (
)}
); }; export default EditorArticle;