NeahNew/components/email/ComposeEmail.tsx
2025-05-03 14:17:46 +02:00

626 lines
22 KiB
TypeScript

'use client';
import { useState, useRef, useEffect } from 'react';
import {
X, Paperclip, SendHorizontal, Loader2, Plus, ChevronDown
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import DOMPurify from 'isomorphic-dompurify';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import RichEmailEditor from '@/components/email/RichEmailEditor';
import { detectTextDirection } from '@/lib/utils/text-direction';
// Import from the centralized utils
import {
formatReplyEmail,
formatForwardedEmail
} from '@/lib/utils/email-utils';
import { EmailMessage } from '@/types/email';
/**
* Email composer component
* Handles new emails, replies, and forwards with a clean UI
*/
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;
fromAccount?: string;
attachments?: Array<{
name: string;
content: string;
type: string;
}>;
}) => Promise<void>;
accounts?: Array<{
id: string;
email: string;
display_name?: string;
}>;
}
export default function ComposeEmail(props: ComposeEmailProps) {
const { initialEmail, type = 'new', onClose, onSend, accounts = [] } = props;
// State for email form
const [selectedAccount, setSelectedAccount] = useState<any>(accounts[0]);
const [to, setTo] = useState('');
const [cc, setCc] = useState('');
const [bcc, setBcc] = useState('');
const [subject, setSubject] = useState('');
const [emailContent, setEmailContent] = useState('');
const [showCc, setShowCc] = useState(false);
const [showBcc, setShowBcc] = useState(false);
const [sending, setSending] = useState(false);
const [attachments, setAttachments] = useState<Array<{name: string; content: string; type: string;}>>([]);
// Reference to editor
const editorRef = useRef<HTMLDivElement>(null);
// Helper function to get formatted info from email
function getFormattedInfoForEmail(email: any) {
// Format the subject
const subject = email.subject || '';
// Format the date
const dateStr = email.date ? new Date(email.date).toLocaleString() : 'Unknown Date';
// Format sender
const fromStr = Array.isArray(email.from)
? email.from.map((addr: any) => {
if (typeof addr === 'string') return addr;
return addr.name ? `${addr.name} <${addr.address}>` : addr.address;
}).join(', ')
: typeof email.from === 'string'
? email.from
: email.from?.address
? email.from.name
? `${email.from.name} <${email.from.address}>`
: email.from.address
: 'Unknown Sender';
// Format recipients
const toStr = Array.isArray(email.to)
? email.to.map((addr: any) => {
if (typeof addr === 'string') return addr;
return addr.name ? `${addr.name} <${addr.address}>` : addr.address;
}).join(', ')
: typeof email.to === 'string'
? email.to
: '';
// Format CC
const ccStr = Array.isArray(email.cc)
? email.cc.map((addr: any) => {
if (typeof addr === 'string') return addr;
return addr.name ? `${addr.name} <${addr.address}>` : addr.address;
}).join(', ')
: typeof email.cc === 'string'
? email.cc
: '';
return { fromStr, toStr, ccStr, dateStr, subject };
}
// Initialize email form based on initial email and type
useEffect(() => {
if (initialEmail) {
try {
console.log('Initializing compose with email:', {
id: initialEmail.id,
subject: initialEmail.subject,
hasContent: !!initialEmail.content,
contentType: initialEmail.content ? typeof initialEmail.content : 'none'
});
// Set default account from original email - use type assertion since accountId might be custom property
const emailAny = initialEmail as any;
if (emailAny.accountId && accounts?.length) {
const account = accounts.find(a => a.id === emailAny.accountId);
if (account) {
setSelectedAccount(account);
}
}
// Get recipients based on type
if (type === 'reply' || type === 'reply-all') {
// Get formatted data for reply
const formatted = formatReplyEmail(initialEmail, type);
// Set reply addresses
setTo(formatted.to);
if (formatted.cc) {
setShowCc(true);
setCc(formatted.cc);
}
// Set subject
setSubject(formatted.subject);
// Set content with original email - ensure we have content
const content = formatted.content.html || formatted.content.text || '';
if (!content) {
console.warn('Reply content is empty, falling back to a basic template');
// Provide a basic template if the content is empty
const { fromStr, dateStr } = getFormattedInfoForEmail(initialEmail);
const fallbackContent = `
<div style="margin: 20px 0 10px 0; color: #666; border-bottom: 1px solid #ddd; padding-bottom: 5px;">
On ${dateStr}, ${fromStr} wrote:
</div>
<blockquote style="margin: 0; padding-left: 10px; border-left: 3px solid #ddd; color: #505050; background-color: #f9f9f9; padding: 10px;">
[Original message content could not be loaded]
</blockquote>
`;
setEmailContent(fallbackContent);
} else {
console.log('Setting reply content:', {
length: content.length,
isHtml: formatted.content.isHtml,
startsWithHtml: content.trim().startsWith('<'),
contentType: typeof content
});
setEmailContent(content);
}
// Handle any attachments from reply (e.g., inline images extracted as attachments)
if (formatted.attachments && formatted.attachments.length > 0) {
const formattedAttachments = formatted.attachments.map(att => ({
name: att.filename || 'attachment',
type: att.contentType || 'application/octet-stream',
content: att.content || ''
}));
setAttachments(formattedAttachments);
}
}
else if (type === 'forward') {
// Get formatted data for forward
const formatted = formatForwardedEmail(initialEmail);
// Set subject
setSubject(formatted.subject);
// Set content with original email - ensure we have content
const content = formatted.content.html || formatted.content.text || '';
if (!content) {
console.warn('Forward content is empty, falling back to a basic template');
// Provide a basic template if the content is empty
const { fromStr, dateStr, subject: origSubject, toStr, ccStr } = getFormattedInfoForEmail(initialEmail);
console.log('Creating forward fallback with:', { fromStr, dateStr, origSubject });
const fallbackContent = `
<div style="margin: 20px 0 10px 0; color: #666; font-family: Arial, sans-serif;">
<div style="border-bottom: 1px solid #ccc; margin-bottom: 10px; padding-bottom: 5px;">
<div>---------------------------- Forwarded Message ----------------------------</div>
</div>
<table style="margin-bottom: 10px; font-size: 14px;">
<tr>
<td style="padding: 3px 10px 3px 0; font-weight: bold; text-align: right; vertical-align: top;">From:</td>
<td style="padding: 3px 0;">${fromStr}</td>
</tr>
<tr>
<td style="padding: 3px 10px 3px 0; font-weight: bold; text-align: right; vertical-align: top;">Date:</td>
<td style="padding: 3px 0;">${dateStr}</td>
</tr>
<tr>
<td style="padding: 3px 10px 3px 0; font-weight: bold; text-align: right; vertical-align: top;">Subject:</td>
<td style="padding: 3px 0;">${origSubject || ''}</td>
</tr>
<tr>
<td style="padding: 3px 10px 3px 0; font-weight: bold; text-align: right; vertical-align: top;">To:</td>
<td style="padding: 3px 0;">${toStr}</td>
</tr>
${ccStr ? `
<tr>
<td style="padding: 3px 10px 3px 0; font-weight: bold; text-align: right; vertical-align: top;">Cc:</td>
<td style="padding: 3px 0;">${ccStr}</td>
</tr>` : ''}
</table>
<div style="border-bottom: 1px solid #ccc; margin-top: 5px; margin-bottom: 15px; padding-bottom: 5px;">
<div>----------------------------------------------------------------------</div>
</div>
</div>
<div class="forwarded-content" style="margin: 0; color: #333;">
[Original message content could not be loaded]
</div>
`;
setEmailContent(fallbackContent);
} else {
console.log('Setting forward content:', {
length: content.length,
isHtml: formatted.content.isHtml
});
setEmailContent(content);
}
// Handle attachments for forward (original attachments + extracted inline images)
if (formatted.attachments && formatted.attachments.length > 0) {
console.log(`Processing ${formatted.attachments.length} attachments for forwarded email`);
const formattedAttachments = formatted.attachments.map(att => ({
name: att.filename || 'attachment',
type: att.contentType || 'application/octet-stream',
content: att.content || ''
}));
setAttachments(formattedAttachments);
}
}
} catch (error) {
console.error('Error initializing compose form:', error);
// Provide a fallback in case of error
setEmailContent('<p>Error loading email content</p>');
}
}
}, [initialEmail, type, accounts]);
// Place cursor at beginning and ensure content is scrolled to top
useEffect(() => {
if (editorRef.current && type !== 'new') {
// Small delay to ensure DOM is ready
setTimeout(() => {
if (editorRef.current) {
// Focus the editor
editorRef.current.focus();
// Also make sure editor container is scrolled to top
editorRef.current.scrollTop = 0;
// Find parent scrollable containers and scroll them to top
let parent = editorRef.current.parentElement;
while (parent) {
if (parent.classList.contains('overflow-y-auto')) {
parent.scrollTop = 0;
}
parent = parent.parentElement;
}
}
}, 100);
}
}, [emailContent, type]);
// Handle file attachments
const handleAttachmentAdd = async (files: FileList) => {
const newAttachments = Array.from(files).map(file => ({
name: file.name,
type: file.type,
content: URL.createObjectURL(file)
}));
setAttachments(prev => [...prev, ...newAttachments]);
};
const handleAttachmentRemove = (index: number) => {
setAttachments(prev => prev.filter((_, i) => i !== index));
};
// Handle sending email
const handleSend = async () => {
if (!to) {
alert('Please specify at least one recipient');
return;
}
setSending(true);
try {
await onSend({
to,
cc: cc || undefined,
bcc: bcc || undefined,
subject,
body: emailContent,
fromAccount: selectedAccount?.id,
attachments
});
// Reset form and close
onClose();
} catch (error) {
console.error('Error sending email:', error);
alert('Failed to send email. Please try again.');
} finally {
setSending(false);
}
};
// Get compose title based on type
const getComposeTitle = () => {
switch(type) {
case 'reply': return 'Reply';
case 'reply-all': return 'Reply All';
case 'forward': return 'Forward';
default: return 'New Message';
}
};
return (
<div className="flex flex-col h-full max-h-[80vh] bg-white border rounded-md shadow-md">
{/* Header */}
<div className="flex items-center justify-between p-3 border-b bg-gray-50">
<h2 className="text-lg font-medium text-gray-800">{getComposeTitle()}</h2>
<Button variant="ghost" size="icon" onClick={onClose}>
<X className="h-5 w-5" />
</Button>
</div>
{/* Email Form */}
<div className="flex-1 overflow-y-auto bg-white">
<div className="p-2 space-y-2">
{/* From */}
<div className="border-b pb-1">
<div className="flex items-center">
<span className="w-16 text-gray-700 text-sm font-medium">From:</span>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="outline"
className="w-full flex justify-between items-center h-8 px-2 py-1 text-left font-normal bg-white text-gray-800 border-gray-200"
>
<span className="truncate">
{selectedAccount ?
(selectedAccount.display_name ?
`${selectedAccount.display_name} <${selectedAccount.email}>` :
selectedAccount.email) :
'Select account'}
</span>
<ChevronDown className="h-4 w-4 opacity-50" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-[240px]">
<DropdownMenuLabel>Select account</DropdownMenuLabel>
<DropdownMenuSeparator />
{accounts.length > 0 ? (
accounts.map(account => (
<DropdownMenuItem
key={account.id}
onClick={() => setSelectedAccount(account)}
className="cursor-pointer hover:bg-blue-50 focus:bg-blue-50"
>
{account.display_name ?
`${account.display_name} <${account.email}>` :
account.email}
</DropdownMenuItem>
))
) : (
<DropdownMenuItem disabled>No accounts available</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
{/* Recipients */}
<div className="border-b pb-1">
<div className="flex items-center">
<span className="w-16 text-gray-700 text-sm font-medium">To:</span>
<Input
type="text"
value={to}
onChange={(e) => setTo(e.target.value)}
placeholder="recipient@example.com"
className="flex-1 border-0 shadow-none focus-visible:ring-0 px-0 h-8 bg-white text-gray-800"
/>
</div>
{showCc && (
<div className="flex items-center">
<span className="w-16 text-gray-700 text-sm font-medium">Cc:</span>
<Input
type="text"
value={cc}
onChange={(e) => setCc(e.target.value)}
placeholder="cc@example.com"
className="flex-1 border-0 shadow-none focus-visible:ring-0 px-0 h-8 bg-white text-gray-800"
/>
</div>
)}
{showBcc && (
<div className="flex items-center">
<span className="w-16 text-gray-700 text-sm font-medium">Bcc:</span>
<Input
type="text"
value={bcc}
onChange={(e) => setBcc(e.target.value)}
placeholder="bcc@example.com"
className="flex-1 border-0 shadow-none focus-visible:ring-0 px-0 h-8 bg-white text-gray-800"
/>
</div>
)}
{/* CC/BCC Toggle Links */}
<div className="flex gap-3 ml-16">
{!showCc && (
<button
className="text-blue-600 text-sm hover:underline"
onClick={() => setShowCc(true)}
>
Add Cc
</button>
)}
{!showBcc && (
<button
className="text-blue-600 text-sm hover:underline"
onClick={() => setShowBcc(true)}
>
Add Bcc
</button>
)}
</div>
</div>
{/* Subject */}
<div className="border-b pb-1">
<div className="flex items-center">
<span className="w-16 text-gray-700 text-sm font-medium">Subject:</span>
<Input
type="text"
value={subject}
onChange={(e) => setSubject(e.target.value)}
placeholder="Subject"
className="flex-1 border-0 shadow-none focus-visible:ring-0 px-0 h-8 bg-white text-gray-800"
/>
</div>
</div>
{/* Message Body */}
<RichEmailEditor
initialContent={emailContent}
onChange={(html) => {
setEmailContent(html);
}}
placeholder="Write your message here..."
minHeight="320px"
/>
{/* Attachments */}
{attachments.length > 0 && (
<div className="p-2 border rounded-md bg-gray-50">
<div className="text-sm font-medium mb-1 text-gray-700">Attachments:</div>
{attachments.map((file, index) => (
<div key={index} className="flex items-center justify-between text-sm py-1">
<span className="truncate mr-2 text-gray-800">{file.name}</span>
<Button
variant="ghost"
size="sm"
onClick={() => handleAttachmentRemove(index)}
className="h-6 w-6 p-0"
>
<X className="h-4 w-4" />
</Button>
</div>
))}
</div>
)}
</div>
</div>
{/* Footer */}
<div className="border-t p-3 flex items-center justify-between bg-gray-50">
<div className="flex items-center gap-2">
{/* File Input for Attachments - simpler version */}
<input
type="file"
id="file-attachment"
className="hidden"
multiple
onChange={(e) => {
if (e.target.files && e.target.files.length > 0) {
handleAttachmentAdd(e.target.files);
}
}}
/>
<label htmlFor="file-attachment" className="cursor-pointer">
<Button
variant="ghost"
size="sm"
className="p-1 text-gray-700 hover:bg-gray-100"
title="Attach files"
>
<Paperclip className="h-5 w-5" />
</Button>
</label>
</div>
<div className="flex items-center gap-2">
<Button
variant="default"
onClick={onClose}
className="bg-red-600 hover:bg-red-700 text-white"
>
Cancel
</Button>
<Button
variant="default"
onClick={handleSend}
disabled={sending}
className="bg-blue-600 hover:bg-blue-700 text-white"
>
{sending ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Sending
</>
) : (
<>
<SendHorizontal className="mr-2 h-4 w-4" />
Send
</>
)}
</Button>
</div>
</div>
{/* Styles for email content */}
<style jsx global>{`
[contenteditable] {
-webkit-user-modify: read-write-plaintext-only;
overflow-wrap: break-word;
-webkit-line-break: after-white-space;
-webkit-user-select: text;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, sans-serif;
font-size: 14px;
line-height: 1.5;
color: #333;
background-color: #fff;
}
[contenteditable]:focus {
outline: none;
}
[contenteditable] blockquote {
margin: 10px 0;
padding-left: 15px;
border-left: 2px solid #ddd;
color: #666;
}
[contenteditable] img {
max-width: 100%;
height: auto;
}
[contenteditable] table {
border-collapse: collapse;
width: 100%;
max-width: 100%;
margin-bottom: 1rem;
}
[contenteditable] th,
[contenteditable] td {
padding: 5px;
border: 1px solid #ddd;
}
[contenteditable] th {
background-color: #f8f9fa;
font-weight: 600;
text-align: left;
}
/* Forwarded message styles */
.email-original-content {
margin-top: 20px;
color: #505050;
}
`}</style>
</div>
);
}