diff --git a/app/courrier/page.tsx b/app/courrier/page.tsx index 56a8424b..5ac8a396 100644 --- a/app/courrier/page.tsx +++ b/app/courrier/page.tsx @@ -280,6 +280,10 @@ export default function CourrierPage() { // Handle mailbox change with prefetching const handleMailboxChange = (folder: string) => { + // Reset to page 1 when changing folders + setPage(1); + + // Change folder in the state changeFolder(folder); setCurrentView(folder); diff --git a/components/email/EmailList.tsx b/components/email/EmailList.tsx index a973bead..13c82983 100644 --- a/components/email/EmailList.tsx +++ b/components/email/EmailList.tsx @@ -44,8 +44,28 @@ export default function EmailList({ const [scrollPosition, setScrollPosition] = useState(0); const [searchQuery, setSearchQuery] = useState(''); const scrollRef = React.useRef(null); + const [emailsLength, setEmailsLength] = useState(emails.length); + const [isScrollingToTop, setIsScrollingToTop] = useState(false); - // Handle scroll to detect when user reaches the bottom + // Track changes in emails array to manage scrolling + React.useEffect(() => { + // If email count increased, we loaded more emails + if (emails.length > emailsLength) { + // If not loading more at the bottom, let's maintain scroll position + if (!isLoading && scrollRef.current && !isScrollingToTop) { + // This ensures the visible emails stay the same after loading more + setTimeout(() => { + if (scrollRef.current) { + scrollRef.current.scrollTop = scrollPosition; + } + }, 50); + } + } + // Update the emails length tracker + setEmailsLength(emails.length); + }, [emails, emailsLength, isLoading, scrollPosition]); + + // Handle scroll to detect when user reaches the bottom or scrolls up const handleScroll = (event: React.UIEvent) => { const target = event.target as HTMLDivElement; const { scrollTop, scrollHeight, clientHeight } = target; @@ -53,6 +73,9 @@ export default function EmailList({ // Save scroll position for restoration when needed setScrollPosition(scrollTop); + // Detect scrolling direction + setIsScrollingToTop(scrollTop < scrollPosition); + // If user scrolls near the bottom and we have more emails, load more if (scrollHeight - scrollTop - clientHeight < 200 && hasMoreEmails && !isLoading) { // Store current scroll data before loading more @@ -64,6 +87,13 @@ export default function EmailList({ } }; + // Add a function to scroll to top + const scrollToTop = () => { + if (scrollRef.current) { + scrollRef.current.scrollTop = 0; + } + }; + // Update title to show date sort order React.useEffect(() => { // Add a small indicator in the header to show emails are sorted by date @@ -165,8 +195,14 @@ export default function EmailList({ >
{/* Add a small note to show emails are sorted by date */} -
- Sorted by date (newest first) +
+ Sorted by date (newest first) +
{emails.map((email) => (