Neah/components/email/EmailList.tsx
2025-04-30 16:44:10 +02:00

226 lines
7.8 KiB
TypeScript

'use client';
import React, { useState, useEffect, useRef } from 'react';
import { Loader2, Mail, Search, X } from 'lucide-react';
import { Email } from '@/hooks/use-courrier';
import EmailListItem from './EmailListItem';
import EmailListHeader from './EmailListHeader';
import BulkActionsToolbar from './BulkActionsToolbar';
import { Input } from '@/components/ui/input';
interface EmailListProps {
emails: Email[];
selectedEmailIds: string[];
selectedEmail: Email | null;
currentFolder: string;
isLoading: boolean;
totalEmails: number;
hasMoreEmails: boolean;
onSelectEmail: (emailId: string, accountId: string, folder: string) => void;
onToggleSelect: (emailId: string) => void;
onToggleSelectAll: () => void;
onBulkAction: (action: 'delete' | 'mark-read' | 'mark-unread' | 'archive') => void;
onToggleStarred: (emailId: string) => void;
onLoadMore: () => void;
onSearch?: (query: string) => void;
}
export default function EmailList({
emails,
selectedEmailIds,
selectedEmail,
currentFolder,
isLoading,
totalEmails,
hasMoreEmails,
onSelectEmail,
onToggleSelect,
onToggleSelectAll,
onBulkAction,
onToggleStarred,
onLoadMore,
onSearch
}: EmailListProps) {
const [scrollPosition, setScrollPosition] = useState(0);
const [searchQuery, setSearchQuery] = useState('');
const listRef = useRef<HTMLDivElement>(null);
const isLoadingMoreRef = useRef(false);
// Reset loading state when isLoading changes
useEffect(() => {
if (!isLoading) {
isLoadingMoreRef.current = false;
}
}, [isLoading]);
// 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);
// Calculate how close to the bottom we are (in pixels)
const distanceToBottom = scrollHeight - scrollTop - clientHeight;
// Debug logging to help diagnose scrolling issues
console.log(`[EMAIL_LIST] Scroll metrics - scrollHeight: ${scrollHeight}, scrollTop: ${scrollTop}, clientHeight: ${clientHeight}, distanceToBottom: ${distanceToBottom}`);
// Only trigger if we have more emails, aren't already loading, and we're near the bottom
const LOAD_MORE_THRESHOLD = 400; // Increased threshold for more reliable loading
if (distanceToBottom < LOAD_MORE_THRESHOLD && hasMoreEmails && !isLoading && !isLoadingMoreRef.current) {
console.log(`[EMAIL_LIST] Near bottom (${distanceToBottom}px), loading more emails. hasMoreEmails: ${hasMoreEmails}, isLoading: ${isLoading}`);
isLoadingMoreRef.current = true; // Prevent multiple load more triggers
onLoadMore();
}
};
// Also check on component mount and email changes if we need to load more
useEffect(() => {
if (!listRef.current) return;
const checkScroll = () => {
const { scrollHeight, clientHeight } = listRef.current as HTMLDivElement;
// If the content doesn't fill the container, and we have more to load
if (scrollHeight <= clientHeight && hasMoreEmails && !isLoading && !isLoadingMoreRef.current) {
console.log("[EMAIL_LIST] Content doesn't fill container, loading more emails");
isLoadingMoreRef.current = true;
onLoadMore();
}
};
// Check after render and when emails change
requestAnimationFrame(checkScroll);
}, [emails, hasMoreEmails, isLoading, onLoadMore]);
// Handle search
const handleSearch = (e: React.FormEvent) => {
e.preventDefault();
onSearch?.(searchQuery);
};
const clearSearch = () => {
setSearchQuery('');
onSearch?.('');
};
// Render loading state
if (isLoading && emails.length === 0) {
return (
<div className="flex justify-center items-center h-full p-8 bg-white/95 backdrop-blur-sm">
<div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-blue-500"></div>
</div>
);
}
// Render empty state
if (emails.length === 0) {
return (
<div className="flex flex-col justify-center items-center h-64 p-8 text-center bg-white/95 backdrop-blur-sm">
<Mail className="h-8 w-8 text-gray-400 mb-2" />
<p className="text-gray-500 text-sm">
{searchQuery
? 'No emails match your search'
: currentFolder === 'INBOX'
? "Your inbox is empty. You're all caught up!"
: 'No emails in this folder'}
</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="w-[320px] bg-white/95 backdrop-blur-sm border-r border-gray-100 flex flex-col">
{/* Search header */}
<div className="border-b border-gray-100">
<div className="px-4 py-2">
<div className="relative">
<Search className="absolute left-2 top-2.5 h-4 w-4 text-gray-400" />
<form onSubmit={handleSearch}>
<Input
type="search"
placeholder="Search in folder..."
className="pl-8 h-9 bg-gray-50"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
{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-gray-400" />
</button>
)}
</form>
</div>
</div>
<EmailListHeader
allSelected={allSelected}
someSelected={someSelected}
onToggleSelectAll={onToggleSelectAll}
currentFolder={currentFolder}
totalEmails={totalEmails}
/>
</div>
{/* Only show bulk actions when emails are explicitly selected via checkboxes */}
{selectedEmailIds.length > 0 && (
<BulkActionsToolbar
selectedCount={selectedEmailIds.length}
onBulkAction={onBulkAction}
/>
)}
<div
ref={listRef}
className="flex-1 overflow-y-auto scroll-smooth"
onScroll={handleScroll}
>
<div className="divide-y divide-gray-100">
{emails.map((email) => (
<EmailListItem
key={email.id}
email={email}
isSelected={selectedEmailIds.includes(email.id)}
isActive={selectedEmail?.id === email.id}
onSelect={() => onSelectEmail(email.id, email.accountId || '', email.folder || '')}
onToggleSelect={(e: React.MouseEvent) => {
e.stopPropagation();
onToggleSelect(email.id);
}}
onToggleStarred={(e: React.MouseEvent) => {
e.stopPropagation();
onToggleStarred(email.id);
}}
/>
))}
{/* Make loading indicator more visible */}
{isLoading && (
<div className="flex items-center justify-center p-4 bg-gray-50">
<Loader2 className="h-5 w-5 text-blue-500 animate-spin mr-2" />
<span className="text-sm text-gray-600">Loading more emails...</span>
</div>
)}
{/* Visual indicator when all emails are loaded */}
{!hasMoreEmails && emails.length > 0 && (
<div className="p-3 text-center text-xs text-gray-500 bg-gray-50">
End of emails in this folder
</div>
)}
</div>
</div>
</div>
);
}