'use client'; import Link from 'next/link'; import { useParams, usePathname, useRouter } from 'next/navigation'; import { type User } from 'next-auth'; import { useEffect, useState } from 'react'; import { toast } from 'sonner'; import useSWR from 'swr'; import { InfoIcon, MoreHorizontalIcon, TrashIcon, } from '@/components/custom/icons'; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from '@/components/ui/alert-dialog'; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from '@/components/ui/dropdown-menu'; import { SidebarGroup, SidebarGroupContent, SidebarGroupLabel, SidebarMenu, SidebarMenuAction, SidebarMenuButton, SidebarMenuItem, useSidebar, } from '@/components/ui/sidebar'; import { Chat } from '@/db/schema'; import { fetcher, getTitleFromChat } from '@/lib/utils'; export function SidebarHistory({ user }: { user: User | undefined }) { const { setOpenMobile } = useSidebar(); const { id } = useParams(); const pathname = usePathname(); const { data: history, isLoading, mutate, } = useSWR>(user ? '/api/history' : null, fetcher, { fallbackData: [], }); useEffect(() => { mutate(); }, [pathname, mutate]); const [deleteId, setDeleteId] = useState(null); const [showDeleteDialog, setShowDeleteDialog] = useState(false); const router = useRouter(); const handleDelete = async () => { const deletePromise = fetch(`/api/chat?id=${deleteId}`, { method: 'DELETE', }); toast.promise(deletePromise, { loading: 'Deleting chat...', success: () => { mutate((history) => { if (history) { return history.filter((h) => h.id !== id); } }); return 'Chat deleted successfully'; }, error: 'Failed to delete chat', }); setShowDeleteDialog(false); if (deleteId === id) { router.push('/'); } }; if (!user) { return ( History
Login to save and revisit previous chats!
); } if (isLoading) { return ( History
{[44, 32, 28, 64, 52].map((item) => (
))}
); } if (history?.length === 0) { return ( History No chats found ); } return ( <> History {history && history.map((chat) => ( setOpenMobile(false)} > {getTitleFromChat(chat)} More { setDeleteId(chat.id); setShowDeleteDialog(true); }} > Delete ))} Are you absolutely sure? This action cannot be undone. This will permanently delete your chat and remove it from our servers. Cancel Continue ); }