'use client'; import React, { useEffect, useRef, useState } from 'react'; import 'quill/dist/quill.snow.css'; import { sanitizeHtml } from '@/lib/utils/email-formatter'; interface RichEmailEditorProps { initialContent: string; onChange: (content: string) => void; placeholder?: string; minHeight?: string; maxHeight?: string; preserveFormatting?: boolean; } const RichEmailEditor: React.FC = ({ initialContent, onChange, placeholder = 'Write your message here...', minHeight = '200px', maxHeight = 'calc(100vh - 400px)', preserveFormatting = false, }) => { const editorRef = useRef(null); const toolbarRef = useRef(null); const quillRef = useRef(null); const [isReady, setIsReady] = useState(false); // Initialize Quill editor when component mounts useEffect(() => { // Import Quill dynamically (client-side only) const initializeQuill = async () => { if (!editorRef.current || !toolbarRef.current) return; const Quill = (await import('quill')).default; // Import quill-better-table try { const QuillBetterTable = await import('quill-better-table'); // Register the table module if available if (QuillBetterTable && QuillBetterTable.default) { Quill.register({ 'modules/better-table': QuillBetterTable.default }, true); console.log('Better Table module registered successfully'); } } catch (err) { console.warn('Table module not available:', err); } // Define custom formats/modules with table support const emailToolbarOptions = [ ['bold', 'italic', 'underline', 'strike'], [{ 'color': [] }, { 'background': [] }], [{ 'list': 'ordered'}, { 'list': 'bullet' }], [{ 'indent': '-1'}, { 'indent': '+1' }], [{ 'align': [] }], ['link'], ['clean'], ]; // Create new Quill instance with the DOM element and custom toolbar const editorElement = editorRef.current; quillRef.current = new Quill(editorElement, { modules: { toolbar: { container: toolbarRef.current, handlers: { // Add any custom toolbar handlers here } }, 'better-table': preserveFormatting ? { operationMenu: { items: { unmergeCells: { text: 'Unmerge cells' } } } } : false, }, placeholder: placeholder, theme: 'snow', }); // Set initial content (sanitized) if (initialContent) { try { // First, ensure we preserve the raw HTML structure const preservedContent = sanitizeHtml(initialContent); // Set editor content with paste method which preserves most formatting quillRef.current.clipboard.dangerouslyPasteHTML(0, preservedContent); // If we're specifically trying to preserve complex HTML like tables if (preserveFormatting) { // For tables and complex formatting, we may need to manually preserve some elements // Get all table elements from the original content const tempDiv = document.createElement('div'); tempDiv.innerHTML = preservedContent; // Force better table rendering in Quill setTimeout(() => { // This ensures tables are properly rendered by forcing a refresh quillRef.current.update(); // Additional step: directly set HTML if tables aren't rendering properly if (tempDiv.querySelectorAll('table').length > 0 && !quillRef.current.root.querySelectorAll('table').length) { console.log('Using HTML fallback for tables'); quillRef.current.root.innerHTML = preservedContent; } }, 50); } } catch (err) { console.error('Error setting initial content:', err); // Fallback method if the above fails quillRef.current.setText(''); quillRef.current.clipboard.dangerouslyPasteHTML(sanitizeHtml(initialContent)); } } // Add change listener quillRef.current.on('text-change', () => { const html = quillRef.current.root.innerHTML; onChange(html); }); // Improve editor layout const editorContainer = editorElement.closest('.ql-container'); if (editorContainer) { editorContainer.classList.add('email-editor-container'); } setIsReady(true); }; initializeQuill().catch(err => { console.error('Failed to initialize Quill editor:', err); }); // Clean up on unmount return () => { if (quillRef.current) { // Clean up any event listeners or resources quillRef.current.off('text-change'); } }; }, []); // Update content from props if changed externally useEffect(() => { if (quillRef.current && isReady) { const currentContent = quillRef.current.root.innerHTML; // Only update if content changed to avoid editor position reset if (initialContent !== currentContent) { try { // Preserve cursor position if possible const selection = quillRef.current.getSelection(); // First clear the content quillRef.current.root.innerHTML = ''; // Then insert the new content at position 0 quillRef.current.clipboard.dangerouslyPasteHTML(0, sanitizeHtml(initialContent)); // Force update quillRef.current.update(); // Restore selection if possible if (selection) { setTimeout(() => quillRef.current.setSelection(selection), 10); } } catch (err) { console.error('Error updating content:', err); // Fallback update method quillRef.current.clipboard.dangerouslyPasteHTML(sanitizeHtml(initialContent)); } } } }, [initialContent, isReady]); return (
{/* Custom toolbar container */}
{/* Editor container with improved scrolling */}
{/* Loading indicator */} {!isReady && (
)}
{/* Custom styles for email context */}
); }; export default RichEmailEditor;