Neah/components/email/ComposeEmail.tsx

551 lines
19 KiB
TypeScript

'use client';
import { useState, useRef, useEffect } from 'react';
import { formatEmailForReplyOrForward, EmailMessage, EmailAddress } 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 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>('');
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;
}>>([]);
// Refs
const editorRef = useRef<HTMLDivElement>(null);
const attachmentInputRef = useRef<HTMLInputElement>(null);
// Initialize the form when replying to or forwarding an email
useEffect(() => {
if (initialEmail && type !== 'new') {
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]);
// 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(', ');
};
// Initialize forwarded email with clear structure and style preservation
const initializeForwardedEmail = async () => {
console.log('Starting initializeForwardedEmail');
if (!initialEmail) {
console.error('No email available for forwarding');
setBody('<div style="color: #666; font-style: italic;">No email available for forwarding</div>');
return;
}
// Debug the email object structure
console.log('Forwarding email object:', {
id: initialEmail.id,
subject: initialEmail.subject,
fromLength: initialEmail.from?.length,
from: initialEmail.from,
to: initialEmail.to,
date: initialEmail.date,
hasContent: Boolean(initialEmail.content),
contentLength: initialEmail.content?.length,
hasHtml: Boolean(initialEmail.html),
htmlLength: initialEmail.html?.length
});
try {
// Format subject with Fwd: prefix if needed
const subjectBase = initialEmail.subject || '(No subject)';
const subjectRegex = /^(Fwd|FW|Forward):\s*/i;
const subject = subjectRegex.test(subjectBase)
? subjectBase
: `Fwd: ${subjectBase}`;
setSubject(subject);
// Format the forwarded message with a well-structured header
const fromString = Array.isArray(initialEmail.from) && initialEmail.from.length > 0
? initialEmail.from.map(addr => addr.name
? `${addr.name} <${addr.address}>`
: addr.address).join(', ')
: 'Unknown';
const toString = Array.isArray(initialEmail.to) && initialEmail.to.length > 0
? initialEmail.to.map(addr => addr.name
? `${addr.name} <${addr.address}>`
: addr.address).join(', ')
: '';
const dateString = initialEmail.date
? typeof initialEmail.date === 'string'
? new Date(initialEmail.date).toLocaleString()
: initialEmail.date.toLocaleString()
: new Date().toLocaleString();
// Create a clean wrapper that won't interfere with the original email's styling
// Use inline styles for the header to avoid CSS conflicts
const headerHtml = `
<div style="border-top: 1px solid #e1e1e1; margin-top: 20px; padding-top: 15px; font-family: Arial, sans-serif; color: #333;">
<div style="margin-bottom: 15px;">
<div style="font-weight: normal; margin-bottom: 10px;">---------- Forwarded message ---------</div>
<div><b>From:</b> ${fromString}</div>
<div><b>Date:</b> ${dateString}</div>
<div><b>Subject:</b> ${subjectBase}</div>
<div><b>To:</b> ${toString}</div>
</div>
</div>
`;
// Process the original content
let originalContent = '';
// First try to use the API to parse and sanitize the email content
try {
// Use server-side parsing via fetch API to properly handle complex emails
const response = await fetch('/api/parse-email', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: initialEmail.content || initialEmail.html || initialEmail.text || ''
}),
});
if (response.ok) {
const parsedEmail = await response.json();
if (parsedEmail.html && parsedEmail.html.trim()) {
console.log('Using parsed HTML content for forward');
// Create an iframe-like containment for the email content
// This prevents CSS from the original email leaking into our compose view
originalContent = `
<div class="email-content-container">
${parsedEmail.html}
</div>
`;
} else if (parsedEmail.text && parsedEmail.text.trim()) {
console.log('Using parsed text content for forward');
originalContent = `<div style="white-space: pre-wrap; font-family: monospace;">${parsedEmail.text}</div>`;
} else {
console.log('No content available from parser');
originalContent = '<div style="color: #666; font-style: italic; padding: 10px; font-size: 14px; border: 1px dashed #ccc; margin: 10px 0; text-align: center; background-color: #f9f9f9;">No content available</div>';
}
} else {
throw new Error('Failed to parse email content');
}
} catch (parseError) {
console.error('Error parsing email content:', parseError);
// Fall back to direct content handling if API parsing fails
if (initialEmail.html && initialEmail.html.trim()) {
console.log('Falling back to HTML content for forward');
// Use DOMPurify to sanitize HTML and remove dangerous elements
originalContent = DOMPurify.sanitize(initialEmail.html, {
ADD_TAGS: ['style', 'div', 'span', 'p', 'br', 'hr', 'h1', 'h2', 'h3', 'img', 'table', 'tr', 'td', 'th'],
ADD_ATTR: ['style', 'class', 'id', 'src', 'alt', 'href', 'target'],
FORBID_TAGS: ['script', 'iframe', 'object', 'embed'],
FORBID_ATTR: ['onerror', 'onload', 'onclick', 'onmouseover']
});
} else if (initialEmail.content && initialEmail.content.trim()) {
console.log('Falling back to content field for forward');
originalContent = DOMPurify.sanitize(initialEmail.content);
} else if (initialEmail.text && initialEmail.text.trim()) {
console.log('Falling back to text content for forward');
originalContent = `<div style="white-space: pre-wrap; font-family: monospace;">${initialEmail.text}</div>`;
} else {
console.log('No content available for forward');
originalContent = '<div style="color: #666; font-style: italic; padding: 10px; font-size: 14px; border: 1px dashed #ccc; margin: 10px 0; text-align: center; background-color: #f9f9f9;">No content available</div>';
}
}
// Preserve all original structure by wrapping, not modifying the original content
// Important: We add a style scope to prevent CSS leakage
const forwardedContent = `
${headerHtml}
<!-- Start original email content - DO NOT MODIFY THIS CONTENT -->
<div class="original-email-content" style="margin-top: 10px; border-left: 2px solid #e1e1e1; padding-left: 15px;">
<!-- Email content styling isolation container -->
<div style="position: relative; overflow: auto;">
${originalContent}
</div>
</div>
<!-- End original email content -->
`;
console.log('Setting body with forwarded content');
setBody(forwardedContent);
} catch (error) {
console.error('Error initializing forwarded email:', error);
// Even in error case, provide a usable template with empty values
setBody(`
<div style="border-top: 1px solid #e1e1e1; margin-top: 20px; padding-top: 15px; font-family: Arial, sans-serif; color: #333;">
<div style="margin-bottom: 15px;">
<div style="font-weight: normal; margin-bottom: 10px;">---------- Forwarded message ---------</div>
<div><b>From:</b> ${initialEmail.from ? formatSender(initialEmail.from) : 'Unknown'}</div>
<div><b>Date:</b> ${new Date().toLocaleString()}</div>
<div><b>Subject:</b> ${initialEmail.subject || '(No subject)'}</div>
<div><b>To:</b> ${initialEmail.to ? formatRecipients(initialEmail.to) : ''}</div>
</div>
</div>
<div style="margin-top: 10px; padding: 10px; color: #d32f2f; font-style: italic; border: 1px dashed #d32f2f; margin: 10px 0; text-align: center; background-color: #fff8f8;">
Error loading original message content. The original message may still be viewable in your inbox.
</div>
`);
}
};
// 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);
await onSend({
to,
cc: cc || undefined,
bcc: bcc || undefined,
subject,
body: editorRef.current?.innerHTML || body,
attachments
});
onClose();
} catch (error) {
console.error('Error sending email:', error);
alert('Failed to send email. Please try again.');
} finally {
setSending(false);
}
};
// Handle editor input
const handleEditorInput = (e: React.FormEvent<HTMLDivElement>) => {
// Store the HTML content for use in the send function
setBody(e.currentTarget.innerHTML);
};
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>
);
}