An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
Refactor: Align chat deletion UX with clear history and use Server Action. Unified the user experience for chat deletion to match the clear history functionality, including spinner behavior and dialog/menu interactions. Replaced API call for chat deletion with a direct call to the `deleteChat` Server Action. Removed the now-unused API endpoint for deleting individual chats.
Yoshiki Miuradfd80b2a7768
diff --git a/app/api/chat/[id]/route.ts b/app/api/chat/[id]/route.tsdeleted file mode 100644index 32757fb7..00000000--- a/app/api/chat/[id]/route.ts+++ /dev/null@@ -1,40 +0,0 @@-import { deleteChat } from '@/lib/actions/chat'-import { getCurrentUserId } from '@/lib/auth/get-current-user'-import { NextRequest, NextResponse } from 'next/server'--export async function DELETE(- request: NextRequest,- { params }: { params: Promise<{ id: string }> }-) {- const enableSaveChatHistory = process.env.ENABLE_SAVE_CHAT_HISTORY === 'true'- if (!enableSaveChatHistory) {- return NextResponse.json(- { error: 'Chat history saving is disabled.' },- { status: 403 }- )- }-- const chatId = (await params).id- if (!chatId) {- return NextResponse.json({ error: 'Chat ID is required' }, { status: 400 })- }-- const userId = await getCurrentUserId()-- try {- const result = await deleteChat(chatId, userId)-- if (result.error) {- const statusCode = result.error === 'Chat not found' ? 404 : 500- return NextResponse.json({ error: result.error }, { status: statusCode })- }-- return NextResponse.json({ ok: true })- } catch (error) {- console.error(`API route error deleting chat ${chatId}:`, error)- return NextResponse.json(- { error: 'Internal Server Error' },- { status: 500 }- )- }-}diff --git a/components/sidebar/chat-menu-item.tsx b/components/sidebar/chat-menu-item.tsxindex 209516bd..8cabead9 100644--- a/components/sidebar/chat-menu-item.tsx+++ b/components/sidebar/chat-menu-item.tsx@@ -22,11 +22,12 @@ import {SidebarMenuButton,SidebarMenuItem} from '@/components/ui/sidebar'+import { deleteChat } from '@/lib/actions/chat-db'import { Chat as DBChat } from '@/lib/db/schema'import { MoreHorizontal, Trash2 } from 'lucide-react'import Link from 'next/link'import { usePathname, useRouter } from 'next/navigation'-import { useState, useTransition } from 'react'+import { useCallback, useState, useTransition } from 'react'import { toast } from 'sonner'import { Spinner } from '../ui/spinner'@@ -79,35 +80,47 @@ export function ChatMenuItem({ chat }: ChatMenuItemProps) {const router = useRouter()const [isPending, startTransition] = useTransition()const [isMenuOpen, setIsMenuOpen] = useState(false)- const [dialogOpen, setDialogOpen] = useState(false)+ const [isAlertOpen, setIsAlertOpen] = useState(false)- const onDelete = () => {+ const handleDeleteChat = useCallback(() => {startTransition(async () => {- try {- const res = await fetch(`/api/chat/${chat.id}`, { method: 'DELETE' })-- if (!res.ok) {- const errorData = await res.json()- throw new Error(errorData.error || 'Failed to delete chat')- }+ const result = await deleteChat(chat.id)+ if (result?.success) {toast.success('Chat deleted')- setIsMenuOpen(false) // Close menu on success- setDialogOpen(false) // Close dialog on success-- // If deleting the currently active chat, navigate homeif (isActive) {router.push('/')}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')- setIsMenuOpen(false) // Close menu on error- setDialogOpen(false) // Close dialog on error+ } else if (result?.error) {+ toast.error(result.error)+ } else {+ toast.error('An unexpected error occurred while deleting the chat.')}+ setIsAlertOpen(false)+ setIsMenuOpen(false)})- }+ }, [chat.id, isActive, router, startTransition])++ const handleAlertOpenChange = useCallback(+ (open: boolean) => {+ setIsAlertOpen(open)+ if (!open && !isPending) {+ setIsMenuOpen(false)+ }+ },+ [isPending, setIsMenuOpen, setIsAlertOpen]+ )++ const handleMenuOpenChange = useCallback(+ (open: boolean) => {+ setIsMenuOpen(open)+ if (!open && !isPending) {+ setIsAlertOpen(false)+ }+ },+ [isPending, setIsMenuOpen, setIsAlertOpen]+ )return (<SidebarMenuItem>@@ -126,28 +139,20 @@ export function ChatMenuItem({ chat }: ChatMenuItemProps) {</Link></SidebarMenuButton>- <DropdownMenu open={isMenuOpen} onOpenChange={setIsMenuOpen}>+ <DropdownMenu open={isMenuOpen} onOpenChange={handleMenuOpenChange}><DropdownMenuTrigger asChild>- <SidebarMenuAction disabled={isPending} className="size-7 p-1 mr-1">- {isPending ? (- <div className="flex items-center justify-center size-full">- <Spinner />- </div>- ) : (- <MoreHorizontal size={16} />- )}+ <SidebarMenuAction className="size-7 p-1 mr-1">+ <MoreHorizontal size={16} /><span className="sr-only">Chat Actions</span></SidebarMenuAction></DropdownMenuTrigger><DropdownMenuContent side="right" align="start">- <AlertDialog open={dialogOpen} onOpenChange={setDialogOpen}>+ <AlertDialog open={isAlertOpen} onOpenChange={handleAlertOpenChange}><AlertDialogTrigger asChild><DropdownMenuItem- disabled={isPending}className="gap-2 text-destructive focus:text-destructive"onSelect={e => {e.preventDefault()- // Don't call onDelete directly, just open the dialog}}><Trash2 size={14} />@@ -168,7 +173,10 @@ export function ChatMenuItem({ chat }: ChatMenuItemProps) {</AlertDialogCancel><AlertDialogActiondisabled={isPending}- onClick={onDelete} // Call onDelete here+ onClick={event => {+ event.preventDefault()+ handleDeleteChat()+ }}className="bg-destructive text-destructive-foreground hover:bg-destructive/90">{isPending ? (diff --git a/lib/actions/chat-db.ts b/lib/actions/chat-db.tsindex 3de13c15..a544b359 100644--- a/lib/actions/chat-db.ts+++ b/lib/actions/chat-db.ts@@ -1,5 +1,6 @@'use server'+import { getCurrentUserId } from '@/lib/auth/get-current-user' // Import getCurrentUserIdimport * as chatDb from '@/lib/db/chat'import { type Chat as DBChat, type Message as DBMessage } from '@/lib/db/schema' // Import DB schema types@@ -19,13 +20,57 @@ export async function getChat(id: string, userId: string) {}// Clear all chats for a user-export async function clearChats(userId: string) {- return chatDb.clearChats(userId)+export async function clearChats(): Promise<{+ error?: string+ success?: boolean+}> {+ const userId = await getCurrentUserId() // Get userId on the server+ if (!userId) {+ return { error: 'User not authenticated' }+ }+ try {+ const result = await chatDb.clearChats(userId) // Call the db function+ if (result.error) {+ return { error: result.error }+ }+ return { success: true } // Indicate success+ } catch (error) {+ // This catch might be redundant if chatDb.clearChats handles its own errors and returns { error: ... }+ // However, it can catch unexpected errors during the call to chatDb.clearChats itself.+ console.error('Error in server action clearChats:', error)+ return { error: 'Failed to clear chats at server action level' }+ }}// Delete a single chat-export async function deleteChat(chatId: string, userId: string) {- return chatDb.deleteChat(chatId, userId)+export async function deleteChat(chatId: string): Promise<{+ error?: string+ success?: boolean+}> {+ const userId = await getCurrentUserId()+ if (!userId) {+ return { error: 'User not authenticated' }+ }+ try {+ const result = await chatDb.deleteChat(chatId, userId)+ // Assuming chatDb.deleteChat also returns a similar object or throws an error+ // If chatDb.deleteChat returns something else, this part needs adjustment+ if (result && 'error' in result && result.error) {+ return { error: result.error }+ }+ // If chatDb.deleteChat signifies success differently, adjust this condition+ // For example, if it returns the deleted chat or a count > 0 on success+ // For now, let's assume if no error, it's a success. Consider a more explicit success check.+ return { success: true }+ } catch (error: any) {+ console.error(+ `Error in server action deleteChat for chat ID ${chatId}:`,+ error+ )+ return {+ error: error.message || 'Failed to delete chat at server action level'+ }+ }}// Interface for chat metadata input from the client