506 lines
17 KiB
TypeScript
506 lines
17 KiB
TypeScript
'use client';
|
|
|
|
import { useRef, useEffect, useState } from 'react';
|
|
import { Button } from '@/components/ui/button';
|
|
import { Input } from '@/components/ui/input';
|
|
import { Label } from '@/components/ui/label';
|
|
import { Paperclip, X } from 'lucide-react';
|
|
import { Textarea } from '@/components/ui/textarea';
|
|
import { decodeComposeContent, encodeComposeContent } from '@/lib/compose-mime-decoder';
|
|
import { Email } from '@/app/courrier/page';
|
|
import mime from 'mime';
|
|
import { simpleParser } from 'mailparser';
|
|
|
|
interface ComposeEmailProps {
|
|
showCompose: boolean;
|
|
setShowCompose: (show: boolean) => void;
|
|
composeTo: string;
|
|
setComposeTo: (to: string) => void;
|
|
composeCc: string;
|
|
setComposeCc: (cc: string) => void;
|
|
composeBcc: string;
|
|
setComposeBcc: (bcc: string) => void;
|
|
composeSubject: string;
|
|
setComposeSubject: (subject: string) => void;
|
|
composeBody: string;
|
|
setComposeBody: (body: string) => void;
|
|
showCc: boolean;
|
|
setShowCc: (show: boolean) => void;
|
|
showBcc: boolean;
|
|
setShowBcc: (show: boolean) => void;
|
|
attachments: any[];
|
|
setAttachments: (attachments: any[]) => void;
|
|
handleSend: () => Promise<void>;
|
|
originalEmail?: {
|
|
content: string;
|
|
type: 'reply' | 'reply-all' | 'forward';
|
|
};
|
|
onSend: (email: Email) => void;
|
|
onCancel: () => void;
|
|
onBodyChange?: (body: string) => void;
|
|
initialTo?: string;
|
|
initialSubject?: string;
|
|
initialBody?: string;
|
|
initialCc?: string;
|
|
initialBcc?: string;
|
|
replyTo?: Email | null;
|
|
forwardFrom?: Email | null;
|
|
}
|
|
|
|
export default function ComposeEmail({
|
|
showCompose,
|
|
setShowCompose,
|
|
composeTo,
|
|
setComposeTo,
|
|
composeCc,
|
|
setComposeCc,
|
|
composeBcc,
|
|
setComposeBcc,
|
|
composeSubject,
|
|
setComposeSubject,
|
|
composeBody,
|
|
setComposeBody,
|
|
showCc,
|
|
setShowCc,
|
|
showBcc,
|
|
setShowBcc,
|
|
attachments,
|
|
setAttachments,
|
|
handleSend,
|
|
originalEmail,
|
|
onSend,
|
|
onCancel,
|
|
onBodyChange,
|
|
initialTo,
|
|
initialSubject,
|
|
initialBody,
|
|
initialCc,
|
|
initialBcc,
|
|
replyTo,
|
|
forwardFrom
|
|
}: ComposeEmailProps) {
|
|
const composeBodyRef = useRef<HTMLDivElement>(null);
|
|
const [localContent, setLocalContent] = useState('');
|
|
const [isInitialized, setIsInitialized] = useState(false);
|
|
|
|
useEffect(() => {
|
|
if (composeBodyRef.current && !isInitialized) {
|
|
let content = '';
|
|
|
|
if (replyTo || forwardFrom) {
|
|
// Get the original email content
|
|
const originalContent = replyTo?.body || forwardFrom?.body || '';
|
|
|
|
// Parse the original email content using the API
|
|
fetch('/api/parse-email', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify({ emailContent: originalContent }),
|
|
})
|
|
.then(response => response.json())
|
|
.then(parsed => {
|
|
// Create the reply/forward structure
|
|
content = `
|
|
<div class="compose-area" contenteditable="true" style="min-height: 100px; padding: 10px; border: 1px solid #e5e7eb; border-radius: 4px; margin-bottom: 20px;"></div>
|
|
<div class="quoted-content" contenteditable="false" style="color: #6b7280; font-size: 0.875rem;">
|
|
${forwardFrom ? `
|
|
<div style="margin-bottom: 10px;">
|
|
---------- Forwarded message ---------<br/>
|
|
From: ${forwardFrom.from}<br/>
|
|
Date: ${new Date(forwardFrom.date).toLocaleString()}<br/>
|
|
Subject: ${forwardFrom.subject}<br/>
|
|
To: ${forwardFrom.to}<br/>
|
|
${forwardFrom.cc ? `Cc: ${forwardFrom.cc}<br/>` : ''}
|
|
<br/>
|
|
${parsed.html || parsed.text}
|
|
</div>
|
|
` : `
|
|
<div style="margin-bottom: 10px;">
|
|
On ${new Date(replyTo?.date || '').toLocaleString()}, ${replyTo?.from} wrote:
|
|
</div>
|
|
<blockquote style="margin: 0; padding-left: 1em; border-left: 2px solid #e5e7eb;">
|
|
${parsed.html || parsed.text}
|
|
</blockquote>
|
|
`}
|
|
</div>
|
|
`;
|
|
|
|
if (composeBodyRef.current) {
|
|
composeBodyRef.current.innerHTML = content;
|
|
setIsInitialized(true);
|
|
|
|
// Place cursor at the beginning of the compose area
|
|
const composeArea = composeBodyRef.current.querySelector('.compose-area');
|
|
if (composeArea) {
|
|
const range = document.createRange();
|
|
const sel = window.getSelection();
|
|
range.setStart(composeArea, 0);
|
|
range.collapse(true);
|
|
sel?.removeAllRanges();
|
|
sel?.addRange(range);
|
|
(composeArea as HTMLElement).focus();
|
|
}
|
|
}
|
|
})
|
|
.catch(error => {
|
|
console.error('Error parsing email:', error);
|
|
});
|
|
} else {
|
|
// For new messages
|
|
content = `<div class="compose-area" contenteditable="true" style="min-height: 100px; padding: 10px; border: 1px solid #e5e7eb; border-radius: 4px;"></div>`;
|
|
composeBodyRef.current.innerHTML = content;
|
|
setIsInitialized(true);
|
|
|
|
// Place cursor at the beginning of the compose area
|
|
const composeArea = composeBodyRef.current.querySelector('.compose-area');
|
|
if (composeArea) {
|
|
const range = document.createRange();
|
|
const sel = window.getSelection();
|
|
range.setStart(composeArea, 0);
|
|
range.collapse(true);
|
|
sel?.removeAllRanges();
|
|
sel?.addRange(range);
|
|
(composeArea as HTMLElement).focus();
|
|
}
|
|
}
|
|
}
|
|
}, [composeBody, replyTo, forwardFrom, isInitialized]);
|
|
|
|
// Modified input handler to work with the single contentEditable area
|
|
const handleInput = (e: React.FormEvent<HTMLDivElement>) => {
|
|
if (!composeBodyRef.current) return;
|
|
|
|
// Get the compose area content
|
|
const composeArea = composeBodyRef.current.querySelector('.compose-area');
|
|
if (!composeArea) return;
|
|
|
|
// Get the quoted content if it exists
|
|
const quotedContent = composeBodyRef.current.querySelector('.quoted-content');
|
|
|
|
// Combine compose area and quoted content
|
|
const content = composeArea.innerHTML + (quotedContent ? quotedContent.outerHTML : '');
|
|
|
|
if (!content.trim()) {
|
|
console.warn('Email content is empty');
|
|
return;
|
|
}
|
|
|
|
// Create MIME headers
|
|
const mimeHeaders = {
|
|
'MIME-Version': '1.0',
|
|
'Content-Type': 'text/html; charset="utf-8"',
|
|
'Content-Transfer-Encoding': 'quoted-printable'
|
|
};
|
|
|
|
// Combine headers and content
|
|
const mimeContent = Object.entries(mimeHeaders)
|
|
.map(([key, value]) => `${key}: ${value}`)
|
|
.join('\n') + '\n\n' + content;
|
|
|
|
setComposeBody(mimeContent);
|
|
|
|
if (onBodyChange) {
|
|
onBodyChange(mimeContent);
|
|
}
|
|
};
|
|
|
|
const handleSendEmail = async () => {
|
|
// Ensure we have content before sending
|
|
if (!composeBodyRef.current) {
|
|
console.error('Compose body ref is not available');
|
|
return;
|
|
}
|
|
|
|
const composeArea = composeBodyRef.current.querySelector('.compose-area');
|
|
if (!composeArea) {
|
|
console.error('Compose area not found');
|
|
return;
|
|
}
|
|
|
|
// Get the current content
|
|
const composeContent = composeArea.innerHTML;
|
|
if (!composeContent.trim()) {
|
|
console.error('Email content is empty');
|
|
return;
|
|
}
|
|
|
|
// Get the quoted content if it exists
|
|
const quotedContent = composeBodyRef.current.querySelector('.quoted-content');
|
|
const fullContent = composeContent + (quotedContent ? quotedContent.outerHTML : '');
|
|
|
|
// Create MIME headers
|
|
const mimeHeaders = {
|
|
'MIME-Version': '1.0',
|
|
'Content-Type': 'text/html; charset="utf-8"',
|
|
'Content-Transfer-Encoding': 'quoted-printable'
|
|
};
|
|
|
|
// Combine headers and content
|
|
const mimeContent = Object.entries(mimeHeaders)
|
|
.map(([key, value]) => `${key}: ${value}`)
|
|
.join('\n') + '\n\n' + fullContent;
|
|
|
|
setComposeBody(mimeContent);
|
|
|
|
try {
|
|
await handleSend();
|
|
setShowCompose(false);
|
|
} catch (error) {
|
|
console.error('Error sending email:', error);
|
|
}
|
|
};
|
|
|
|
const handleFileAttachment = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
if (!e.target.files) return;
|
|
|
|
const newAttachments: any[] = [];
|
|
const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB in bytes
|
|
const oversizedFiles: string[] = [];
|
|
|
|
for (const file of e.target.files) {
|
|
if (file.size > MAX_FILE_SIZE) {
|
|
oversizedFiles.push(file.name);
|
|
continue;
|
|
}
|
|
|
|
try {
|
|
// Read file as base64
|
|
const base64Content = await new Promise<string>((resolve) => {
|
|
const reader = new FileReader();
|
|
reader.onloadend = () => {
|
|
const base64 = reader.result as string;
|
|
resolve(base64.split(',')[1]); // Remove data URL prefix
|
|
};
|
|
reader.readAsDataURL(file);
|
|
});
|
|
|
|
newAttachments.push({
|
|
name: file.name,
|
|
type: file.type,
|
|
content: base64Content,
|
|
encoding: 'base64'
|
|
});
|
|
} catch (error) {
|
|
console.error('Error processing attachment:', error);
|
|
}
|
|
}
|
|
|
|
if (oversizedFiles.length > 0) {
|
|
alert(`The following files exceed the 10MB size limit and were not attached:\n${oversizedFiles.join('\n')}`);
|
|
}
|
|
|
|
if (newAttachments.length > 0) {
|
|
setAttachments([...attachments, ...newAttachments]);
|
|
}
|
|
};
|
|
|
|
if (!showCompose) return null;
|
|
|
|
return (
|
|
<div className="fixed inset-0 bg-gray-600/30 backdrop-blur-sm z-50 flex items-center justify-center">
|
|
<div className="w-full max-w-2xl h-[90vh] bg-white rounded-xl shadow-xl flex flex-col mx-4">
|
|
{/* Modal Header */}
|
|
<div className="flex-none flex items-center justify-between px-6 py-3 border-b border-gray-200">
|
|
<h3 className="text-lg font-semibold text-gray-900">
|
|
{replyTo ? 'Reply' : forwardFrom ? 'Forward' : 'New Message'}
|
|
</h3>
|
|
<Button
|
|
variant="ghost"
|
|
size="icon"
|
|
className="hover:bg-gray-100 rounded-full"
|
|
onClick={onCancel}
|
|
>
|
|
<X className="h-5 w-5 text-gray-500" />
|
|
</Button>
|
|
</div>
|
|
|
|
{/* Modal Body */}
|
|
<div className="flex-1 overflow-hidden">
|
|
<div className="h-full flex flex-col p-6 space-y-4 overflow-y-auto">
|
|
{/* To Field */}
|
|
<div className="flex-none">
|
|
<Label htmlFor="to" className="block text-sm font-medium text-gray-700">To</Label>
|
|
<Input
|
|
id="to"
|
|
value={composeTo}
|
|
onChange={(e) => setComposeTo(e.target.value)}
|
|
placeholder="recipient@example.com"
|
|
className="w-full mt-1 bg-white border-gray-300 text-gray-900"
|
|
/>
|
|
</div>
|
|
|
|
{/* CC/BCC Toggle Buttons */}
|
|
<div className="flex-none flex items-center gap-4">
|
|
<button
|
|
type="button"
|
|
className="text-blue-600 hover:text-blue-700 text-sm font-medium"
|
|
onClick={() => setShowCc(!showCc)}
|
|
>
|
|
{showCc ? 'Hide Cc' : 'Add Cc'}
|
|
</button>
|
|
<button
|
|
type="button"
|
|
className="text-blue-600 hover:text-blue-700 text-sm font-medium"
|
|
onClick={() => setShowBcc(!showBcc)}
|
|
>
|
|
{showBcc ? 'Hide Bcc' : 'Add Bcc'}
|
|
</button>
|
|
</div>
|
|
|
|
{/* CC Field */}
|
|
{showCc && (
|
|
<div className="flex-none">
|
|
<Label htmlFor="cc" className="block text-sm font-medium text-gray-700">Cc</Label>
|
|
<Input
|
|
id="cc"
|
|
value={composeCc}
|
|
onChange={(e) => setComposeCc(e.target.value)}
|
|
placeholder="cc@example.com"
|
|
className="w-full mt-1 bg-white border-gray-300 text-gray-900"
|
|
/>
|
|
</div>
|
|
)}
|
|
|
|
{/* BCC Field */}
|
|
{showBcc && (
|
|
<div className="flex-none">
|
|
<Label htmlFor="bcc" className="block text-sm font-medium text-gray-700">Bcc</Label>
|
|
<Input
|
|
id="bcc"
|
|
value={composeBcc}
|
|
onChange={(e) => setComposeBcc(e.target.value)}
|
|
placeholder="bcc@example.com"
|
|
className="w-full mt-1 bg-white border-gray-300 text-gray-900"
|
|
/>
|
|
</div>
|
|
)}
|
|
|
|
{/* Subject Field */}
|
|
<div className="flex-none">
|
|
<Label htmlFor="subject" className="block text-sm font-medium text-gray-700">Subject</Label>
|
|
<Input
|
|
id="subject"
|
|
value={composeSubject}
|
|
onChange={(e) => setComposeSubject(e.target.value)}
|
|
placeholder="Enter subject"
|
|
className="w-full mt-1 bg-white border-gray-300 text-gray-900"
|
|
/>
|
|
</div>
|
|
|
|
{/* Message Body - Single contentEditable area with separated regions */}
|
|
<div className="flex-1 min-h-[200px] flex flex-col">
|
|
<Label htmlFor="message" className="flex-none block text-sm font-medium text-gray-700 mb-2">Message</Label>
|
|
<div
|
|
ref={composeBodyRef}
|
|
contentEditable="true"
|
|
onInput={handleInput}
|
|
className="flex-1 w-full bg-white border border-gray-300 rounded-md p-4 text-gray-900 overflow-y-auto focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
|
style={{
|
|
direction: 'ltr',
|
|
maxHeight: 'calc(100vh - 400px)',
|
|
minHeight: '200px',
|
|
overflowY: 'auto',
|
|
scrollbarWidth: 'thin',
|
|
scrollbarColor: '#cbd5e0 #f3f4f6'
|
|
}}
|
|
dir="ltr"
|
|
spellCheck="true"
|
|
role="textbox"
|
|
aria-multiline="true"
|
|
tabIndex={0}
|
|
suppressContentEditableWarning={true}
|
|
>
|
|
<style>{`
|
|
.compose-area {
|
|
min-height: 100px;
|
|
margin-bottom: 20px;
|
|
outline: none;
|
|
overflow-y: auto;
|
|
max-height: 300px;
|
|
}
|
|
.quoted-content {
|
|
color: #666;
|
|
user-select: text;
|
|
-webkit-user-select: text;
|
|
overflow-y: auto;
|
|
max-height: 300px;
|
|
}
|
|
.quoted-content blockquote {
|
|
margin: 0.8ex;
|
|
padding-left: 1ex;
|
|
border-left: 1px solid #ccc;
|
|
}
|
|
[contenteditable="true"] {
|
|
outline: none;
|
|
}
|
|
[contenteditable="true"]:focus {
|
|
outline: none;
|
|
}
|
|
/* Custom scrollbar styles */
|
|
::-webkit-scrollbar {
|
|
width: 8px;
|
|
}
|
|
::-webkit-scrollbar-track {
|
|
background: #f3f4f6;
|
|
border-radius: 4px;
|
|
}
|
|
::-webkit-scrollbar-thumb {
|
|
background: #cbd5e0;
|
|
border-radius: 4px;
|
|
}
|
|
::-webkit-scrollbar-thumb:hover {
|
|
background: #a0aec0;
|
|
}
|
|
`}</style>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Modal Footer */}
|
|
<div className="flex-none flex items-center justify-between px-6 py-3 border-t border-gray-200 bg-white">
|
|
<div className="flex items-center gap-2">
|
|
{/* File Input for Attachments */}
|
|
<input
|
|
type="file"
|
|
id="file-attachment"
|
|
className="hidden"
|
|
multiple
|
|
onChange={handleFileAttachment}
|
|
/>
|
|
<label htmlFor="file-attachment">
|
|
<Button
|
|
variant="outline"
|
|
size="icon"
|
|
className="rounded-full bg-white hover:bg-gray-100 border-gray-300"
|
|
onClick={(e) => {
|
|
e.preventDefault();
|
|
document.getElementById('file-attachment')?.click();
|
|
}}
|
|
>
|
|
<Paperclip className="h-4 w-4 text-gray-600" />
|
|
</Button>
|
|
</label>
|
|
</div>
|
|
<div className="flex items-center gap-3">
|
|
<Button
|
|
variant="ghost"
|
|
className="text-gray-600 hover:text-gray-700 hover:bg-gray-100"
|
|
onClick={onCancel}
|
|
>
|
|
Cancel
|
|
</Button>
|
|
<Button
|
|
className="bg-blue-600 text-white hover:bg-blue-700"
|
|
onClick={handleSendEmail}
|
|
>
|
|
Send
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|