courrier refactor
This commit is contained in:
parent
6e66c2ac34
commit
aefe858106
File diff suppressed because it is too large
Load Diff
93
components/email/BulkActionsToolbar.tsx
Normal file
93
components/email/BulkActionsToolbar.tsx
Normal file
@ -0,0 +1,93 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import React from 'react';
|
||||||
|
import { Trash, Mail, MailOpen, Archive } from 'lucide-react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import {
|
||||||
|
Tooltip,
|
||||||
|
TooltipContent,
|
||||||
|
TooltipProvider,
|
||||||
|
TooltipTrigger
|
||||||
|
} from '@/components/ui/tooltip';
|
||||||
|
|
||||||
|
interface BulkActionsToolbarProps {
|
||||||
|
selectedCount: number;
|
||||||
|
onBulkAction: (action: 'delete' | 'mark-read' | 'mark-unread' | 'archive') => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function BulkActionsToolbar({
|
||||||
|
selectedCount,
|
||||||
|
onBulkAction
|
||||||
|
}: BulkActionsToolbarProps) {
|
||||||
|
return (
|
||||||
|
<div className="border-b p-2 flex items-center gap-2 bg-accent/20">
|
||||||
|
<div className="text-xs font-medium flex-1">
|
||||||
|
{selectedCount} {selectedCount === 1 ? 'message' : 'messages'} selected
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<TooltipProvider>
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-8 w-8"
|
||||||
|
onClick={() => onBulkAction('mark-read')}
|
||||||
|
>
|
||||||
|
<MailOpen className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent>Mark as read</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</TooltipProvider>
|
||||||
|
|
||||||
|
<TooltipProvider>
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-8 w-8"
|
||||||
|
onClick={() => onBulkAction('mark-unread')}
|
||||||
|
>
|
||||||
|
<Mail className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent>Mark as unread</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</TooltipProvider>
|
||||||
|
|
||||||
|
<TooltipProvider>
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-8 w-8"
|
||||||
|
onClick={() => onBulkAction('archive')}
|
||||||
|
>
|
||||||
|
<Archive className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent>Archive</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</TooltipProvider>
|
||||||
|
|
||||||
|
<TooltipProvider>
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-8 w-8 text-destructive hover:text-destructive"
|
||||||
|
onClick={() => onBulkAction('delete')}
|
||||||
|
>
|
||||||
|
<Trash className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent>Delete</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</TooltipProvider>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
114
components/email/EmailContent.tsx
Normal file
114
components/email/EmailContent.tsx
Normal file
@ -0,0 +1,114 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import React, { useState, useEffect } from 'react';
|
||||||
|
import { Loader2, Paperclip, FileDown } from 'lucide-react';
|
||||||
|
import { sanitizeHtml } from '@/lib/utils/email-formatter';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Email } from '@/hooks/use-courrier';
|
||||||
|
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
|
||||||
|
|
||||||
|
interface EmailContentProps {
|
||||||
|
email: Email;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function EmailContent({ email }: EmailContentProps) {
|
||||||
|
const [content, setContent] = useState<React.ReactNode>(null);
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!email) return;
|
||||||
|
|
||||||
|
const renderContent = async () => {
|
||||||
|
setIsLoading(true);
|
||||||
|
setError(null);
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (!email.content || email.content.length === 0) {
|
||||||
|
setContent(<div className="text-gray-500">Email content is empty</div>);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use the sanitizer from the centralized formatter
|
||||||
|
const sanitizedHtml = sanitizeHtml(email.content);
|
||||||
|
|
||||||
|
setContent(
|
||||||
|
<div
|
||||||
|
className="email-content prose prose-sm max-w-none dark:prose-invert"
|
||||||
|
dangerouslySetInnerHTML={{ __html: sanitizedHtml }}
|
||||||
|
dir="auto"
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error rendering email content:', err);
|
||||||
|
setError('Error rendering email content. Please try again.');
|
||||||
|
setContent(null);
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
renderContent();
|
||||||
|
}, [email]);
|
||||||
|
|
||||||
|
// Render attachments if they exist
|
||||||
|
const renderAttachments = () => {
|
||||||
|
if (!email?.attachments || email.attachments.length === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="border-t mt-4 pt-4">
|
||||||
|
<h3 className="text-sm font-medium mb-2 flex items-center gap-1">
|
||||||
|
<Paperclip className="h-4 w-4" />
|
||||||
|
Attachments ({email.attachments.length})
|
||||||
|
</h3>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{email.attachments.map((attachment, index) => (
|
||||||
|
<Button
|
||||||
|
key={index}
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
className="flex items-center gap-1 text-xs"
|
||||||
|
asChild
|
||||||
|
>
|
||||||
|
<a
|
||||||
|
href={`/api/courrier/${email.id}/attachment/${encodeURIComponent(attachment.filename)}`}
|
||||||
|
download={attachment.filename}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
>
|
||||||
|
<FileDown className="h-3 w-3 mr-1" />
|
||||||
|
{attachment.filename} ({(attachment.size / 1024).toFixed(0)}KB)
|
||||||
|
</a>
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<div className="flex justify-center items-center h-full p-8">
|
||||||
|
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return (
|
||||||
|
<Alert variant="destructive" className="m-4">
|
||||||
|
<AlertTitle>Error</AlertTitle>
|
||||||
|
<AlertDescription>{error}</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="p-4">
|
||||||
|
{content}
|
||||||
|
{renderAttachments()}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
109
components/email/EmailHeader.tsx
Normal file
109
components/email/EmailHeader.tsx
Normal file
@ -0,0 +1,109 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import React, { useState } from 'react';
|
||||||
|
import { Search, X, Settings } from 'lucide-react';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import {
|
||||||
|
Tooltip,
|
||||||
|
TooltipContent,
|
||||||
|
TooltipProvider,
|
||||||
|
TooltipTrigger
|
||||||
|
} from '@/components/ui/tooltip';
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from '@/components/ui/dropdown-menu';
|
||||||
|
|
||||||
|
interface EmailHeaderProps {
|
||||||
|
onSearch: (query: string) => void;
|
||||||
|
onSettingsClick?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function EmailHeader({
|
||||||
|
onSearch,
|
||||||
|
onSettingsClick,
|
||||||
|
}: EmailHeaderProps) {
|
||||||
|
const [searchQuery, setSearchQuery] = useState('');
|
||||||
|
const [isSearching, setIsSearching] = useState(false);
|
||||||
|
|
||||||
|
const handleSearch = (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
onSearch(searchQuery);
|
||||||
|
};
|
||||||
|
|
||||||
|
const clearSearch = () => {
|
||||||
|
setSearchQuery('');
|
||||||
|
onSearch('');
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="border-b px-4 py-2 flex items-center">
|
||||||
|
<div className="flex-1">
|
||||||
|
<form onSubmit={handleSearch} className="relative">
|
||||||
|
<Search className="absolute left-2 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||||
|
<Input
|
||||||
|
type="text"
|
||||||
|
placeholder="Search emails..."
|
||||||
|
value={searchQuery}
|
||||||
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
|
className="pl-8 pr-8 h-9"
|
||||||
|
/>
|
||||||
|
{searchQuery && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={clearSearch}
|
||||||
|
className="absolute right-2 top-1/2 transform -translate-y-1/2"
|
||||||
|
>
|
||||||
|
<X className="h-4 w-4 text-muted-foreground" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="ml-2 flex items-center gap-1">
|
||||||
|
<TooltipProvider>
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className="h-8 w-8"
|
||||||
|
onClick={handleSearch}
|
||||||
|
>
|
||||||
|
<Search className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent>Search</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</TooltipProvider>
|
||||||
|
|
||||||
|
<DropdownMenu>
|
||||||
|
<TooltipProvider>
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<Button variant="ghost" size="icon" className="h-8 w-8">
|
||||||
|
<Settings className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent>Settings</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</TooltipProvider>
|
||||||
|
<DropdownMenuContent align="end">
|
||||||
|
<DropdownMenuItem onClick={onSettingsClick}>
|
||||||
|
Email settings
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem onClick={onSettingsClick}>
|
||||||
|
Configure IMAP
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
130
components/email/EmailList.tsx
Normal file
130
components/email/EmailList.tsx
Normal file
@ -0,0 +1,130 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import React, { useState } from 'react';
|
||||||
|
import { Loader2 } from 'lucide-react';
|
||||||
|
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||||
|
import { Email } from '@/hooks/use-courrier';
|
||||||
|
import EmailListItem from './EmailListItem';
|
||||||
|
import EmailListHeader from './EmailListHeader';
|
||||||
|
import BulkActionsToolbar from './BulkActionsToolbar';
|
||||||
|
|
||||||
|
interface EmailListProps {
|
||||||
|
emails: Email[];
|
||||||
|
selectedEmailIds: string[];
|
||||||
|
selectedEmail: Email | null;
|
||||||
|
currentFolder: string;
|
||||||
|
isLoading: boolean;
|
||||||
|
totalEmails: number;
|
||||||
|
hasMoreEmails: boolean;
|
||||||
|
onSelectEmail: (emailId: string) => void;
|
||||||
|
onToggleSelect: (emailId: string) => void;
|
||||||
|
onToggleSelectAll: () => void;
|
||||||
|
onBulkAction: (action: 'delete' | 'mark-read' | 'mark-unread' | 'archive') => void;
|
||||||
|
onToggleStarred: (emailId: string) => void;
|
||||||
|
onLoadMore: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function EmailList({
|
||||||
|
emails,
|
||||||
|
selectedEmailIds,
|
||||||
|
selectedEmail,
|
||||||
|
currentFolder,
|
||||||
|
isLoading,
|
||||||
|
totalEmails,
|
||||||
|
hasMoreEmails,
|
||||||
|
onSelectEmail,
|
||||||
|
onToggleSelect,
|
||||||
|
onToggleSelectAll,
|
||||||
|
onBulkAction,
|
||||||
|
onToggleStarred,
|
||||||
|
onLoadMore
|
||||||
|
}: EmailListProps) {
|
||||||
|
const [scrollPosition, setScrollPosition] = useState(0);
|
||||||
|
|
||||||
|
// Handle scroll to detect when user reaches the bottom
|
||||||
|
const handleScroll = (event: React.UIEvent<HTMLDivElement>) => {
|
||||||
|
const target = event.target as HTMLDivElement;
|
||||||
|
const { scrollTop, scrollHeight, clientHeight } = target;
|
||||||
|
|
||||||
|
setScrollPosition(scrollTop);
|
||||||
|
|
||||||
|
// If user scrolls near the bottom and we have more emails, load more
|
||||||
|
if (scrollHeight - scrollTop - clientHeight < 200 && hasMoreEmails && !isLoading) {
|
||||||
|
onLoadMore();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Render loading state
|
||||||
|
if (isLoading && emails.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="flex justify-center items-center h-full p-8">
|
||||||
|
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Render empty state
|
||||||
|
if (emails.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col justify-center items-center h-full p-8 text-center">
|
||||||
|
<h3 className="text-lg font-semibold mb-2">No emails found</h3>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
{currentFolder === 'INBOX'
|
||||||
|
? "Your inbox is empty. You're all caught up!"
|
||||||
|
: `The ${currentFolder} folder is empty.`}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Are all emails selected
|
||||||
|
const allSelected = selectedEmailIds.length === emails.length && emails.length > 0;
|
||||||
|
|
||||||
|
// Are some (but not all) emails selected
|
||||||
|
const someSelected = selectedEmailIds.length > 0 && selectedEmailIds.length < emails.length;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col h-full">
|
||||||
|
<EmailListHeader
|
||||||
|
allSelected={allSelected}
|
||||||
|
someSelected={someSelected}
|
||||||
|
onToggleSelectAll={onToggleSelectAll}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{selectedEmailIds.length > 0 && (
|
||||||
|
<BulkActionsToolbar
|
||||||
|
selectedCount={selectedEmailIds.length}
|
||||||
|
onBulkAction={onBulkAction}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<ScrollArea className="flex-1" onScroll={handleScroll}>
|
||||||
|
<div className="divide-y">
|
||||||
|
{emails.map((email) => (
|
||||||
|
<EmailListItem
|
||||||
|
key={email.id}
|
||||||
|
email={email}
|
||||||
|
isSelected={selectedEmailIds.includes(email.id)}
|
||||||
|
isActive={selectedEmail?.id === email.id}
|
||||||
|
onSelect={() => onSelectEmail(email.id)}
|
||||||
|
onToggleSelect={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
onToggleSelect(email.id);
|
||||||
|
}}
|
||||||
|
onToggleStarred={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
onToggleStarred(email.id);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{isLoading && emails.length > 0 && (
|
||||||
|
<div className="p-4 flex justify-center">
|
||||||
|
<Loader2 className="h-6 w-6 animate-spin text-primary" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</ScrollArea>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
60
components/email/EmailListHeader.tsx
Normal file
60
components/email/EmailListHeader.tsx
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import React from 'react';
|
||||||
|
import { ChevronDown } from 'lucide-react';
|
||||||
|
import { Checkbox } from '@/components/ui/checkbox';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from '@/components/ui/dropdown-menu';
|
||||||
|
|
||||||
|
interface EmailListHeaderProps {
|
||||||
|
allSelected: boolean;
|
||||||
|
someSelected: boolean;
|
||||||
|
onToggleSelectAll: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function EmailListHeader({
|
||||||
|
allSelected,
|
||||||
|
someSelected,
|
||||||
|
onToggleSelectAll,
|
||||||
|
}: EmailListHeaderProps) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-between border-b px-4 py-2">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Checkbox
|
||||||
|
checked={allSelected}
|
||||||
|
ref={(input) => {
|
||||||
|
if (input) {
|
||||||
|
(input as unknown as HTMLInputElement).indeterminate = someSelected && !allSelected;
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
onClick={onToggleSelectAll}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<Button variant="ghost" size="icon" className="h-8 w-8 p-0">
|
||||||
|
<ChevronDown className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="start">
|
||||||
|
<DropdownMenuItem onClick={onToggleSelectAll}>
|
||||||
|
{allSelected ? 'Unselect all' : 'Select all'}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem onClick={onToggleSelectAll} disabled={!someSelected}>
|
||||||
|
Unselect all
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="text-sm text-muted-foreground">
|
||||||
|
Select messages to perform actions
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
158
components/email/EmailListItem.tsx
Normal file
158
components/email/EmailListItem.tsx
Normal file
@ -0,0 +1,158 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import React from 'react';
|
||||||
|
import { Star, Mail, MailOpen } from 'lucide-react';
|
||||||
|
import { Checkbox } from '@/components/ui/checkbox';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
import { Email } from '@/hooks/use-courrier';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
|
||||||
|
|
||||||
|
interface EmailListItemProps {
|
||||||
|
email: Email;
|
||||||
|
isSelected: boolean;
|
||||||
|
isActive: boolean;
|
||||||
|
onSelect: () => void;
|
||||||
|
onToggleSelect: (e: React.MouseEvent) => void;
|
||||||
|
onToggleStarred: (e: React.MouseEvent) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function EmailListItem({
|
||||||
|
email,
|
||||||
|
isSelected,
|
||||||
|
isActive,
|
||||||
|
onSelect,
|
||||||
|
onToggleSelect,
|
||||||
|
onToggleStarred
|
||||||
|
}: EmailListItemProps) {
|
||||||
|
// Format the date in a readable way
|
||||||
|
const formatDate = (dateString: string) => {
|
||||||
|
const date = new Date(dateString);
|
||||||
|
const now = new Date();
|
||||||
|
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||||
|
const yesterday = new Date(today);
|
||||||
|
yesterday.setDate(yesterday.getDate() - 1);
|
||||||
|
|
||||||
|
// Check if date is today
|
||||||
|
if (date >= today) {
|
||||||
|
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if date is yesterday
|
||||||
|
if (date >= yesterday) {
|
||||||
|
return 'Yesterday';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if date is this year
|
||||||
|
if (date.getFullYear() === now.getFullYear()) {
|
||||||
|
return date.toLocaleDateString([], { month: 'short', day: 'numeric' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Date is from a previous year
|
||||||
|
return date.toLocaleDateString([], { year: 'numeric', month: 'short', day: 'numeric' });
|
||||||
|
};
|
||||||
|
|
||||||
|
// Get the first letter of the sender's name or email for the avatar
|
||||||
|
const getSenderInitial = () => {
|
||||||
|
if (!email.from || email.from.length === 0) return '?';
|
||||||
|
|
||||||
|
const sender = email.from[0];
|
||||||
|
if (sender.name && sender.name.trim()) {
|
||||||
|
return sender.name.trim()[0].toUpperCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sender.address && sender.address.trim()) {
|
||||||
|
return sender.address.trim()[0].toUpperCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
return '?';
|
||||||
|
};
|
||||||
|
|
||||||
|
// Get sender name or email
|
||||||
|
const getSenderName = () => {
|
||||||
|
if (!email.from || email.from.length === 0) return 'Unknown';
|
||||||
|
|
||||||
|
const sender = email.from[0];
|
||||||
|
if (sender.name && sender.name.trim()) {
|
||||||
|
return sender.name.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
return sender.address || 'Unknown';
|
||||||
|
};
|
||||||
|
|
||||||
|
// Generate a stable color based on the sender's email
|
||||||
|
const getAvatarColor = () => {
|
||||||
|
if (!email.from || email.from.length === 0) return 'hsl(0, 0%, 50%)';
|
||||||
|
|
||||||
|
const address = email.from[0].address || '';
|
||||||
|
let hash = 0;
|
||||||
|
|
||||||
|
for (let i = 0; i < address.length; i++) {
|
||||||
|
hash = address.charCodeAt(i) + ((hash << 5) - hash);
|
||||||
|
}
|
||||||
|
|
||||||
|
const h = hash % 360;
|
||||||
|
return `hsl(${h}, 70%, 80%)`;
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
'flex items-start gap-2 p-3 cursor-pointer transition-colors hover:bg-accent/50 relative',
|
||||||
|
isActive && 'bg-accent',
|
||||||
|
!email.read && 'font-medium'
|
||||||
|
)}
|
||||||
|
onClick={onSelect}
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-2 min-w-[3rem]">
|
||||||
|
<Checkbox
|
||||||
|
checked={isSelected}
|
||||||
|
onClick={onToggleSelect}
|
||||||
|
className="mt-1"
|
||||||
|
/>
|
||||||
|
<div onClick={onToggleStarred}>
|
||||||
|
<Star
|
||||||
|
className={cn(
|
||||||
|
'h-5 w-5 cursor-pointer transition-colors',
|
||||||
|
email.starred ? 'fill-yellow-400 text-yellow-400' : 'text-muted-foreground hover:text-yellow-400'
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Avatar className="mt-1 h-8 w-8 font-semibold text-sm" style={{ backgroundColor: getAvatarColor() }}>
|
||||||
|
<AvatarFallback>{getSenderInitial()}</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="flex justify-between items-baseline mb-1">
|
||||||
|
<div className="font-medium truncate">
|
||||||
|
{getSenderName()}
|
||||||
|
</div>
|
||||||
|
<div className="text-xs text-muted-foreground whitespace-nowrap ml-2">
|
||||||
|
{formatDate(email.date)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-baseline">
|
||||||
|
<div className="font-medium truncate">
|
||||||
|
{email.subject || '(No subject)'}
|
||||||
|
</div>
|
||||||
|
{email.hasAttachments && (
|
||||||
|
<Badge variant="outline" className="ml-2 text-xs">📎</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="text-sm text-muted-foreground truncate mt-1">
|
||||||
|
{email.preview || 'No preview available'}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!email.read && (
|
||||||
|
<div className="absolute right-3 top-3">
|
||||||
|
<div className="h-2 w-2 rounded-full bg-primary"></div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
140
components/email/EmailSidebar.tsx
Normal file
140
components/email/EmailSidebar.tsx
Normal file
@ -0,0 +1,140 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import React from 'react';
|
||||||
|
import {
|
||||||
|
Inbox, Send, Trash, Archive, Star,
|
||||||
|
File, RefreshCw, Plus, MailOpen
|
||||||
|
} from 'lucide-react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
|
||||||
|
interface EmailSidebarProps {
|
||||||
|
currentFolder: string;
|
||||||
|
folders: string[];
|
||||||
|
onFolderChange: (folder: string) => void;
|
||||||
|
onRefresh: () => void;
|
||||||
|
onCompose: () => void;
|
||||||
|
isLoading: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function EmailSidebar({
|
||||||
|
currentFolder,
|
||||||
|
folders,
|
||||||
|
onFolderChange,
|
||||||
|
onRefresh,
|
||||||
|
onCompose,
|
||||||
|
isLoading
|
||||||
|
}: EmailSidebarProps) {
|
||||||
|
// Get the appropriate icon for a folder
|
||||||
|
const getFolderIcon = (folder: string) => {
|
||||||
|
const folderLower = folder.toLowerCase();
|
||||||
|
|
||||||
|
switch (folderLower) {
|
||||||
|
case 'inbox':
|
||||||
|
return <Inbox className="h-4 w-4" />;
|
||||||
|
case 'sent':
|
||||||
|
case 'sent items':
|
||||||
|
return <Send className="h-4 w-4" />;
|
||||||
|
case 'drafts':
|
||||||
|
return <File className="h-4 w-4" />;
|
||||||
|
case 'trash':
|
||||||
|
case 'deleted':
|
||||||
|
case 'bin':
|
||||||
|
return <Trash className="h-4 w-4" />;
|
||||||
|
case 'archive':
|
||||||
|
case 'archived':
|
||||||
|
return <Archive className="h-4 w-4" />;
|
||||||
|
case 'starred':
|
||||||
|
case 'important':
|
||||||
|
return <Star className="h-4 w-4" />;
|
||||||
|
default:
|
||||||
|
return <MailOpen className="h-4 w-4" />;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Group folders into standard and custom
|
||||||
|
const standardFolders = ['INBOX', 'Sent', 'Drafts', 'Trash', 'Archive', 'Junk'];
|
||||||
|
const visibleStandardFolders = standardFolders.filter(f =>
|
||||||
|
folders.includes(f) || folders.some(folder => folder.toLowerCase() === f.toLowerCase())
|
||||||
|
);
|
||||||
|
|
||||||
|
const customFolders = folders.filter(f =>
|
||||||
|
!standardFolders.some(sf => sf.toLowerCase() === f.toLowerCase())
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<aside className="w-60 border-r h-full flex flex-col">
|
||||||
|
<div className="p-4">
|
||||||
|
<Button
|
||||||
|
className="w-full gap-2"
|
||||||
|
size="sm"
|
||||||
|
onClick={onCompose}
|
||||||
|
>
|
||||||
|
<Plus className="h-4 w-4" />
|
||||||
|
Compose
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="px-4 py-2">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="w-full justify-start gap-2"
|
||||||
|
onClick={onRefresh}
|
||||||
|
disabled={isLoading}
|
||||||
|
>
|
||||||
|
<RefreshCw className={cn(
|
||||||
|
"h-4 w-4",
|
||||||
|
isLoading && "animate-spin"
|
||||||
|
)} />
|
||||||
|
Refresh
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ScrollArea className="flex-1">
|
||||||
|
<div className="space-y-1 p-2">
|
||||||
|
<div className="text-xs font-medium text-muted-foreground px-2 py-1">
|
||||||
|
FOLDERS
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Standard folders */}
|
||||||
|
{visibleStandardFolders.map(folder => (
|
||||||
|
<Button
|
||||||
|
key={folder}
|
||||||
|
variant={currentFolder === folder ? "secondary" : "ghost"}
|
||||||
|
size="sm"
|
||||||
|
className="w-full justify-start gap-2"
|
||||||
|
onClick={() => onFolderChange(folder)}
|
||||||
|
>
|
||||||
|
{getFolderIcon(folder)}
|
||||||
|
<span className="capitalize">{folder.toLowerCase()}</span>
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{/* Custom folders section */}
|
||||||
|
{customFolders.length > 0 && (
|
||||||
|
<>
|
||||||
|
<div className="text-xs font-medium text-muted-foreground px-2 py-1 mt-4">
|
||||||
|
CUSTOM FOLDERS
|
||||||
|
</div>
|
||||||
|
{customFolders.map(folder => (
|
||||||
|
<Button
|
||||||
|
key={folder}
|
||||||
|
variant={currentFolder === folder ? "secondary" : "ghost"}
|
||||||
|
size="sm"
|
||||||
|
className="w-full justify-start gap-2"
|
||||||
|
onClick={() => onFolderChange(folder)}
|
||||||
|
>
|
||||||
|
{getFolderIcon(folder)}
|
||||||
|
<span className="truncate">{folder}</span>
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</ScrollArea>
|
||||||
|
</aside>
|
||||||
|
);
|
||||||
|
}
|
||||||
466
hooks/use-courrier.ts
Normal file
466
hooks/use-courrier.ts
Normal file
@ -0,0 +1,466 @@
|
|||||||
|
import { useState, useCallback, useEffect } from 'react';
|
||||||
|
import { useSession } from 'next-auth/react';
|
||||||
|
import { useToast } from './use-toast';
|
||||||
|
import { formatEmailForReplyOrForward } from '@/lib/utils/email-formatter';
|
||||||
|
|
||||||
|
export interface EmailAddress {
|
||||||
|
name: string;
|
||||||
|
address: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Email {
|
||||||
|
id: string;
|
||||||
|
from: EmailAddress[];
|
||||||
|
to: EmailAddress[];
|
||||||
|
cc?: EmailAddress[];
|
||||||
|
bcc?: EmailAddress[];
|
||||||
|
subject: string;
|
||||||
|
content: string;
|
||||||
|
preview?: string;
|
||||||
|
date: string;
|
||||||
|
read: boolean;
|
||||||
|
starred: boolean;
|
||||||
|
attachments?: { filename: string; contentType: string; size: number; content?: string }[];
|
||||||
|
folder: string;
|
||||||
|
hasAttachments: boolean;
|
||||||
|
contentFetched?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EmailListResult {
|
||||||
|
emails: Email[];
|
||||||
|
totalEmails: number;
|
||||||
|
page: number;
|
||||||
|
perPage: number;
|
||||||
|
totalPages: number;
|
||||||
|
folder: string;
|
||||||
|
mailboxes: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EmailData {
|
||||||
|
to: string;
|
||||||
|
cc?: string;
|
||||||
|
bcc?: string;
|
||||||
|
subject: string;
|
||||||
|
body: string;
|
||||||
|
attachments?: Array<{
|
||||||
|
name: string;
|
||||||
|
content: string;
|
||||||
|
type: string;
|
||||||
|
}>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type MailFolder = string;
|
||||||
|
|
||||||
|
// Hook for managing email operations
|
||||||
|
export const useCourrier = () => {
|
||||||
|
// State for email data
|
||||||
|
const [emails, setEmails] = useState<Email[]>([]);
|
||||||
|
const [selectedEmail, setSelectedEmail] = useState<Email | null>(null);
|
||||||
|
const [selectedEmailIds, setSelectedEmailIds] = useState<string[]>([]);
|
||||||
|
const [currentFolder, setCurrentFolder] = useState<MailFolder>('INBOX');
|
||||||
|
const [mailboxes, setMailboxes] = useState<string[]>([]);
|
||||||
|
|
||||||
|
// State for UI
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const [isSending, setIsSending] = useState(false);
|
||||||
|
const [isDeleting, setIsDeleting] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [searchQuery, setSearchQuery] = useState('');
|
||||||
|
const [page, setPage] = useState(1);
|
||||||
|
const [perPage, setPerPage] = useState(20);
|
||||||
|
const [totalEmails, setTotalEmails] = useState(0);
|
||||||
|
const [totalPages, setTotalPages] = useState(0);
|
||||||
|
|
||||||
|
// Auth and notifications
|
||||||
|
const { data: session } = useSession();
|
||||||
|
const { toast } = useToast();
|
||||||
|
|
||||||
|
// Load emails when folder or page changes
|
||||||
|
useEffect(() => {
|
||||||
|
if (session?.user?.id) {
|
||||||
|
loadEmails();
|
||||||
|
}
|
||||||
|
}, [currentFolder, page, perPage, session?.user?.id]);
|
||||||
|
|
||||||
|
// Load emails from the server
|
||||||
|
const loadEmails = useCallback(async (isLoadMore = false) => {
|
||||||
|
if (!session?.user?.id) return;
|
||||||
|
|
||||||
|
setIsLoading(true);
|
||||||
|
setError(null);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Build query params
|
||||||
|
const queryParams = new URLSearchParams({
|
||||||
|
folder: currentFolder,
|
||||||
|
page: page.toString(),
|
||||||
|
perPage: perPage.toString()
|
||||||
|
});
|
||||||
|
|
||||||
|
if (searchQuery) {
|
||||||
|
queryParams.set('search', searchQuery);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch emails from API
|
||||||
|
const response = await fetch(`/api/courrier?${queryParams.toString()}`);
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorData = await response.json();
|
||||||
|
throw new Error(errorData.error || 'Failed to fetch emails');
|
||||||
|
}
|
||||||
|
|
||||||
|
const data: EmailListResult = await response.json();
|
||||||
|
|
||||||
|
// Update state with the fetched data
|
||||||
|
if (isLoadMore) {
|
||||||
|
setEmails(prev => [...prev, ...data.emails]);
|
||||||
|
} else {
|
||||||
|
setEmails(data.emails);
|
||||||
|
}
|
||||||
|
|
||||||
|
setTotalEmails(data.totalEmails);
|
||||||
|
setTotalPages(data.totalPages);
|
||||||
|
|
||||||
|
// Update available mailboxes if provided
|
||||||
|
if (data.mailboxes && data.mailboxes.length > 0) {
|
||||||
|
setMailboxes(data.mailboxes);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clear selection if not loading more
|
||||||
|
if (!isLoadMore) {
|
||||||
|
setSelectedEmail(null);
|
||||||
|
setSelectedEmailIds([]);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error loading emails:', err);
|
||||||
|
setError(err instanceof Error ? err.message : 'Failed to load emails');
|
||||||
|
toast({
|
||||||
|
variant: "destructive",
|
||||||
|
title: "Error",
|
||||||
|
description: err instanceof Error ? err.message : 'Failed to load emails'
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
}, [currentFolder, page, perPage, searchQuery, session?.user?.id, toast]);
|
||||||
|
|
||||||
|
// Fetch a single email's content
|
||||||
|
const fetchEmailContent = useCallback(async (emailId: string) => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/courrier/${emailId}?folder=${encodeURIComponent(currentFolder)}`);
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Failed to fetch email content: ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
return data;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching email content:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}, [currentFolder]);
|
||||||
|
|
||||||
|
// Select an email to view
|
||||||
|
const handleEmailSelect = useCallback(async (emailId: string) => {
|
||||||
|
setIsLoading(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Find the email in the current list
|
||||||
|
const email = emails.find(e => e.id === emailId);
|
||||||
|
|
||||||
|
if (!email) {
|
||||||
|
throw new Error('Email not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
// If content is not fetched, get the full content
|
||||||
|
if (!email.contentFetched) {
|
||||||
|
const fullEmail = await fetchEmailContent(emailId);
|
||||||
|
|
||||||
|
// Merge the full content with the email
|
||||||
|
const updatedEmail = {
|
||||||
|
...email,
|
||||||
|
content: fullEmail.content,
|
||||||
|
attachments: fullEmail.attachments,
|
||||||
|
contentFetched: true
|
||||||
|
};
|
||||||
|
|
||||||
|
// Update the email in the list
|
||||||
|
setEmails(emails.map(e => e.id === emailId ? updatedEmail : e));
|
||||||
|
setSelectedEmail(updatedEmail);
|
||||||
|
} else {
|
||||||
|
setSelectedEmail(email);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mark the email as read if it's not already
|
||||||
|
if (!email.read) {
|
||||||
|
markEmailAsRead(emailId, true);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error selecting email:', err);
|
||||||
|
toast({
|
||||||
|
variant: "destructive",
|
||||||
|
title: "Error",
|
||||||
|
description: "Could not load email content"
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
}, [emails, fetchEmailContent, toast]);
|
||||||
|
|
||||||
|
// Mark an email as read/unread
|
||||||
|
const markEmailAsRead = useCallback(async (emailId: string, isRead: boolean) => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/courrier/${emailId}/mark-read`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
isRead,
|
||||||
|
folder: currentFolder
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to mark email as read');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update the email in the list
|
||||||
|
setEmails(emails.map(email =>
|
||||||
|
email.id === emailId ? { ...email, read: isRead } : email
|
||||||
|
));
|
||||||
|
|
||||||
|
// If the selected email is the one being marked, update it too
|
||||||
|
if (selectedEmail && selectedEmail.id === emailId) {
|
||||||
|
setSelectedEmail({ ...selectedEmail, read: isRead });
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error marking email as read:', error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}, [emails, selectedEmail, currentFolder]);
|
||||||
|
|
||||||
|
// Toggle starred status for an email
|
||||||
|
const toggleStarred = useCallback(async (emailId: string) => {
|
||||||
|
const email = emails.find(e => e.id === emailId);
|
||||||
|
if (!email) return;
|
||||||
|
|
||||||
|
const newStarredStatus = !email.starred;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/courrier/${emailId}/star`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
starred: newStarredStatus,
|
||||||
|
folder: currentFolder
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to toggle star status');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update the email in the list
|
||||||
|
setEmails(emails.map(email =>
|
||||||
|
email.id === emailId ? { ...email, starred: newStarredStatus } : email
|
||||||
|
));
|
||||||
|
|
||||||
|
// If the selected email is the one being starred, update it too
|
||||||
|
if (selectedEmail && selectedEmail.id === emailId) {
|
||||||
|
setSelectedEmail({ ...selectedEmail, starred: newStarredStatus });
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error toggling star status:', error);
|
||||||
|
toast({
|
||||||
|
variant: "destructive",
|
||||||
|
title: "Error",
|
||||||
|
description: "Could not update star status"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [emails, selectedEmail, currentFolder, toast]);
|
||||||
|
|
||||||
|
// Send an email
|
||||||
|
const sendEmail = useCallback(async (emailData: EmailData) => {
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
toast({
|
||||||
|
variant: "destructive",
|
||||||
|
title: "Error",
|
||||||
|
description: "You must be logged in to send emails"
|
||||||
|
});
|
||||||
|
return { success: false, error: "Not authenticated" };
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsSending(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/courrier/send', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
},
|
||||||
|
body: JSON.stringify(emailData)
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await response.json();
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(result.error || 'Failed to send email');
|
||||||
|
}
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: "Success",
|
||||||
|
description: "Email sent successfully"
|
||||||
|
});
|
||||||
|
|
||||||
|
return { success: true, messageId: result.messageId };
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error sending email:', error);
|
||||||
|
|
||||||
|
toast({
|
||||||
|
variant: "destructive",
|
||||||
|
title: "Error",
|
||||||
|
description: error instanceof Error ? error.message : 'Failed to send email'
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: error instanceof Error ? error.message : 'Failed to send email'
|
||||||
|
};
|
||||||
|
} finally {
|
||||||
|
setIsSending(false);
|
||||||
|
}
|
||||||
|
}, [session?.user?.id, toast]);
|
||||||
|
|
||||||
|
// Delete selected emails
|
||||||
|
const deleteEmails = useCallback(async (emailIds: string[]) => {
|
||||||
|
if (emailIds.length === 0) return;
|
||||||
|
|
||||||
|
setIsDeleting(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/courrier/delete', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
emailIds,
|
||||||
|
folder: currentFolder
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to delete emails');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove the deleted emails from the list
|
||||||
|
setEmails(emails.filter(email => !emailIds.includes(email.id)));
|
||||||
|
|
||||||
|
// Clear selection if the selected email was deleted
|
||||||
|
if (selectedEmail && emailIds.includes(selectedEmail.id)) {
|
||||||
|
setSelectedEmail(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clear selected IDs
|
||||||
|
setSelectedEmailIds([]);
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: "Success",
|
||||||
|
description: `${emailIds.length} email(s) deleted`
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error deleting emails:', error);
|
||||||
|
|
||||||
|
toast({
|
||||||
|
variant: "destructive",
|
||||||
|
title: "Error",
|
||||||
|
description: "Failed to delete emails"
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setIsDeleting(false);
|
||||||
|
}
|
||||||
|
}, [emails, selectedEmail, currentFolder, toast]);
|
||||||
|
|
||||||
|
// Toggle selection of an email
|
||||||
|
const toggleEmailSelection = useCallback((emailId: string) => {
|
||||||
|
setSelectedEmailIds(prev => {
|
||||||
|
if (prev.includes(emailId)) {
|
||||||
|
return prev.filter(id => id !== emailId);
|
||||||
|
} else {
|
||||||
|
return [...prev, emailId];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Select all emails
|
||||||
|
const toggleSelectAll = useCallback(() => {
|
||||||
|
if (selectedEmailIds.length === emails.length) {
|
||||||
|
setSelectedEmailIds([]);
|
||||||
|
} else {
|
||||||
|
setSelectedEmailIds(emails.map(email => email.id));
|
||||||
|
}
|
||||||
|
}, [emails, selectedEmailIds]);
|
||||||
|
|
||||||
|
// Change the current folder
|
||||||
|
const changeFolder = useCallback((folder: MailFolder) => {
|
||||||
|
setCurrentFolder(folder);
|
||||||
|
setPage(1);
|
||||||
|
setSelectedEmail(null);
|
||||||
|
setSelectedEmailIds([]);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Search emails
|
||||||
|
const searchEmails = useCallback((query: string) => {
|
||||||
|
setSearchQuery(query);
|
||||||
|
setPage(1);
|
||||||
|
loadEmails();
|
||||||
|
}, [loadEmails]);
|
||||||
|
|
||||||
|
// Format an email for reply or forward
|
||||||
|
const formatEmailForAction = useCallback((email: Email, type: 'reply' | 'reply-all' | 'forward') => {
|
||||||
|
if (!email) return null;
|
||||||
|
|
||||||
|
return formatEmailForReplyOrForward(email, type);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Return all the functionality and state values
|
||||||
|
return {
|
||||||
|
// Data
|
||||||
|
emails,
|
||||||
|
selectedEmail,
|
||||||
|
selectedEmailIds,
|
||||||
|
currentFolder,
|
||||||
|
mailboxes,
|
||||||
|
isLoading,
|
||||||
|
isSending,
|
||||||
|
isDeleting,
|
||||||
|
error,
|
||||||
|
searchQuery,
|
||||||
|
page,
|
||||||
|
perPage,
|
||||||
|
totalEmails,
|
||||||
|
totalPages,
|
||||||
|
|
||||||
|
// Functions
|
||||||
|
loadEmails,
|
||||||
|
handleEmailSelect,
|
||||||
|
markEmailAsRead,
|
||||||
|
toggleStarred,
|
||||||
|
sendEmail,
|
||||||
|
deleteEmails,
|
||||||
|
toggleEmailSelection,
|
||||||
|
toggleSelectAll,
|
||||||
|
changeFolder,
|
||||||
|
searchEmails,
|
||||||
|
formatEmailForAction,
|
||||||
|
setPage,
|
||||||
|
setPerPage,
|
||||||
|
setSearchQuery,
|
||||||
|
};
|
||||||
|
};
|
||||||
Loading…
Reference in New Issue
Block a user