import { AlignCenter, AlignLeft, AlignRight, Bold, Code, Heading1, Heading2, Heading3, Heading4, Image as ImageIcon, Italic, Link as LinkIcon, List, ListOrdered, Maximize2, Minimize2, Minus, Music, PaintBucket, Palette, Quote, Redo, RemoveFormatting, Table as TableIcon, Underline, Undo, Video, } from 'lucide-react'; import { useCallback,useEffect,useRef,useState } from 'react'; import MediaSelector from './MediaSelector'; interface RichTextEditorProps { value: string; onChange: (html: string) => void; placeholder?: string; className?: string; minHeight?: string; } const PRESET_COLORS = [ { label: 'سیاه / پیش‌فرض', value: '#111827' }, { label: 'خاکستری', value: '#4b5563' }, { label: 'آبی کنینا', value: '#0052cc' }, { label: 'بنفش اختصاصی', value: '#7c3aed' }, { label: 'سبز درمانی', value: '#059669' }, { label: 'قرمز هشدار', value: '#dc2626' }, { label: 'کهربایی / زرد', value: '#d97706' }, ]; const PRESET_BG_COLORS = [ { label: 'بی‌رنگ / حذف پس‌زمینه', value: 'transparent' }, { label: 'هایلایت زرد', value: '#fef08a' }, { label: 'هایلایت آبی', value: '#dbeafe' }, { label: 'هایلایت بنفش', value: '#f3e8ff' }, { label: 'هایلایت سبز', value: '#dcfce7' }, { label: 'هایلایت قرمز', value: '#fee2e2' }, { label: 'خاکستری ملایم', value: '#f3f4f6' }, ]; interface ActiveStates { isBold: boolean; isItalic: boolean; isUnderline: boolean; isH1: boolean; isH2: boolean; isH3: boolean; isH4: boolean; isP: boolean; isUL: boolean; isOL: boolean; isBlockquote: boolean; align: 'right' | 'center' | 'left' | 'justify'; } export default function RichTextEditor({ value, onChange, placeholder = 'محتوای مقاله یا متن خود را اینجا بنویسید...', className = '', minHeight = 'min-h-[300px]', }: RichTextEditorProps) { const editorRef = useRef(null); const isTypingRef = useRef(false); const isMountedRef = useRef(false); const [isCodeMode, setIsCodeMode] = useState(false); const [isFullscreen, setIsFullscreen] = useState(false); const [showColorPicker, setShowColorPicker] = useState(false); const [showBgColorPicker, setShowBgColorPicker] = useState(false); const colorPickerRef = useRef(null); const bgColorPickerRef = useRef(null); useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if (colorPickerRef.current && !colorPickerRef.current.contains(event.target as Node)) { setShowColorPicker(false); } if (bgColorPickerRef.current && !bgColorPickerRef.current.contains(event.target as Node)) { setShowBgColorPicker(false); } }; document.addEventListener('mousedown', handleClickOutside); return () => document.removeEventListener('mousedown', handleClickOutside); }, []); const [customColor, setCustomColor] = useState('#111827'); const [customBgColor, setCustomBgColor] = useState('#fef08a'); // Media selector modal state const [mediaModalOpen, setMediaModalOpen] = useState(false); const [mediaTargetType, setMediaTargetType] = useState<'image' | 'video' | 'audio'>('image'); const savedSelectionRef = useRef(null); // Inline Image Alt Modal const [showImagePrompt, setShowImagePrompt] = useState(false); const [pendingImageUrl, setPendingImageUrl] = useState(''); const [imageAlt, setImageAlt] = useState(''); const [imageCaption, setImageCaption] = useState(''); const [activeStates, setActiveStates] = useState({ isBold: false, isItalic: false, isUnderline: false, isH1: false, isH2: false, isH3: false, isH4: false, isP: false, isUL: false, isOL: false, isBlockquote: false, align: 'right', }); // Save selection before opening modal const saveSelection = () => { const sel = window.getSelection(); if (sel && sel.rangeCount > 0) { savedSelectionRef.current = sel.getRangeAt(0).cloneRange(); } }; const restoreSelection = () => { const sel = window.getSelection(); if (sel && savedSelectionRef.current) { sel.removeAllRanges(); sel.addRange(savedSelectionRef.current); } }; // Query formatting states on cursor/selection change const updateActiveStates = useCallback(() => { if (!editorRef.current || isCodeMode) return; try { const doc = document as any; const isBold = doc.queryCommandState ? doc.queryCommandState('bold') : false; const isItalic = doc.queryCommandState ? doc.queryCommandState('italic') : false; const isUnderline = doc.queryCommandState ? doc.queryCommandState('underline') : false; const isUL = doc.queryCommandState ? doc.queryCommandState('insertUnorderedList') : false; const isOL = doc.queryCommandState ? doc.queryCommandState('insertOrderedList') : false; let block = (doc.queryCommandValue ? doc.queryCommandValue('formatBlock') : '') || ''; block = block.toLowerCase().replace(/[<>]/g, ''); // Check parent tag const selection = window.getSelection(); let parentTag = ''; if (selection && selection.rangeCount > 0) { let node: Node | null = selection.getRangeAt(0).commonAncestorContainer; if (node && node.nodeType === 3 && node.parentNode) { node = node.parentNode; } while (node && node !== editorRef.current) { const tag = (node as HTMLElement).tagName?.toLowerCase(); if (['h1', 'h2', 'h3', 'h4', 'p', 'ul', 'ol', 'blockquote'].includes(tag)) { parentTag = tag; break; } node = node.parentNode; } } const activeBlock = parentTag || block; setActiveStates({ isBold, isItalic, isUnderline, isH1: activeBlock === 'h1', isH2: activeBlock === 'h2', isH3: activeBlock === 'h3', isH4: activeBlock === 'h4', isBlockquote: activeBlock === 'blockquote', isP: activeBlock === 'p' || (!['h1', 'h2', 'h3', 'h4', 'blockquote'].includes(activeBlock) && !isUL && !isOL), isUL, isOL, align: doc.queryCommandState && doc.queryCommandState('justifyCenter') ? 'center' : doc.queryCommandState && doc.queryCommandState('justifyLeft') ? 'left' : 'right', }); } catch { // Ignored } }, [isCodeMode]); // Sync value from props on initial mount or when external change occurs useEffect(() => { if (!editorRef.current) return; if (!isMountedRef.current) { editorRef.current.innerHTML = value || ''; isMountedRef.current = true; return; } if (editorRef.current.innerHTML !== (value || '')) { if (!isTypingRef.current && document.activeElement !== editorRef.current) { editorRef.current.innerHTML = value || ''; } } }, [value, isCodeMode]); const exec = (command: string, val: string | undefined = undefined) => { if (isCodeMode) return; editorRef.current?.focus(); document.execCommand(command, false, val); if (editorRef.current) { onChange(editorRef.current.innerHTML); } setTimeout(updateActiveStates, 20); }; const setBlockTag = (tagName: 'h1' | 'h2' | 'h3' | 'h4' | 'p' | 'blockquote') => { if (isCodeMode) return; editorRef.current?.focus(); const blockValue = `<${tagName}>`; const success = document.execCommand('formatBlock', false, blockValue); if (!success) { document.execCommand('formatBlock', false, tagName); } if (editorRef.current) { onChange(editorRef.current.innerHTML); } setTimeout(updateActiveStates, 20); }; const handleLink = () => { if (isCodeMode) return; const url = prompt('آدرس لینک (URL) را وارد کنید:', 'https://'); if (url) { exec('createLink', url); } }; const handleInsertHorizontalRule = () => { if (isCodeMode) return; exec('insertHorizontalRule'); }; const handleInsertTable = () => { if (isCodeMode) return; const rows = 3; const cols = 3; let tableHtml = ''; for (let c = 0; c < cols; c++) { tableHtml += ``; } tableHtml += ''; for (let r = 0; r < rows; r++) { tableHtml += ''; for (let c = 0; c < cols; c++) { tableHtml += ''; } tableHtml += ''; } tableHtml += '
عنوان ${c + 1}
داده


