/** * Utilities for email formatting with proper text direction handling */ import DOMPurify from 'isomorphic-dompurify'; // Interface definitions export interface EmailAddress { name: string; address: string; } export interface EmailMessage { id: string; messageId?: string; subject: string; from: EmailAddress[]; to: EmailAddress[]; cc?: EmailAddress[]; bcc?: EmailAddress[]; date: Date | string; flags?: { seen: boolean; flagged: boolean; answered: boolean; deleted: boolean; draft: boolean; }; preview?: string; content?: string; html?: string; text?: string; hasAttachments?: boolean; attachments?: any[]; folder?: string; size?: number; contentFetched?: boolean; } /** * Format email addresses for display */ export function formatEmailAddresses(addresses: EmailAddress[]): string { if (!addresses || addresses.length === 0) return ''; return addresses.map(addr => addr.name && addr.name !== addr.address ? `${addr.name} <${addr.address}>` : addr.address ).join(', '); } /** * Format date for display */ export function formatEmailDate(date: Date | string | undefined): string { if (!date) return ''; try { const dateObj = typeof date === 'string' ? new Date(date) : date; return dateObj.toLocaleString('en-US', { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }); } catch (e) { return typeof date === 'string' ? date : date.toString(); } } /** * Clean HTML content to prevent RTL/LTR issues */ export function cleanHtmlContent(content: string): string { if (!content) return ''; // First sanitize the HTML const sanitized = DOMPurify.sanitize(content); // Process content to ensure consistent direction let processed = sanitized; // Replace RTL attributes with LTR processed = processed.replace(/dir\s*=\s*["']rtl["']/gi, 'dir="ltr"'); processed = processed.replace(/style\s*=\s*["']([^"']*)direction\s*:\s*rtl;?([^"']*)["']/gi, (match, before, after) => `style="${before}direction: ltr;${after}"`); return processed; } /** * Format an email for forwarding */ export function formatForwardedEmail(email: EmailMessage): { subject: string; content: string; } { // Format subject with Fwd: prefix if needed const subjectBase = email.subject || '(No subject)'; const subject = subjectBase.match(/^(Fwd|FW|Forward):/i) ? subjectBase : `Fwd: ${subjectBase}`; // Get sender and recipient information const fromString = formatEmailAddresses(email.from || []); const toString = formatEmailAddresses(email.to || []); const dateString = formatEmailDate(email.date); // Get and clean original content const originalContent = cleanHtmlContent(email.content || email.html || email.text || ''); // Create formatted content with explicit LTR formatting const content = `