An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
Refactor: Improve chat history scroll handling and data fetching
Yoshiki Miura3cba724d0ad7
diff --git a/components/chat.tsx b/components/chat.tsxindex e46b06cb..c95173d3 100644--- a/components/chat.tsx+++ b/components/chat.tsx@@ -48,10 +48,8 @@ export function Chat({id},onFinish: () => {- router.replace(`/search/${id}`)- startTransition(() => {- router.refresh()- })+ window.history.replaceState({}, '', `/search/${id}`)+ window.dispatchEvent(new CustomEvent('chat-history-updated'))},onError: error => {toast.error(`Error in chat: ${error.message}`)diff --git a/components/clear-history.tsx b/components/clear-history.tsxindex 73dab643..19a4c605 100644--- a/components/clear-history.tsx+++ b/components/clear-history.tsx@@ -1,6 +1,5 @@'use client'-import { useState, useTransition } from 'react'import {AlertDialog,AlertDialogAction,@@ -14,6 +13,7 @@ import {} from '@/components/ui/alert-dialog'import { Button } from '@/components/ui/button'import { clearChats } from '@/lib/actions/chat'+import { useState, useTransition } from 'react'import { toast } from 'sonner'import { Spinner } from './ui/spinner'diff --git a/components/sidebar/chat-history-client.tsx b/components/sidebar/chat-history-client.tsxindex 8abb25ec..389e77f6 100644--- a/components/sidebar/chat-history-client.tsx+++ b/components/sidebar/chat-history-client.tsx@@ -6,32 +6,59 @@ import { useCallback, useEffect, useRef, useState, useTransition } from 'react'import { toast } from 'sonner'import { ChatHistorySkeleton } from './chat-history-skeleton'import { ChatMenuItem } from './chat-menu-item'+import { ClearHistoryAction } from './clear-history-action'-interface ChatHistoryClientProps {- initialChats: Chat[]- initialNextOffset: number | null-}+// interface ChatHistoryClientProps {} // Removed empty interfaceinterface ChatPageResponse {chats: Chat[]nextOffset: number | null}-export function ChatHistoryClient({- initialChats,- initialNextOffset-}: ChatHistoryClientProps) {- const [chats, setChats] = useState<Chat[]>(initialChats)- const [nextOffset, setNextOffset] = useState<number | null>(initialNextOffset)- const [isLoading, setIsLoading] = useState(false)+export function ChatHistoryClient() {+ // Removed props from function signature+ const [chats, setChats] = useState<Chat[]>([])+ const [nextOffset, setNextOffset] = useState<number | null>(null)+ const [isLoading, setIsLoading] = useState(true)const loadMoreRef = useRef<HTMLDivElement>(null)const [isPending, startTransition] = useTransition()- // Synchronize state with props when initial data changes (e.g., after router.refresh)+ const fetchInitialChats = useCallback(async () => {+ setIsLoading(true)+ try {+ const response = await fetch(`/api/chats?offset=0&limit=20`)+ if (!response.ok) {+ throw new Error('Failed to fetch initial chat history')+ }+ const { chats: newChats, nextOffset: newNextOffset } =+ (await response.json()) as ChatPageResponse++ setChats(newChats)+ setNextOffset(newNextOffset)+ } catch (error) {+ console.error('Failed to load initial chats:', error)+ toast.error('Failed to load chat history.')+ setNextOffset(null)+ } finally {+ setIsLoading(false)+ }+ }, [])++ useEffect(() => {+ fetchInitialChats()+ }, [fetchInitialChats])+useEffect(() => {- setChats(initialChats)- setNextOffset(initialNextOffset)- }, [initialChats, initialNextOffset])+ const handleHistoryUpdate = () => {+ startTransition(() => {+ fetchInitialChats()+ })+ }+ window.addEventListener('chat-history-updated', handleHistoryUpdate)+ return () => {+ window.removeEventListener('chat-history-updated', handleHistoryUpdate)+ }+ }, [fetchInitialChats])const fetchMoreChats = useCallback(async () => {if (isLoading || nextOffset === null) return@@ -40,19 +67,16 @@ export function ChatHistoryClient({try {const response = await fetch(`/api/chats?offset=${nextOffset}&limit=20`)if (!response.ok) {- throw new Error('Failed to fetch chat history')+ throw new Error('Failed to fetch more chat history')}const { chats: newChats, nextOffset: newNextOffset } =(await response.json()) as ChatPageResponse- startTransition(() => {- setChats(prevChats => [...prevChats, ...newChats])- setNextOffset(newNextOffset)- })+ setChats(prevChats => [...prevChats, ...newChats])+ setNextOffset(newNextOffset)} catch (error) {console.error('Failed to load more chats:', error)toast.error('Failed to load more chat history.')- // Optionally stop trying to load more if there's an errorsetNextOffset(null)} finally {setIsLoading(false)@@ -61,15 +85,15 @@ export function ChatHistoryClient({useEffect(() => {const observerRefValue = loadMoreRef.current- if (!observerRefValue || nextOffset === null) return+ if (!observerRefValue || nextOffset === null || isPending) returnconst observer = new IntersectionObserver(([entry]) => {- if (entry.isIntersecting && !isLoading) {+ if (entry.isIntersecting && !isLoading && !isPending) {fetchMoreChats()}},- { threshold: 0.1 } // Trigger when 10% visible+ { threshold: 0.1 })observer.observe(observerRefValue)@@ -79,31 +103,34 @@ export function ChatHistoryClient({observer.unobserve(observerRefValue)}}- }, [fetchMoreChats, nextOffset, isLoading])+ }, [fetchMoreChats, nextOffset, isLoading, isPending])++ const isHistoryEmpty = !isLoading && !chats.length && nextOffset === nullreturn (- <div className="flex-1 overflow-y-auto mb-2 relative">- {!chats?.length && !isLoading && nextOffset === null ? (- <div className="px-2 text-foreground/30 text-sm text-center py-4">- No search history- </div>- ) : (- <SidebarMenu>- {chats.map(- (chat: Chat) => chat && <ChatMenuItem key={chat.id} chat={chat} />- )}- </SidebarMenu>- )}-- {/* Sentinel Element */}- <div ref={loadMoreRef} style={{ height: '1px' }} />-- {/* Loading Skeleton/Spinner */}- {(isLoading || isPending) && (- <div className="py-2">- <ChatHistorySkeleton />- </div>- )}- </div>+ <>+ <div className="px-2 pb-1 pt-0 mt-[-8px] mb-1">+ <ClearHistoryAction empty={isHistoryEmpty} />+ </div>+ <div className="flex-1 overflow-y-auto mb-2 relative">+ {isHistoryEmpty && !isPending ? (+ <div className="px-2 text-foreground/30 text-sm text-center py-4">+ No search history+ </div>+ ) : (+ <SidebarMenu>+ {chats.map(+ (chat: Chat) => chat && <ChatMenuItem key={chat.id} chat={chat} />+ )}+ </SidebarMenu>+ )}+ <div ref={loadMoreRef} style={{ height: '1px' }} />+ {(isLoading || isPending) && (+ <div className="py-2">+ <ChatHistorySkeleton />+ </div>+ )}+ </div>+ </>)}diff --git a/components/sidebar/chat-history-section.tsx b/components/sidebar/chat-history-section.tsxindex 37d01833..ac765b45 100644--- a/components/sidebar/chat-history-section.tsx+++ b/components/sidebar/chat-history-section.tsx@@ -1,8 +1,5 @@import { SidebarGroup, SidebarGroupLabel } from '@/components/ui/sidebar'-import { getChatsPage } from '@/lib/actions/chat'-import { getCurrentUserId } from '@/lib/auth/get-current-user'import { ChatHistoryClient } from './chat-history-client'-import { ClearHistoryAction } from './clear-history-action'export async function ChatHistorySection() {const enableSaveChatHistory = process.env.ENABLE_SAVE_CHAT_HISTORY === 'true'@@ -10,19 +7,14 @@ export async function ChatHistorySection() {return null}- // Fetch the initial page of chats- const userId = await getCurrentUserId()- const { chats, nextOffset } = await getChatsPage(userId, 20, 0)-return (<div className="flex flex-col flex-1 h-full"><SidebarGroup><div className="flex items-center justify-between w-full"><SidebarGroupLabel className="p-0">History</SidebarGroupLabel>- <ClearHistoryAction empty={!chats?.length && !nextOffset} /></div></SidebarGroup>- <ChatHistoryClient initialChats={chats} initialNextOffset={nextOffset} />+ <ChatHistoryClient /></div>)}diff --git a/components/sidebar/chat-menu-item.tsx b/components/sidebar/chat-menu-item.tsxindex 9a36feb2..c95d8778 100644--- a/components/sidebar/chat-menu-item.tsx+++ b/components/sidebar/chat-menu-item.tsx@@ -98,8 +98,7 @@ export function ChatMenuItem({ chat }: ChatMenuItemProps) {if (isActive) {router.push('/')}- // Refresh data for the sidebar- router.refresh()+ window.dispatchEvent(new CustomEvent('chat-history-updated'))} catch (error) {console.error('Failed to delete chat:', error)toast.error((error as Error).message || 'Failed to delete chat')diff --git a/components/sidebar/clear-history-action.tsx b/components/sidebar/clear-history-action.tsxindex 4911bd95..f6b23f5b 100644--- a/components/sidebar/clear-history-action.tsx+++ b/components/sidebar/clear-history-action.tsx@@ -21,7 +21,6 @@ import { SidebarGroupAction } from '@/components/ui/sidebar'import { Spinner } from '@/components/ui/spinner'import { clearChats } from '@/lib/actions/chat'import { MoreHorizontal, Trash2 } from 'lucide-react'-import { useRouter } from 'next/navigation'import { useState, useTransition } from 'react'import { toast } from 'sonner'@@ -32,14 +31,13 @@ interface ClearHistoryActionProps {export function ClearHistoryAction({ empty }: ClearHistoryActionProps) {const [isPending, start] = useTransition()const [open, setOpen] = useState(false)- const router = useRouter()const onClear = () =>start(async () => {const res = await clearChats()res?.error ? toast.error(res.error) : toast.success('History cleared')setOpen(false)- router.refresh()+ window.dispatchEvent(new CustomEvent('chat-history-updated'))})return (