'; editorRef.current?.focus(); document.execCommand('insertHTML', false, tableHtml); if (editorRef.current) { onChange(editorRef.current.innerHTML); } }; const openMediaModal = (type: 'image' | 'video' | 'audio') => { saveSelection(); setMediaTargetType(type); setMediaModalOpen(true); }; const handleMediaSelect = (url: string) => { setMediaModalOpen(false); restoreSelection(); if (mediaTargetType === 'image') { setPendingImageUrl(url); setImageAlt(''); setImageCaption(''); setShowImagePrompt(true); } else if (mediaTargetType === 'video') { const videoHtml = `


`; editorRef.current?.focus(); document.execCommand('insertHTML', false, videoHtml); if (editorRef.current) onChange(editorRef.current.innerHTML); } else if (mediaTargetType === 'audio') { const audioHtml = `
🎵 فایل صوتی / پادکست


`; editorRef.current?.focus(); document.execCommand('insertHTML', false, audioHtml); if (editorRef.current) onChange(editorRef.current.innerHTML); } }; const confirmInsertImage = () => { if (!pendingImageUrl) return; const figureHtml = `
${imageAlt.replace(/ ${imageCaption ? `
${imageCaption}
` : ''}


`; editorRef.current?.focus(); document.execCommand('insertHTML', false, figureHtml); if (editorRef.current) onChange(editorRef.current.innerHTML); setShowImagePrompt(false); setPendingImageUrl(''); }; const handleInput = () => { if (editorRef.current) { isTypingRef.current = true; onChange(editorRef.current.innerHTML); setTimeout(() => { isTypingRef.current = false; }, 50); updateActiveStates(); } }; const clearFormatting = () => { exec('removeFormat'); setBlockTag('p'); }; return (
{/* Toolbar */}
{/* Headings */}
{/* Basic Formats */}
{/* Alignment */}
{/* Lists & Link */}
{/* Inline Media Insert Buttons (Image, Video, Audio) */}
{/* Text Color Picker */}
{showColorPicker && (
رنگ‌های پیشنهادی:
{PRESET_COLORS.map((c) => (
{ setCustomColor(e.target.value); exec('foreColor', e.target.value); }} className="w-8 h-8 rounded-lg cursor-pointer border-none bg-transparent" /> { setCustomColor(e.target.value); exec('foreColor', e.target.value); }} placeholder="#111827" className="w-full text-xs font-mono font-bold px-2 py-1 border border-gray-200 rounded-lg outline-none uppercase" dir="ltr" />
)}
{/* Background Color Picker */}
{showBgColorPicker && (
رنگ‌های هایلایت:
{PRESET_BG_COLORS.map((c) => (
{ setCustomBgColor(e.target.value); exec('hiliteColor', e.target.value); }} className="w-8 h-8 rounded-lg cursor-pointer border-none bg-transparent" /> { setCustomBgColor(e.target.value); exec('hiliteColor', e.target.value); }} placeholder="#fef08a" className="w-full text-xs font-mono font-bold px-2 py-1 border border-gray-200 rounded-lg outline-none uppercase" dir="ltr" />
)}
{/* View Mode & Fullscreen */}
{/* Editor Content Area */} {isCodeMode ? (