534 lines
20 KiB
TypeScript
534 lines
20 KiB
TypeScript
'use client';
|
|
|
|
import { useState, useRef, useEffect } from 'react';
|
|
import { formatEmailForReplyOrForward, EmailMessage } from '@/lib/services/email-service';
|
|
import { X, Paperclip, ChevronDown, ChevronUp, SendHorizontal, Loader2 } from 'lucide-react';
|
|
import { Button } from '@/components/ui/button';
|
|
import { Input } from '@/components/ui/input';
|
|
import { Card, CardContent, CardHeader, CardTitle, CardFooter } from '@/components/ui/card';
|
|
import { decodeEmail } from '@/lib/mail-parser-wrapper';
|
|
import DOMPurify from 'isomorphic-dompurify';
|
|
|
|
interface ComposeEmailProps {
|
|
initialEmail?: EmailMessage | null;
|
|
type?: 'new' | 'reply' | 'reply-all' | 'forward';
|
|
onClose: () => void;
|
|
onSend: (emailData: {
|
|
to: string;
|
|
cc?: string;
|
|
bcc?: string;
|
|
subject: string;
|
|
body: string;
|
|
attachments?: Array<{
|
|
name: string;
|
|
content: string;
|
|
type: string;
|
|
}>;
|
|
}) => Promise<void>;
|
|
}
|
|
|
|
export default function ComposeEmail({
|
|
initialEmail,
|
|
type = 'new',
|
|
onClose,
|
|
onSend
|
|
}: ComposeEmailProps) {
|
|
// Email form state
|
|
const [to, setTo] = useState<string>('');
|
|
const [cc, setCc] = useState<string>('');
|
|
const [bcc, setBcc] = useState<string>('');
|
|
const [subject, setSubject] = useState<string>('');
|
|
const [body, setBody] = useState<string>('');
|
|
|
|
// UI state
|
|
const [showCc, setShowCc] = useState<boolean>(false);
|
|
const [showBcc, setShowBcc] = useState<boolean>(false);
|
|
const [sending, setSending] = useState<boolean>(false);
|
|
const [attachments, setAttachments] = useState<Array<{
|
|
name: string;
|
|
content: string;
|
|
type: string;
|
|
}>>([]);
|
|
|
|
const editorRef = useRef<HTMLDivElement | null>(null);
|
|
const attachmentInputRef = useRef<HTMLInputElement | null>(null);
|
|
|
|
// Initialize the form when replying to or forwarding an email
|
|
useEffect(() => {
|
|
if (initialEmail && type !== 'new') {
|
|
// If it's a forward, use the same approach as Panel 3
|
|
if (type === 'forward') {
|
|
initializeForwardedEmail();
|
|
} else {
|
|
// For reply/reply-all, continue using formatEmailForReplyOrForward
|
|
const formattedEmail = formatEmailForReplyOrForward(initialEmail, type as 'reply' | 'reply-all');
|
|
|
|
setTo(formattedEmail.to);
|
|
|
|
if (formattedEmail.cc) {
|
|
setCc(formattedEmail.cc);
|
|
setShowCc(true);
|
|
}
|
|
|
|
setSubject(formattedEmail.subject);
|
|
setBody(formattedEmail.body);
|
|
}
|
|
|
|
// Focus editor after initializing
|
|
setTimeout(() => {
|
|
if (editorRef.current) {
|
|
editorRef.current.focus();
|
|
|
|
// Place cursor at the beginning of the content
|
|
const selection = window.getSelection();
|
|
const range = document.createRange();
|
|
|
|
range.setStart(editorRef.current, 0);
|
|
range.collapse(true);
|
|
|
|
selection?.removeAllRanges();
|
|
selection?.addRange(range);
|
|
}
|
|
}, 100);
|
|
}
|
|
}, [initialEmail, type]);
|
|
|
|
// Helper functions for formatting the forwarded message - moved outside try block
|
|
|
|
// Format date for the forwarded message header
|
|
const formatDate = (date: Date | null): string => {
|
|
if (!date) return '';
|
|
try {
|
|
return date.toLocaleString('en-US', {
|
|
weekday: 'short',
|
|
year: 'numeric',
|
|
month: 'short',
|
|
day: 'numeric',
|
|
hour: '2-digit',
|
|
minute: '2-digit'
|
|
});
|
|
} catch (e) {
|
|
return date.toString();
|
|
}
|
|
};
|
|
|
|
// Format sender address in a readable format
|
|
const formatSender = (from: Array<{name?: string, address: string}> | undefined): string => {
|
|
if (!from || from.length === 0) return 'Unknown';
|
|
return from.map(sender =>
|
|
sender.name && sender.name !== sender.address
|
|
? `${sender.name} <${sender.address}>`
|
|
: sender.address
|
|
).join(', ');
|
|
};
|
|
|
|
// Format recipient addresses in a readable format
|
|
const formatRecipients = (recipients: Array<{name?: string, address: string}> | undefined): string => {
|
|
if (!recipients || recipients.length === 0) return '';
|
|
return recipients.map(recipient =>
|
|
recipient.name && recipient.name !== recipient.address
|
|
? `${recipient.name} <${recipient.address}>`
|
|
: recipient.address
|
|
).join(', ');
|
|
};
|
|
|
|
// Handle editor input
|
|
const handleEditorInput = (e: React.FormEvent<HTMLDivElement>) => {
|
|
// Only store the content of the editable area, not the entire HTML with CSS
|
|
// This prevents breaking complex CSS when editing
|
|
if (editorRef.current) {
|
|
// If we're in forward mode and the editor contains our wrapper structure
|
|
const editableContent = editorRef.current.querySelector('.editable-content');
|
|
if (type === 'forward' && editableContent) {
|
|
// Only update the editable portion, preserving the CSS and header
|
|
const headerSection = editorRef.current.querySelector('.forwarded-header');
|
|
const styleSection = editorRef.current.querySelector('.email-styles');
|
|
|
|
// Combine the preserved sections with the updated editable content
|
|
const updatedContent = (styleSection?.outerHTML || '') +
|
|
(headerSection?.outerHTML || '') +
|
|
editableContent.innerHTML;
|
|
setBody(updatedContent);
|
|
} else {
|
|
// For new emails or replies, we can use the entire content
|
|
setBody(e.currentTarget.innerHTML);
|
|
}
|
|
}
|
|
};
|
|
|
|
// Modified initializeForwardedEmail to separate CSS from content
|
|
const initializeForwardedEmail = async () => {
|
|
if (!initialEmail) {
|
|
console.error('No email available for forwarding');
|
|
setBody('<div style="color: #666; font-style: italic;">No email available for forwarding</div>');
|
|
return;
|
|
}
|
|
|
|
// Helper functions remain the same
|
|
try {
|
|
setSending(true); // Use sending state to show loading
|
|
|
|
// Format subject with Fwd: prefix if needed
|
|
const cleanSubject = initialEmail.subject.replace(/^(Fwd|FW|Forward):\s*/i, '').trim();
|
|
const formattedSubject = initialEmail.subject.match(/^(Fwd|FW|Forward):/i)
|
|
? initialEmail.subject
|
|
: `Fwd: ${cleanSubject}`;
|
|
|
|
setSubject(formattedSubject);
|
|
|
|
// Create a forwarded message header with proper formatting
|
|
const headerContent = `
|
|
<div class="forwarded-header" contenteditable="false" style="border-bottom: 1px solid #e2e2e2; margin-bottom: 15px; padding-bottom: 15px; font-family: Arial, sans-serif; color: #333;">
|
|
<p style="margin: 5px 0; font-size: 14px;">---------- Forwarded message ---------</p>
|
|
<p style="margin: 5px 0; font-size: 14px;"><b>From:</b> ${formatSender(initialEmail.from)}</p>
|
|
<p style="margin: 5px 0; font-size: 14px;"><b>Date:</b> ${formatDate(initialEmail.date)}</p>
|
|
<p style="margin: 5px 0; font-size: 14px;"><b>Subject:</b> ${initialEmail.subject || ''}</p>
|
|
<p style="margin: 5px 0; font-size: 14px;"><b>To:</b> ${formatRecipients(initialEmail.to)}</p>
|
|
</div>`;
|
|
|
|
// Process content
|
|
let contentBody = '';
|
|
let styleContent = '';
|
|
|
|
// Check if email content exists
|
|
if (!initialEmail.content || initialEmail.content.trim() === '') {
|
|
contentBody = '<div class="editable-content" style="color: #666; font-style: italic; margin-top: 10px;">No content available</div>';
|
|
} else {
|
|
try {
|
|
// Parse content to extract styles and make content editable
|
|
const content = initialEmail.content;
|
|
|
|
// Extract style tags to preserve them
|
|
const styleRegex = /<style[^>]*>([\s\S]*?)<\/style>/gi;
|
|
const styles: string[] = [];
|
|
let styleMatch;
|
|
|
|
// Find all style tags and collect them
|
|
while ((styleMatch = styleRegex.exec(content)) !== null) {
|
|
styles.push(styleMatch[0]);
|
|
}
|
|
|
|
// Combine all styles into one non-editable section
|
|
if (styles.length > 0) {
|
|
styleContent = `<div class="email-styles" contenteditable="false">${styles.join('')}</div>`;
|
|
}
|
|
|
|
// Use DOMPurify to sanitize the rest of the HTML content
|
|
const sanitizedContent = DOMPurify.sanitize(content, {
|
|
ADD_TAGS: ['style', 'meta', 'link', 'table', 'thead', 'tbody', 'tr', 'td', 'th', 'hr', 'font', 'div', 'span', 'a', 'img', 'b', 'strong', 'i', 'em', 'u', 'br', 'p', 'ul', 'ol', 'li', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'pre', 'code', 'center', 'section', 'header', 'footer', 'article', 'nav', 'keyframes'],
|
|
ADD_ATTR: ['*', 'colspan', 'rowspan', 'cellpadding', 'cellspacing', 'border', 'bgcolor', 'width', 'height', 'align', 'valign', 'class', 'id', 'style', 'color', 'face', 'size', 'background', 'src', 'href', 'target', 'rel', 'alt', 'title', 'name', 'animation', 'animation-name', 'animation-duration', 'animation-fill-mode'],
|
|
ALLOW_UNKNOWN_PROTOCOLS: true,
|
|
WHOLE_DOCUMENT: true,
|
|
KEEP_CONTENT: true,
|
|
FORBID_TAGS: ['script', 'iframe', 'object', 'embed', 'form', 'input', 'button', 'select', 'option', 'textarea', 'canvas', 'video', 'audio'],
|
|
FORBID_ATTR: ['onerror', 'onload', 'onclick', 'onmouseover', 'onmouseout', 'onchange', 'onsubmit'],
|
|
USE_PROFILES: { html: true, svg: false, svgFilters: false, mathMl: false },
|
|
FORCE_BODY: true
|
|
});
|
|
|
|
// Remove style tags from sanitized content (we'll add them back separately)
|
|
let contentWithoutStyles = sanitizedContent.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '');
|
|
|
|
// Wrap the remaining content in an editable div
|
|
contentBody = `<div class="editable-content">${contentWithoutStyles}</div>`;
|
|
} catch (e) {
|
|
console.error('Error sanitizing HTML content:', e);
|
|
contentBody = '<div class="editable-content" style="color: #666; font-style: italic; margin-top: 10px;">Error processing original content</div>';
|
|
}
|
|
}
|
|
|
|
// Set the complete forwarded email with styles preserved separately
|
|
setBody(styleContent + headerContent + contentBody);
|
|
} catch (error) {
|
|
console.error('Error initializing forwarded email:', error);
|
|
// Still provide the headers even if there's an error with the content
|
|
const errorHeaderContent = `
|
|
<div class="forwarded-header" contenteditable="false" style="border-bottom: 1px solid #e2e2e2; margin-bottom: 15px; padding-bottom: 15px; font-family: Arial, sans-serif; color: #333;">
|
|
<p style="margin: 5px 0; font-size: 14px;">---------- Forwarded message ---------</p>
|
|
<p style="margin: 5px 0; font-size: 14px;"><b>From:</b> ${initialEmail.from ? formatSender(initialEmail.from) : 'Unknown'}</p>
|
|
<p style="margin: 5px 0; font-size: 14px;"><b>Date:</b> ${initialEmail.date ? formatDate(initialEmail.date) : ''}</p>
|
|
<p style="margin: 5px 0; font-size: 14px;"><b>Subject:</b> ${initialEmail.subject || ''}</p>
|
|
<p style="margin: 5px 0; font-size: 14px;"><b>To:</b> ${initialEmail.to ? formatRecipients(initialEmail.to) : ''}</p>
|
|
</div>
|
|
<div class="editable-content" style="color: #ef4444; font-style: italic; margin-top: 10px;">Error loading forwarded content</div>`;
|
|
setBody(errorHeaderContent);
|
|
} finally {
|
|
setSending(false);
|
|
}
|
|
};
|
|
|
|
// Handle attachment selection
|
|
const handleAttachmentClick = () => {
|
|
attachmentInputRef.current?.click();
|
|
};
|
|
|
|
// Process selected files
|
|
const handleFileSelection = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
const files = e.target.files;
|
|
if (!files || files.length === 0) return;
|
|
|
|
// Convert selected files to attachments
|
|
const newAttachments = Array.from(files).map(file => ({
|
|
file,
|
|
uploading: true
|
|
}));
|
|
|
|
// Read files as data URLs
|
|
for (const file of files) {
|
|
const reader = new FileReader();
|
|
|
|
reader.onload = (event) => {
|
|
const content = event.target?.result as string;
|
|
|
|
setAttachments(current => [
|
|
...current,
|
|
{
|
|
name: file.name,
|
|
content: content.split(',')[1], // Remove data:mime/type;base64, prefix
|
|
type: file.type
|
|
}
|
|
]);
|
|
};
|
|
|
|
reader.readAsDataURL(file);
|
|
}
|
|
|
|
// Reset file input
|
|
if (e.target) {
|
|
e.target.value = '';
|
|
}
|
|
};
|
|
|
|
// Remove attachment
|
|
const removeAttachment = (index: number) => {
|
|
setAttachments(current => current.filter((_, i) => i !== index));
|
|
};
|
|
|
|
// Send the email
|
|
const handleSend = async () => {
|
|
if (!to) {
|
|
alert('Please specify at least one recipient');
|
|
return;
|
|
}
|
|
|
|
try {
|
|
setSending(true);
|
|
|
|
// Get the email content
|
|
let emailBody = '';
|
|
if (editorRef.current) {
|
|
// For forwarded emails, make sure to include both the style and content sections
|
|
if (type === 'forward') {
|
|
// Gather all parts: styles, header, and editable content
|
|
const styleSection = editorRef.current.querySelector('.email-styles');
|
|
const headerSection = editorRef.current.querySelector('.forwarded-header');
|
|
const editableContent = editorRef.current.querySelector('.editable-content');
|
|
|
|
// Combine all sections for the final email body
|
|
emailBody =
|
|
(styleSection?.outerHTML || '') +
|
|
(headerSection?.outerHTML || '') +
|
|
(editableContent?.innerHTML || editorRef.current.innerHTML);
|
|
|
|
// Remove contenteditable attributes as they're not needed in the sent email
|
|
emailBody = emailBody.replace(/contenteditable="[^"]*"/g, '');
|
|
} else {
|
|
// For new emails or replies, use the entire content
|
|
emailBody = editorRef.current.innerHTML;
|
|
}
|
|
} else {
|
|
// Fallback to using body state
|
|
emailBody = body;
|
|
}
|
|
|
|
await onSend({
|
|
to,
|
|
cc: cc || undefined,
|
|
bcc: bcc || undefined,
|
|
subject,
|
|
body: emailBody,
|
|
attachments
|
|
});
|
|
|
|
onClose();
|
|
} catch (error) {
|
|
console.error('Error sending email:', error);
|
|
alert('Failed to send email. Please try again.');
|
|
} finally {
|
|
setSending(false);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<Card className="w-full h-full flex flex-col overflow-hidden shadow-lg">
|
|
<CardHeader className="border-b py-2 px-4">
|
|
<div className="flex justify-between items-center">
|
|
<CardTitle className="text-lg">
|
|
{type === 'new' ? 'New Message' :
|
|
type === 'reply' ? 'Reply' :
|
|
type === 'reply-all' ? 'Reply All' :
|
|
'Forward'}
|
|
</CardTitle>
|
|
<Button variant="ghost" size="icon" onClick={onClose}>
|
|
<X className="h-4 w-4" />
|
|
</Button>
|
|
</div>
|
|
</CardHeader>
|
|
|
|
<CardContent className="p-0 flex-1 flex flex-col overflow-hidden">
|
|
{/* Email header fields */}
|
|
<div className="p-3 border-b space-y-2">
|
|
<div className="flex items-center">
|
|
<span className="w-16 text-sm font-medium">To:</span>
|
|
<Input
|
|
value={to}
|
|
onChange={(e) => setTo(e.target.value)}
|
|
className="flex-1 border-0 shadow-none h-8 focus-visible:ring-0"
|
|
placeholder="recipient@example.com"
|
|
/>
|
|
</div>
|
|
|
|
{showCc && (
|
|
<div className="flex items-center">
|
|
<span className="w-16 text-sm font-medium">Cc:</span>
|
|
<Input
|
|
value={cc}
|
|
onChange={(e) => setCc(e.target.value)}
|
|
className="flex-1 border-0 shadow-none h-8 focus-visible:ring-0"
|
|
placeholder="cc@example.com"
|
|
/>
|
|
</div>
|
|
)}
|
|
|
|
{showBcc && (
|
|
<div className="flex items-center">
|
|
<span className="w-16 text-sm font-medium">Bcc:</span>
|
|
<Input
|
|
value={bcc}
|
|
onChange={(e) => setBcc(e.target.value)}
|
|
className="flex-1 border-0 shadow-none h-8 focus-visible:ring-0"
|
|
placeholder="bcc@example.com"
|
|
/>
|
|
</div>
|
|
)}
|
|
|
|
{/* CC/BCC controls */}
|
|
<div className="flex items-center text-xs">
|
|
<button
|
|
className="text-primary hover:underline mr-3 flex items-center"
|
|
onClick={() => setShowCc(!showCc)}
|
|
>
|
|
{showCc ? (
|
|
<>
|
|
<ChevronUp className="h-3 w-3 mr-0.5" />
|
|
Hide Cc
|
|
</>
|
|
) : (
|
|
<>
|
|
<ChevronDown className="h-3 w-3 mr-0.5" />
|
|
Show Cc
|
|
</>
|
|
)}
|
|
</button>
|
|
|
|
<button
|
|
className="text-primary hover:underline flex items-center"
|
|
onClick={() => setShowBcc(!showBcc)}
|
|
>
|
|
{showBcc ? (
|
|
<>
|
|
<ChevronUp className="h-3 w-3 mr-0.5" />
|
|
Hide Bcc
|
|
</>
|
|
) : (
|
|
<>
|
|
<ChevronDown className="h-3 w-3 mr-0.5" />
|
|
Show Bcc
|
|
</>
|
|
)}
|
|
</button>
|
|
</div>
|
|
|
|
<div className="flex items-center">
|
|
<span className="w-16 text-sm font-medium">Subject:</span>
|
|
<Input
|
|
value={subject}
|
|
onChange={(e) => setSubject(e.target.value)}
|
|
className="flex-1 border-0 shadow-none h-8 focus-visible:ring-0"
|
|
placeholder="Subject"
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Email body editor */}
|
|
<div
|
|
ref={editorRef}
|
|
className="flex-1 overflow-auto p-4 focus:outline-none email-content"
|
|
contentEditable={true}
|
|
onInput={handleEditorInput}
|
|
dangerouslySetInnerHTML={{ __html: body }}
|
|
style={{ minHeight: '200px' }}
|
|
/>
|
|
|
|
{/* Attachments list */}
|
|
{attachments.length > 0 && (
|
|
<div className="border-t p-2">
|
|
<div className="text-sm font-medium mb-1">Attachments:</div>
|
|
<div className="flex flex-wrap gap-2">
|
|
{attachments.map((attachment, index) => (
|
|
<div key={index} className="flex items-center gap-1 text-sm bg-muted px-2 py-1 rounded">
|
|
<Paperclip className="h-3 w-3" />
|
|
<span>{attachment.name}</span>
|
|
<button
|
|
onClick={() => removeAttachment(index)}
|
|
className="ml-1 text-muted-foreground hover:text-destructive"
|
|
>
|
|
<X className="h-3 w-3" />
|
|
</button>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</div>
|
|
)}
|
|
</CardContent>
|
|
|
|
<CardFooter className="border-t p-3 flex justify-between">
|
|
<div>
|
|
<input
|
|
type="file"
|
|
ref={attachmentInputRef}
|
|
className="hidden"
|
|
onChange={handleFileSelection}
|
|
multiple
|
|
/>
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
onClick={handleAttachmentClick}
|
|
>
|
|
<Paperclip className="h-4 w-4 mr-1" />
|
|
Attach
|
|
</Button>
|
|
</div>
|
|
|
|
<Button
|
|
size="sm"
|
|
onClick={handleSend}
|
|
disabled={sending}
|
|
>
|
|
{sending ? (
|
|
<>
|
|
<Loader2 className="h-4 w-4 mr-1 animate-spin" />
|
|
Sending...
|
|
</>
|
|
) : (
|
|
<>
|
|
<SendHorizontal className="h-4 w-4 mr-1" />
|
|
Send
|
|
</>
|
|
)}
|
|
</Button>
|
|
</CardFooter>
|
|
</Card>
|
|
);
|
|
}
|